Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function Hoisting changing the var value

Tags:

javascript

can anybody explain me why I'm getting different output?

code 1:

var a = 1;

function b() {
  a = 10;
  console.log(a); //output 10
}

b();
console.log(a); //output 10

code 2:

var a = 1;

function b() {
  a = 10;
  console.log(a); //output 10
  function a() {}
}

b();
console.log(a); //output 1

Why I'm getting different output for "a" variable after calling function "b"? Needed some clear explanation what's really happening here?

like image 716
Nag Avatar asked May 20 '26 07:05

Nag


1 Answers

I would say case 1 is pretty self-explanatory, as the value of a is overwritten by a=10.

In case 2, because of function a() {} and because of hoisting the variable declarations and function definitions are moved up to the closest lexical scope which is function b() for function a() so a is scoped to function b() and changing its value will not affect the value of global a and instead the function a() is overwritten.

Because of which the console.log(a) present outside function b() is logging 1 as global value is not changed.

like image 74
void Avatar answered May 24 '26 05:05

void



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!