Junior
What are the ways to declare variables in JavaScript? Name the differences between these methods.
sobes.tech AI
Answer from AI
In JavaScript, variables can be declared in three ways: var, let, const.
Differences between them:
| Difference | var |
let |
const |
|---|---|---|---|
| Scope | Function scope | Block scope | Block scope |
| Redeclaration | Possible | Possible | Not possible |
| Reassignment | Possible | Possible | Not possible |
| Hoisting | Hoists declaration and initialization to undefined |
Hoists declaration but not initialization | Hoists declaration but not initialization |
Examples:
// var
function exampleVar() {
var x = 10; // Function scope
if (true) {
var x = 20; // Redeclaration possible within the same function
console.log(x); // 20
}
console.log(x); // 20 (the x from if is accessible here)
}
console.log(x); // Error: ReferenceError: x is not defined (x is not visible outside the function)
// Hoisting var
console.log(a); // undefined
var a = 5;
console.log(a); // 5
// let
function exampleLet() {
let y = 10; // Block scope
if (true) {
let y = 20; // Cannot redeclare within the same block
console.log(y); // 20 (different y variable)
}
console.log(y); // 10 (y outside the block)
}
console.log(y); // Error: ReferenceError: y is not defined
// Hoisting let
// console.log(b); // Error: ReferenceError: Cannot access 'b' before initialization
let b = 5;
console.log(b); // 5
// const
function exampleConst() {
const z = 10; // Block scope
// z = 20; // Error: TypeError: Assignment to constant variable. (Reassignment not allowed)
if (true) {
const z = 20; // Cannot redeclare within the same block
console.log(z); // 20 (different z variable)
}
console.log(z); // 10 (z outside the block)
}
console.log(z); // Error: ReferenceError: z is not defined
// Hoisting const
// console.log(c); // Error: ReferenceError: Cannot access 'c' before initialization
const c = 5;
console.log(c); // 5
// For objects and arrays declared with const, contents can be modified
const obj = { name: 'Test' };
obj.name = 'New Test'; // Allowed
// obj = { name: 'Another Test' }; // Error