+ 1

Why is this code giving the output "5, undefined , 5" instead of "5,undefined , 10"?

var x = 5; function y(){ x=10; return function x(){} } console.log(x); //5 console.log(y()); //undefined console.log(x); // 5

18th Aug 2021, 2:14 PM
Mons Joseph
Mons Joseph - avatar
3 Réponses
+ 2
Remove the last 2 lines from function y() 👇 return function x(){}
18th Aug 2021, 2:27 PM
Ipang
+ 1
Function y() hasnt been called to assign 10 to x.
18th Aug 2021, 2:21 PM
Anthony Johnson
Anthony Johnson - avatar
0
Thats because variable declarations in JS are hoisted (except when using strict mode or 'let') which means you can use a variable before declaring it, it will just have the value undefined. In the code x is declared inside y() which makes it local to that scope, hence not affecting the global x value. var x = 5; // declare global x function y(){ x=10; // sets local variable x return // returns undefined // function x(){} is the same as: var x = function(){} // declare x local to y // if var was missing it would use the global x instead } console.log(x); //5 console.log(y()); //undefined console.log(x); // 5 Worth noting that trying to use an undeclared variable hoisted or not, results in a ReferenceError thrown
18th Aug 2021, 7:11 PM
Giorgos