1

I am studying hoisting concept now, but i cannot understand why hoisting can only work on declaration, not initialization.

declaration O

catName("cat");

function catName(name){
  console.log(name) // return cat
}

initialization X

console.log(num); // return undefined
var num;
num = 6;
2

1 Answer 1

1

...why hoisting can only work on declaration, not initialization

It can work with initialization (and in fact, that var variable is initialized — with the value undefined), it's just that hoisting the initializer expression is not defined for var. Hoisting initialization is defined for function declarations: The binding (loosely, variable) for the function is both declared and initialized with the function object:

console.log(example); // Shows the function

function example() {
}

It's just that that's not how var is defined, not least because hoisting the initialization expression (rather than undefined) would be much more complicated than hoisting the initialization of a function identifier, because var initializers can be any arbitrary expression. So instead, var variables are initialized with undefined.

Fast-forward several years and the initialization of let, const, and class aren't hoisted at all (only the declaration), leading us to the Temporal Dead Zone between declaration and initialization during which you can't access them, because that was deemed more useful than hoisting undefined:

console.log(example); // ReferenceError

let example = 42;

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.