Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Notes › JavaScript

Hoisting, var, let and const in JavaScript

Execution context in two phases

Before running a script or function, JavaScript does a creation phase: it sets up memory for every variable and function declaration. Then the execution phase runs the code line by line. Using things before their line works (or doesn't) because of what happened in the creation phase — this is called hoisting.

What gets hoisted, and how

Declaration Hoisted? Value before its line
function f() {} ✅ fully the whole function — can be called early
var x ✅ undefined
let x / const x ✅ but uninitialised ReferenceError (temporal dead zone)
class C {} ✅ but uninitialised ReferenceError
const f = () => {} / function expression like let/const/var not callable early
sayHi();                 // "Hi" — function declarations are hoisted completely
function sayHi() { console.log("Hi"); }

console.log(a);          // undefined — var is hoisted and set to undefined
var a = 5;

console.log(b);          // ReferenceError: Cannot access 'b' before initialization
let b = 10;

greet();                 // TypeError: greet is not a function (it is undefined)
var greet = function () {};

Temporal Dead Zone (TDZ)

The time from the start of a block until the let/const line runs. Touching the variable in the TDZ throws a ReferenceError. This catches bugs that var would hide.

{
  // TDZ for x starts here
  console.log(typeof x);   // ReferenceError (even typeof!)
  let x = 1;               // TDZ ends
}

var vs let vs const

var let const
Scope function block block
Re-declare in the same scope ✅ ❌ ❌
Re-assign ✅ ✅ ❌
Hoisting undefined TDZ TDZ
Global var becomes window.x ✅ ❌ ❌
Must be initialised no no yes
const user = { name: "Asha" };
user.name = "Ravi";      // ✅ allowed — the object is mutable
user = {};               // ❌ TypeError — the binding can't change
Object.freeze(user);     // makes the object itself (shallowly) unchangeable

Shadowing

An inner variable with the same name hides the outer one.

let x = 1;
{ let x = 2; console.log(x); }   // 2
console.log(x);                  // 1

Shadowing a let with var in an inner block of the same function is an error ("illegal shadowing").

Function declaration vs expression vs arrow

function a() {}             // declaration — hoisted, has its own `this`
const b = function () {};   // expression — not callable before this line
const c = () => {};         // arrow — not hoisted, no own `this`/`arguments`

Best practices

Interview one-liners

More JavaScript notes