JavaScript Hoisting: var vs Function Declarations

🚀 JavaScript Hoisting: A Small Interview Question That Confuses Many ✅ Today I came across an interesting JavaScript interview question : Why does console.log(bar) print the function instead of undefined? I was asked an interesting JavaScript question in an interview today, and it was a great reminder of how differently JavaScript handles hoisting for function expressions vs. function declarations. Here’s the concept behind the output: 1. **boo** is created using a function expression with **var**. Variables declared with var are hoisted, but only the variable name is initialized. The actual function value is not assigned until later. So when boo is logged before assignment, it returns undefined. 2. **bar** is created using a function declaration. Function declarations are fully hoisted. This means the entire function is placed into memory before any execution happens. So when **bar** is logged, JavaScript prints the complete function definition. 3. After execution reaches their definitions: Both **boo()** and **bar()** run normally because they now hold their respective function values. Key takeaway: **var** hoists only the variable, not the function value. Function declarations hoist both the name and the entire function body. A simple interview question, but a powerful reminder of how JavaScript behaves behind the scenes. #JavaScript #WebDevelopment #FrontendDeveloper #CodingInterview #TechInterview #JavaScriptTips #Hoisting #LearnToCode #Developers #Programming #MERNStack #ReactJS #NodeJS #100DaysOfCode

  • text

To view or add a comment, sign in

Explore content categories