var sum = 2;
function addFive() {
var sum = sum + 5;
console.log(sum); //why not 7
}
addFive();
Why is it returning NaN
instead of 7?
var sum = 2;
function addFive() {
var sum = sum + 5;
console.log(sum); //why not 7
}
addFive();
Why is it returning NaN
instead of 7?
To make things clearer, your code is essentially being read like so:
var sum = 2;
function addFive() {
var sum; // implicitly equal to undefined
sum = sum + 5; // sum = undefined + 5 = NaN
console.log(sum); // NaN
}
addFive();
As you can see, you're redeclaring sum
and it is set to undefined
. So, when you try and add 2
to undefined
you're going to get NaN
(Not a Number).
Instead, you can reference your outer sum
variable by not redefining it within your function and instead just reassign its value:
var sum = 2;
function addFive() {
sum = sum + 5; // sum = 2 + 5 = 7
console.log(sum); // 7
}
addFive();
You're declaring the variable sum
again in the function. This has all to do with scoping in JavaScript.
Take a look at the following article to learn more.
In this case, the local variable (the one that's declared inside the function) gets priority by the JavaScript parser. This behavior's called 'shadowing'. It starts at the innermost scope being executed at the time, and continues until the first match is found, no matter whether there are other variables with the same name in the outer levels or not.
Because you are declared a local variable sum inside the function.
You have to use this
.
var sum = 2;
function addFive(){
var sum = this.sum + 5;
console.log(sum);
}
addFive();
In this context, this
will refer to the global object (in a browser, window
), so the above code is equal to:
var sum = 2;
function addFive(){
var sum = window.sum + 5;
console.log(sum);
}
addFive();
You can read more about this
in this SO post or on MDN