Junior
What is the difference between var and const?
sobes.tech AI
Answer from AI
var is declared globally or at the function level, can be overridden and reassigned. const is block-scoped, cannot be reassigned, but for objects and arrays, their contents can be modified.
| Characteristic | var |
const |
|---|---|---|
| Scope | Function or global | Block ({}) |
| Reassignment | Yes | No |
| Redeclaration | Yes | No in the same scope |
| Initialization | Optional | Mandatory at declaration |
| Hoisting | Declaration and initialization (with undefined) are hoisted |
Hoisted but without initialization (TDZ) |
// var
var x = 10;
console.log(x); // 10
x = 20;
console.log(x); // 20
var x = 30; // Redeclaration is possible
console.log(x); // 30
function testVar() {
var y = 5;
console.log(y); // 5
}
testVar();
// console.log(y); // ReferenceError: y is not defined
if (true) {
var z = 100;
}
console.log(z); // 100 (var does not have block scope)
// const
const a = 10;
console.log(a); // 10
// a = 20; // TypeError: Assignment to constant variable.
const obj = { name: 'Alice' };
console.log(obj.name); // Alice
obj.name = 'Bob'; // The contents of a const object can be changed
console.log(obj.name); // Bob
// obj = { name: 'Charlie' }; // TypeError: Assignment to constant variable.
if (true) {
const b = 200;
console.log(b); // 200
}
// console.log(b); // ReferenceError: b is not defined (const has block scope)
// Hoisting
console.log(hoistedVar); // undefined
var hoistedVar = 1;
// console.log(hoistedConst); // ReferenceError: Cannot access 'hoistedConst' before initialization (TDZ)
const hoistedConst = 2;