Scope with var | let | const
1. Scope
| Keyword | Scope |
|---|---|
var | Function scope |
let, const | Block scope |
Function scope - the variable is visible throughout the whole function where it is declared, regardless of the {} block.
Block scope - the variable is visible only inside the block { ... } where it is declared.
Example
javascript
function test() {
if (true) {
var x = 1;
let y = 2;
const z = 3;
}
console.log(x); // 1
console.log(y); // ReferenceError
console.log(z); // ReferenceError
}
test();x is accessible because var "ignores" the if block and is hoisted to the function level.
y and z are visible only inside the if.
2. Hoisting
All variables are hoisted, but they behave differently.
| Keyword | Hoisted | Can it be used before declaration? |
|---|---|---|
var | yes | yes, but undefined |
let, const | yes | no (error due to TDZ - temporal dead zone) |
Example with var
javascript
console.log(a); // undefined
var a = 10;JS hoists the declaration var a,
but not the assignment (a = 10).
Example with let and const
javascript
console.log(b); // ReferenceError
let b = 20;Although b is hoisted, it is in the "temporal dead zone" (TDZ)
- from the start of the scope until the actual declaration.
3. Redeclaration
| Keyword | Can it be redeclared? |
|---|---|
var | Yes (overwrites the value) |
let, const | No (SyntaxError) |
Example
javascript
var x = 1;
var x = 2; // allowed
console.log(x); // 2
let y = 1;
let y = 2; // SyntaxError4. Reassigning a value
| Keyword | Can the value be changed? |
|---|---|
var | Yes |
let | Yes |
const | No (but the object inside it can be mutated) |
Example
javascript
let name = 'Tim';
name = 'Oleh'; // allowed
const user = { name: 'Tim' };
user.name = 'Oleh'; // the object can be mutated
user = {}; // TypeError - the reference cannot be reassigned5. Example showing all the differences
javascript
function demo() {
console.log(a); // undefined
// console.log(b); // ReferenceError
// console.log(c); // ReferenceError
var a = 1;
let b = 2;
const c = 3;
if (true) {
var a = 10; // the same variable!
let b = 20; // a new variable
const c = 30; // a new variable
console.log(a, b, c); // 10 20 30
}
console.log(a, b, c); // 10 2 3
}
demo();var a "leaked" out of the block,
while let and const created their own local variables inside the block.
6. Where to use what
| Keyword | When to use |
|---|---|
let | For values that change |
const | By default - always (unless the reference needs to change) |
var | Never (only to support legacy code) |
SUMMARY
| Property | var | let | const |
|---|---|---|---|
| Scope | Function | Block | Block |
| Hoisted | Yes | Yes | Yes |
| Use before declaration | undefined | Error (TDZ) | Error (TDZ) |
| Redeclaration | Yes | No | No |
| Reassignment | Yes | Yes | No |
| Modern standard | Legacy | Recommended | Default |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.