DEV Community 👩‍💻👨‍💻

Cover image for JavaScript - Hoisting (1)
Top
Top

Posted on • Updated on

JavaScript - Hoisting (1)

Variable Hoisting

Prior to explain about Hoisting, we need to know about how does JavaScript engine complie the Codes
JavaScript engine alters the structure of code before it runs it

Only Variable declarations, not the assignment are hoisted, or moved to the top of their available scope

JavaScript Code

console.log(x); 
var x = 5;
console.log(x);
console.log(y); 
Enter fullscreen mode Exit fullscreen mode

Altered Code by JavaScript Engine

var x;
console.log(x); // -> undefined
x = 5;
console.log(x); // -> 5
console.log(y); // -> Uncaught ReferenceError: y is not defined
Enter fullscreen mode Exit fullscreen mode

Hoisting Example

console.log(x);
console.log(y);

var x = 'This will log "undefined"!';
y = 'This will throw an error :(';

Enter fullscreen mode Exit fullscreen mode

Are you interested in this?
If you have questions, please ask me...

And if this is okay, I am going to explain about Function Hoisting

Thank you !

Top comments (1)

Collapse
 
curiousdev profile image
CuriousDev

Thanks, very nice!

Visualizing Promises and Async/Await 🤯

async await

☝️ Check out this all-time classic DEV post