Skip to main content

Variable before declaration

1. It all starts with hoisting

Before running the code, JavaScript goes through an initialization stage, where variable and function declarations "rise" to the top of their scope.

This means the engine knows a variable exists in advance, but its value is assigned later, at the moment the line of code executes.


2. Different kinds of declarations behave differently

var

Variables declared with var hoist and get initialized with the value undefined.

javascript
console.log(a); // undefined var a = 10; console.log(a); // 10

Explanation: During compilation, JS "hoists" var a;, but does not assign a = 10;. So at the moment of the first console.log(a), the variable already exists but is not yet initialized.


let and const

Variables declared with let and const also hoist, but they land in the "temporal dead zone" (TDZ), the period from the start of the scope to the line of declaration.

Trying to access them before declaration will cause an error:

javascript
console.log(b); // ReferenceError: Cannot access 'b' before initialization let b = 20; console.log(c); // ReferenceError const c = 30;

Before the line let b = 20;, the variable exists logically, but access to it is forbidden - this is a safeguard against errors.


function

Functions declared as a function declaration hoist completely, body included:

javascript
sayHi(); // "Hi!" function sayHi() { console.log('Hi!'); }

That's why they can be called before their declaration.

But if a function is declared as a function expression (via const, let, var), its behavior will depend on the variable type:

javascript
sayHello(); // ReferenceError const sayHello = function() { console.log('Hello!'); };

In short: what happens when you use a variable before its declaration

Declaration typeCan it be used before declaration?What happens
varYes, but the value will be undefinedNo error, but often a source of bugs
letNoReferenceError (temporal dead zone)
constNoReferenceError (temporal dead zone)
function declarationYesThe function is fully available

Short Answer

Interview ready
Premium

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