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.
console.log(a); // undefined
var a = 10;
console.log(a); // 10Explanation: During compilation, JS "hoists"
var a;, but does not assigna = 10;. So at the moment of the firstconsole.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:
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:
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:
sayHello(); // ReferenceError
const sayHello = function() {
console.log('Hello!');
};In short: what happens when you use a variable before its declaration
| Declaration type | Can it be used before declaration? | What happens |
|---|---|---|
var | Yes, but the value will be undefined | No error, but often a source of bugs |
let | No | ReferenceError (temporal dead zone) |
const | No | ReferenceError (temporal dead zone) |
function declaration | Yes | The function is fully available |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.