Sobes.tech
Junior

What is the difference between var, let, and const?

sobes.tech AI

Answer from AI

var has function scope, while let and const have block scope. var can be redeclared and reassigned, let can be reassigned but not redeclared in the same scope, and const cannot be redeclared or reassigned. Variables declared with var are hoisted with an initial value of undefined, while let and const are hoisted but remain in the "temporal dead zone" until initialized.

// var has function scope
function exampleVar() {
  if (true) {
    var x = 10;
    console.log(x); // 10
  }
  console.log(x); // 10 (x is visible here)
}

// let and const have block scope
function exampleLetConst() {
  if (true) {
    let y = 20;
    const z = 30;
    console.log(y); // 20
    console.log(z); // 30
  }
  // console.log(y); // Error: ReferenceError: y is not defined
  // console.log(z); // Error: ReferenceError: z is not defined
}

// var can be redeclared and reassigned
var a = 1;
var a = 2; // Redeclaration
a = 3; // Reassignment
console.log(a); // 3

// let can be reassigned but not redeclared in the same scope
let b = 4;
// let b = 5; // Error: SyntaxError: Identifier 'b' has already been declared
b = 6; // Reassignment
console.log(b); // 6

// const cannot be reassigned or redeclared
const c = 7;
// const c = 8; // Error: SyntaxError: Identifier 'c' has already been declared
// c = 9; // Error: TypeError: Assignment to constant variable.
console.log(c); // 7 (for primitive types)

// Hoisting
console.log(hoistedVar); // undefined (var is hoisted and initialized to undefined)
var hoistedVar = "I am var";

// console.log(hoistedLet); // Error: ReferenceError: Cannot access 'hoistedLet' before initialization
// let hoistedLet = "I am let"; // In the temporal dead zone

Key differences summarized in the table:

Feature var let const
Scope Function scope Block scope Block scope
Redeclaration Yes No (in the same scope) No
Reassignment Yes Yes No (for primitives)
Hoisting Yes (with undefined) Yes (in temporal dead zone) Yes (in temporal dead zone)
Initialization Not required Not required Must be initialized

It is important to note that for objects and arrays declared with const, the variable itself cannot be reassigned to another object/array, but the contents of the object/array can be modified.

const myObject = { key: 'value' };
// myObject = { newKey: 'newValue' }; // Error: TypeError: Assignment to constant variable.
myObject.key = 'newValue'; // Possible
console.log(myObject); // { key: 'newValue' }

const myArray = [1, 2];
// myArray = [3, 4]; // Error: TypeError: Assignment to constant variable.
myArray.push(3); // Possible
console.log(myArray); // [ 1, 2, 3 ]
What is the difference between var, let, and const… - sobes.tech