Hoisting isn't even REAL!!!

Hoisting isn't even REAL!!!

One of the most famous interview topics - HOISTING, isn't even real.

Yes, you heard that right.

The word 'hoist' wasn't even used in the official ECMAScript specifications until the year 2015. It was first mentioned in the ECMAScript 6 specification, which was published in June of that year.

DEFINITION

If you search on Google, this is what you get

JavaScript Hoisting refers to the process whereby the interpreter appears to move the declaration of functions, variables or classes to the top of their scope, before the execution of the code. Hoisting is not a term normatively defined in the ECMAScript specification.

Please refer to it here.

And even there they've correctly mentioned that Hoisting is not a term normatively defined in the ECMAScript specification.

MISINFORMATION

shinobi;
sensei;
var shinobi = 'naruto';    // line 3
var sensei = 'kakashi';    // line 4

So, based on the definition of hoisting, JS should be able to anticipate all variable declarations, as seen in lines 3 and 4, regardless of their position within the scope and move them to the top of the scope before the code execution begins.

Something like this:

// before execution
var shinobi;
var sensei;

shinobi;
sensei;
shinobi = 'naruto';
sensei = 'kakashi';

Which is not what happens.

JavaScript doesn't move things around the way we might expect it to. Because how would it magically be able to look ahead & find only the declarations in the very first pass?

To be able to do that, you would need to perform complex processing on later tokens in the code block until reaching its end. And theoretically extract any declarations if any are encountered and move them to the top. And guess what that magical processing's called - PARSING!

So, Hoisting is just a shorthand, a convenient explanation to describe this magical behavior without getting into the nitty-gritty details.

REASON

All this misunderstanding occurs because JS execution is a 2-pass process i.e. parsing/compilation & execution. But people tend to think of JS execution as one pass process rather than two.

If you think of it as 2 passes. You can easily explain this magical behavior with the help of Lexical Scope.

Unfortunately, I can't cover it now because of the vastness of the topic but you may refer this as the best resource.