Decoding Hoisting in JavaScript

Decoding Hoisting in JavaScript

?? Mastering Hoisting in JavaScript! ??


?? What is hoisting?

Hoisting is a unique behavior in JavaScript where the declarations of functions, variables, and classes are moved to the top of their scope before any code is executed. This means you can access a function or variable before its actual declaration in the code.


?? Understanding Hoisting with a Debugger:

Let's try to understand hoisting with a code example and debugger.

Hoisting code example

In the image above, I have put a debugger breakpoint on the first line of code. This means the code execution is suspended and not a single line of code is executed. But we can clearly see in the scope that JS engine has initalised variables 'a' & 'b' with value undefined and the 'add' function is also present in the scope.


Hoisting code example

The code snippet prints undefined for variables 'a' and 'b' even before their actual initialization. But how does the JS engine know about these declarations before executing the code?


?? Magic of Execution Context:

It's because of the execution context created by JS engine when the program is executing. Hoisting is a consequence of the memory allocation phase of execution context. To know more about execution context check my previous post: How JS code is executed?


If you want to dive deep into world of JavaScript, checkout Akshay Saini ?? Namaste JavaScript Playlist.

Explore more JavaScript insights and handy notes on my GitHub: https://github.com/sachdevavaibhav/js-fundamentals/ ????


Feel free to share your thoughts and experiences with hoisting in the comments! Let's demystify JavaScript together. ????


要查看或添加评论,请登录

Vaibhav Sachdeva的更多文章

社区洞察

其他会员也浏览了