If you were to try to console.log something traditionally, you would do something like this.
var example = “It works!”
Let’s say you wanted to hoist the declaration. What would that look like?
example = “It works!”
If you ran this in your code, what do you think would happen?
The statement gets printed but you get undefined at first! Let’s go over why that happens. We’ve seen the statement get printed but why? The reason we get undefined instead of a huge error that prevents us the statement even printing is because the compiler acknowledges that the variable exists but it wasn’t assigned a value yet.
You may have noticed I also used
var! Why is that, considering that most people avoid it ever since
const were created. There’s a specific reason for that and you may have guessed it. Although
const are hoisted in their declaration, hoisting differs between all three.
This has to do with initialization. While variable declarations and function declarations are hoisted, initialization is not. There are times in which
let declarations are hoisted but I would advise the person to be careful. However with
const, you will definitely get a reference error.
var declarations can also be accessible even outside the scope they’re used in because they are function-scoped and not block scoped unlike
In summation, I would advise anyone to hoist at their own risk. I’ve provided some links down below for information. Feel free to check them out!
Hoisting is a term you will not find used in any normative specification prose prior to ECMAScript® 2015 Language…