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(){}?
VLAZ
29.6k9 gold badges65 silver badges88 bronze badges
asked Jul 3, 2024 at 5:38
Soumi Ghosh
1591 gold badge1 silver badge14 bronze badges
1 Answer 1
In JavaScript, all function declarations are hoisted to the top of the scope. Function declarations themselves create a scope, so in this case, the code is really interpreted as:
let a=5;
function show(){
function a(){};
a=10;
return a;
}
let res=show();
This means that the outer a reference never changes.
A related SO question: javascript scope of function declarations
answered Jul 3, 2024 at 5:49
Matthew Herbst
32.3k27 gold badges92 silver badges141 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js
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! ;-)