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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With