JavaScript is full of Strange Features, Every day I discover something new that change my understanding of the whole language. This is why I love JS.
But sometimes understanding these strange concepts are quite frustrating and you may feel lost, don't worry it happens with all of us and whenever you get familiar with these concepts it becomes 'aha...!' movement for you.
Now Without wasting time, let's get into it.
Consider this snippet of code.
a = 2;
var a;
console.log(a);
What do you think? What will be the output of the above code?
If you think the output will be undefined, No problem when I first saw this code I also thought undefined but the output will be 2. Feels weird, Heres the explanation.
Hoisting occurs because JavaScript engine will compile the code before its interpretation. The compiler actually considers var a = 2; as two different statements var a; and a = 2;. So the part of the compiler finds all the declaration first and then associate their assignment with their appropriate scopes.
Note:- Hoisting does not work with strict mode.
This was just an introduction part of Hoisting there are lots of scenarios where it can work differently.
I hope you just got a rough idea about it. Thanks for reading and stay tuned for more.
Top comments (9)
Makes sense.. you first get the plate before you put some meat to eat. Thanks!
🤘🤘🤘🤘
Good explanation. However, I feel like this was taken from Kyle Simpson’s book. You can at least cite that. Cheers.
Yup, I read all the parts of YDKJS and I felt this example will be easy to understand that's why I used, By the way, I'm a big fan of Kyle Simpson.
Good Explanation
Thanks Uddesh. Good one on JavaScript hoisting.
What about using the let keyword or const? Do they have the same effect?
using const and let will throw ReferenceError because you have to initialize the variable at the time of declaration if you wanna use const or let. It's not officially mentioned in ECMAScript documentation but it will definitely throw the error.
Good things