📦

How to Declare Variables in JavaScript

JavaScriptBeginner

Learn var, let, and const for variable declarations.

Code Example

JavaScript
// Using var (function-scoped, avoid in modern JS)
var oldWay = "I'm old";
console.log(oldWay);

// Using let (block-scoped, reassignable)
let count = 0;
count = 1;
console.log(count);

// Using const (block-scoped, not reassignable)
const PI = 3.14159;
console.log(PI);

// Block scoping
if (true) {
  let blockScoped = "I'm only here";
  const alsoBlockScoped = "Me too";
  console.log(blockScoped);
}
// console.log(blockScoped); // Error!

// Const with objects and arrays
const user = { name: "Alice" };
user.name = "Bob"; // OK - modifying property
console.log(user);

const numbers = [1, 2, 3];
numbers.push(4); // OK - modifying array
console.log(numbers);

// user = {}; // Error! Can't reassign const

// Hoisting
console.log(hoisted); // undefined (not error)
var hoisted = "I'm hoisted";

// console.log(notHoisted); // Error!
let notHoisted = "I'm not hoisted";

Explanation

Use const by default, let when you need to reassign. Avoid var. const prevents reassignment but objects/arrays can still be modified.

Related Tutorials