Hoisting in JS

Hoisting in JS

Javascript behaves differently in some scenarios when compared to other programming languages and Hoisting is one of the scenarios.

Just look at the below code and observe if it will throw any errors.

console.log(greet);
// ???? -- Undefined
var greet = 'Hello! Everyone';
console.log(greet);
// Hello! Everyone

If you have been around programming languages other than JS then this would potentially throw an error. But it doesn't throw any error and executes successfully and logs undefined and Hello! Everyone. If you have been around Javascript for the first time you might be thinking that using a variable before it is declared is unethical and not allowed but... how does it work without any error? Wait all your questions would be answered but first, lets try to execute the same in Python and note down the observation.

print(greet);
# NameError: name 'greet' is not defined
greet = 'Hello! Everyone';
print(greet);

So you might be thinking that how is this even possible? The same code when executed in Javascript work seamlessly but in Python throws an error.

Want to know the why? It's due to Hoisting.

What is Hoisting???

Formally, 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, prior to the execution of the code*.*

So no matter where you declare your variable in the Javascript program they are automatically moved to the top of their scope.

All variables declared through var, let, and const are hoisted. The rule of thumb to remember is that variables declared through var are hoisted + auto-initialized to undefined and variables declared through let and const are only auto-registered.

var -> hoisted + auto-initialized to undefined.
let and const -----> hoisted + auto-registered but not auto-initialized.

That is the reason why the below code when executed doesn't throw any error and logs undefined and Hello! Everyone.

console.log(greet);
// undefined
var greet = 'Hello! Everyone';
console.log(greet);
// Hello! Everyone

But... when we execute the same program using the let and const convention it throws an error.

console.log(greet);
// Not Defined TDZ(Temporal Dead Zone Error)
let greet = 'Hello! Everyone';
console.log(greet);
// Hello! Everyone

You might be wondering what's the case right here. Are let and const variables not hoisted? The answer is no they are hoisted but do you remember the rule of thumb for let and const type declarations that I mentioned earlier they are hoisted+auto-registered but not auto-initialized therefore it throws a Temporal Dead Zone Error.

Temporal Dead Zone (TDZ) error occurs in let and const types declaration and we will be covering Temporal Dead Zone(TDZ) in-depth and a few best practices to avoid it in our next article. Till then explore Hoisting and try a few examples on your own to get a better understanding of the same.