๐Ÿ”ฅ JavaScript Variables Deep Dive โ€” var, let, and const

pushpesh kumarpushpesh kumar
3 min read

When working with JavaScript, understanding var, let, and const is fundamental. They may seem similar at first glance but behave differently under the hood. In this article, we'll explore everything you need to know about them, including scope, hoisting, redeclaration, reinitialization, and best practices.

๐ŸŒŽ Scope

var

  • Function-scoped.

  • Accessible anywhere within the enclosing function.

function test() {
  if (true) {
    var x = 10;
  }
  console.log(x); // 10
}

let and const

  • Block-scoped.

  • Accessible only within the block {} they are defined in.

function test() {
  if (true) {
    let y = 20;
    const z = 30;
  }
  console.log(y); // ReferenceError
  console.log(z); // ReferenceError
}

โšก Hoisting

var

  • Hoisted to the top of its scope and initialized as undefined.
console.log(a); // undefined
var a = 5;

let and const

  • Hoisted but not initialized.

  • Exist in the Temporal Dead Zone (TDZ) until their declaration is evaluated.

console.log(b); // ReferenceError
let b = 10;

console.log(c); // ReferenceError
const c = 15;

๐Ÿ”„ Redeclaration

var

  • Can be redeclared within the same scope.
var x = 1;
var x = 2; // No error

let and const

  • Cannot be redeclared in the same scope.
let y = 1;
// let y = 2; // SyntaxError

const z = 1;
// const z = 2; // SyntaxError

๐Ÿ” Reinitialization

var and let

  • Can be reassigned.
var a = 5;
a = 10;

let b = 15;
b = 20;

const

  • Cannot be reassigned after initialization.
const c = 25;
// c = 30; // TypeError

๐ŸŒ€ Global object property

When declared in the global scope:

  • var creates a property on the global window object (in browsers).

  • let and const do not.

var a = 1;
let b = 2;
const c = 3;

console.log(window.a); // 1
console.log(window.b); // undefined
console.log(window.c); // undefined

๐Ÿ’ก Best Practices

  • โœ… Prefer const by default. It prevents accidental reassignment.

  • โœ… Use let when you know the variable will change.

  • โŒ Avoid var in modern code unless needed for legacy support.

๐Ÿงพ Summary Table

Featurevarletconst
ScopeFunctionBlockBlock
HoistedYes (init as undefined)Yes (TDZ)Yes (TDZ)
RedeclareYesNoNo
ReassignYesYesNo
Global propYesNoNo

โœ… Conclusion

Understanding the subtle but important differences between var, let, and const helps you write safer, clearer, and more modern JavaScript code. Embrace const and let, and reserve var for very specific cases where its function-scoping behavior is required.

0
Subscribe to my newsletter

Read articles from pushpesh kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

pushpesh kumar
pushpesh kumar