🔥 Spot the Bug – JavaScript Function Edition
console.log(add(2, 3));
var add = function(a, b) {
return a + b;
};
Looks harmless? Think again 😬
This one-liner fails at runtime with:
❌ TypeError: add is not a function
But why?
💡 Here's the trick:
When you use a function expression with var, only the variable gets hoisted, not the function definition. So at the time of the console.log, add is just undefined — not a function!
✅ Correct Version (Function Declaration):
function add(a, b) {
return a + b;
}
console.log(add(2, 3)); // ✅ 5
✅ OR Fix the Timing (Function Expression):
var add = function(a, b) {
return a + b;
};
console.log(add(2, 3)); // ✅ 5
🧠 Understanding hoisting in JS is critical to avoid subtle bugs like this!
💬 Drop a 🧠 if you learned something new!
🔁 Share with your coding buddy who's still learning functions!
📌 Save this reel for interview prep or review
✅ Follow @codebypc for daily JavaScript bug busters & dev tips!
#JavaScript #CodeBug #FunctionExpression #Hoisting #SpotTheBug #WebDevTips #FrontendChallenge #DeveloperLife #JSBugs #CodeSmart #CleanCode #DebuggingJS #FullStackTips #LearnToCode #TechReels
コメント