-2

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(){}?

3
  • 1
    Your function show() assigns the value 10 to the global variable a and defines the function a() in its own scope. It appears that the global variable a and not the function a() is returned at the end of the function. Commented Jul 3, 2024 at 5:48
  • 2
    @CarstenMassmann No, it's the opposite. The definition of functiona() is hoisted at the top of the function show() as a local variable and then overwritten with the number 10. The function show() then returns the local variable a. (If it changed the global variable a then console.log(a, res) would not print 5 as its value.) Commented Jul 3, 2024 at 5:58
  • 1
    The function definition of a() causes a local instance of a to be created in show(). This (creation of functions) always happens before any other code in that function is executed. Afterwards a gets 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! ;-) Commented Jul 3, 2024 at 6:02

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.