DEV Community

mahammadmansur95
mahammadmansur95

Posted on

Js interview #1 : var, let, and const in JavaScript – What's the Difference?

In JavaScript, variables can be declared using var, let, or const. Though they all serve the same fundamental purpose—declaring variables—they behave quite differently in terms of scope, hoisting, reassignment, and more.

Let’s break down their key differences.

🔁 1. Scope: Global, Function, and Block

Feature var let const
Scope type Function-scoped Block-scoped Block-scoped

👉 var – Function Scope

Variables declared with var are function-scoped, which means they are only accessible inside the function in which they are defined.

function example() {
  if (true) {
    var x = 10;
  }
  console.log(x); // ✅ 10 - accessible because var is function-scoped
}
Enter fullscreen mode Exit fullscreen mode

👉 let and const – Block Scope

Both let and const are block-scoped, meaning they only exist within the enclosing {} block.

function example() {
  if (true) {
    let y = 20;
    const z = 30;
  }
  console.log(y); // ❌ ReferenceError
  console.log(z); // ❌ ReferenceError
}
Enter fullscreen mode Exit fullscreen mode

📦 2. Hoisting Behavior

👉 var is hoisted and initialized.

console.log(a); // ✅ undefined
var a = 5;
Enter fullscreen mode Exit fullscreen mode

👉 let and const are hoisted but not initialized

console.log(b); // ❌ ReferenceError (TDZ)
let b = 10;
Enter fullscreen mode Exit fullscreen mode

🔁 3. Redeclaration & Reassignment

👉 var allows redeclaration and reassignment

var x = 1;
var x = 2; // ✅ No error
x = 3;     // ✅ No error
Enter fullscreen mode Exit fullscreen mode

👉 let allows reassignment but not redeclaration

let y = 1;
let y = 2; // ❌ SyntaxError
y = 3;     // ✅ Allowed
Enter fullscreen mode Exit fullscreen mode

👉 const allows neither

const z = 1;
const z = 2; // ❌ SyntaxError
z = 3;       // ❌ TypeError
Enter fullscreen mode Exit fullscreen mode

⛔ 4. Temporal Dead Zone (TDZ)

The Temporal Dead Zone (TDZ) is the period between entering the scope and the actual declaration where variables declared with let and const cannot be accessed.

function test() {
  console.log(a); // ❌ ReferenceError (TDZ)
  let a = 10;
}
Enter fullscreen mode Exit fullscreen mode

With var, accessing the variable before the declaration just returns undefined, but with let and const, it throws an error due to the TDZ.

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.