Skip to main content

Scope with var | let | const

1. Scope

KeywordScope
varFunction scope
let, constBlock 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.

KeywordHoistedCan it be used before declaration?
varyesyes, but undefined
let, constyesno (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

KeywordCan it be redeclared?
varYes (overwrites the value)
let, constNo (SyntaxError)

Example

javascript
var x = 1; var x = 2; // allowed console.log(x); // 2 let y = 1; let y = 2; // SyntaxError

4. Reassigning a value

KeywordCan the value be changed?
varYes
letYes
constNo (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 reassigned

5. 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

KeywordWhen to use
letFor values that change
constBy default - always (unless the reference needs to change)
varNever (only to support legacy code)

SUMMARY

Propertyvarletconst
ScopeFunctionBlockBlock
HoistedYesYesYes
Use before declarationundefinedError (TDZ)Error (TDZ)
RedeclarationYesNoNo
ReassignmentYesYesNo
Modern standardLegacyRecommendedDefault

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.