JavaScript: var, let & const

When working with JavaScript, you must know the differences between var, let, and const. These keywords declare variables but differ in scope, hoisting, and mutability. Let’s understand them:

var

  • Scope: Function-scoped, accessible within the function where it’s declared.
  • Hoisting: Hoisted to the top of their scope with undefined as the initial value.
  • Redeclaration: Can be redeclared in the same scope.
console.log(x); // undefined (hoisting)
var x = 10;
if (true) {
    var y = 20;
}
console.log(y); // 20 (function-scoped)

let

  • Scope: Block-scoped, limited to the block where it’s declared.
  • Hoisting: Hoisted but in a "temporal dead zone" until declared.
  • Redeclaration: Cannot be redeclared in the same scope.
let a = 30;
if (true) {
    let b = 40;
    console.log(b); // 40
}
// console.log(b); // ReferenceError (block-scoped)

const

  • Scope: Block-scoped, like let.
  • Hoisting: Hoisted but in a "temporal dead zone" until declared.
  • Immutability: Cannot be reassigned, though object contents can be mutated.
  • Redeclaration: Cannot be redeclared in the same scope.
const PI = 3.14;
const colors = ['red', 'green'];
colors.push('blue'); // Allowed (mutating array)
console.log(colors); // ['red', 'green', 'blue']

Key Points

  • Use var only for legacy code.
  • Use let for variables that can be reassigned.
  • Use const for variables that shouldn’t be reassigned.

By using let and const, you can write cleaner and easier-to-understand JavaScript!


Leave a Reply

Your email address will not be published. Required fields are marked *