Explain the difference between var, let, and const in JavaScript.

clock icon

Asked 1 year ago

message icon

1

eye icon

13

As I’ve been learning modern JavaScript (ES6 and beyond), I frequently come across three different ways of declaring variables: var, let, and const.

1 Answer

✅ 1. var – The Old Way

  • Scope: Function-scoped If you declare a variable using var inside a function, it's only accessible inside that function. If it's inside a block (like an if or for), it’s still accessible outside that block.
1function example() {
2 if (true) {
3 var x = 10;
4 }
5 console.log(x); // 10 – accessible outside the block!
6}
1function example() {
2 if (true) {
3 var x = 10;
4 }
5 console.log(x); // 10 – accessible outside the block!
6}
  • Hoisting: Variables declared with var are hoisted to the top of their scope and initialized as undefined.
1console.log(a); // undefined
2var a = 5;
1console.log(a); // undefined
2var a = 5;
  • Re-declaration: You can re-declare the same variable in the same scope without error.
1var name = 'Alice';
2var name = 'Bob'; // Allowed
1var name = 'Alice';
2var name = 'Bob'; // Allowed

✅ 2. let – Block Scoped

  • Scope: Block-scoped Meaning it's only accessible within the {} block it’s declared in.
1if (true) {
2 let y = 20;
3}
4console.log(y); // ReferenceError
1if (true) {
2 let y = 20;
3}
4console.log(y); // ReferenceError
  • Hoisting: Yes, but not initialized. Accessing before declaration gives a ReferenceError (Temporal Dead Zone).
1console.log(b); // ReferenceError
2let b = 10;
1console.log(b); // ReferenceError
2let b = 10;
  • Re-declaration: Not allowed in the same scope.
1let name = 'Alice';
2let name = 'Bob'; // SyntaxError
3
1let name = 'Alice';
2let name = 'Bob'; // SyntaxError
3

✅ 3. const – Constant Variables

  • Scope: Block-scoped (same as let)
  • Must be initialized when declared.
  • Cannot be re-assigned after the initial assignment.
1const z = 30;
2z = 40; // ❌ TypeError
1const z = 30;
2z = 40; // ❌ TypeError
  • Mutability: If the value is an object or array, its contents can still be modified — only the binding is constant.
1const arr = [1, 2, 3];
2arr.push(4); // Allowed
3arr = [5, 6]; // Not allowed
1const arr = [1, 2, 3];
2arr.push(4); // Allowed
3arr = [5, 6]; // Not allowed

1

Write your answer here

Top Questions