i'm a beginner in javascript and i tried to learn about function that called inside a function which redefine a value of a variable. Here's the code
var a;
function app2(a) {
var a = 8;
return a
}
function app(a) {
var a = 7;
app2(a)
return a
}
console.log(app(a));
when i run code, it still show 7 as the output. i thought it will be 8 because i've called the function app2
in the app
function. why the value doesn't change into 8? and what should i do update the variable value inside the nested function? thanks in advance
CodePudding user response:
1) You can only get 8
if you are taking the value of app2
and using it inside app
.
Variables declare with var
keyword are function scoped and they are not visible outside of that particular function in which it is declared.
a
declared in app2
is not visible inside app
unless you are not returning the value from app2
and not using the return value from app2
inside app
(Both condition should be satisfied to use it)
var a;
function app2(a) {
var a = 8;
return a;
}
function app(a) {
var a = 7;
a = app2(a); // reassign the returned value from app2
return a;
}
console.log(app(a));
2) If you are returning it and not capturing it, then It's no use. You can also do as:
var a;
function app2(a) {
var a = 8;
return a;
}
function app(a) {
var a = 7;
return app2(a); // Directly return the value of app2 returned value
}
console.log(app(a));
CodePudding user response:
I think the main culprit of what you are seeing is that you are naming the arguments of the functions a
and also the global is named a
.
When experimenting with this you would expect a = 8
when all var
keywords are removed except for the global one. This does not happen because the argument, named a
, is shadowing the global var a
. When you use the var
keyword locally in a function you are essentially telling javascript you want to declare a local function-scoped var a
, and not reference the global var a
, so this way any changes stay in the function scope.
Check this snippet out:
var a;
function app2(b) { // changed argument name from `a` to `b`
a = 8; // removed var keyword here
return a
}
function app(b) { // changed argument name from `a` to `b`
a = 7; // removed var keyword here
app2(a)
return a
}
console.log(app(a)); // output: 8