If a javascript variable is called as function, then what is the working process?
let a=5;
function show(){
a=10;
function a(){};
return a;
}
let res=show();
console.log(a,res); //output:5 10
Can anyone please explain why it is showing 5 for a, what is the meaning of function a(){}?
show()assigns the value 10 to the global variableaand defines the functiona()in its own scope. It appears that the global variableaand not the functiona()is returned at the end of the function.a()is hoisted at the top of the functionshow()as a local variable and then overwritten with the number10. The functionshow()then returns the local variablea. (If it changed the global variableathenconsole.log(a, res)would not print 5 as its value.)a()causes a local instance ofato be created inshow(). This (creation of functions) always happens before any other code in that function is executed. Afterwardsagets a new value: 10, and this is eventually returned at the end of the function. Yes, @GuyIncognito, I just read your comment and I agree - "hoisting" is the magic word here! ;-)