i started with js functions and didn’t understand the output for the following code
var sum = 0;
function add() {
var sum = sum + 3;
return sum;
}
console.log(add());
i am getting NaN as output shouldn’t it be 3 ?
i started with js functions and didn’t understand the output for the following code
var sum = 0;
function add() {
var sum = sum + 3;
return sum;
}
console.log(add());
i am getting NaN as output shouldn’t it be 3 ?
Hey @SharonnoNayak
You have created a global variable called sum and assigned it to be 0. You have also created a function which adds the value of sum + 3. There is small issue here - var sum = sum + 3;
What you are doing here is creating a new sum variable. The sum variable has no value and its scope is limited within the function only. As there is no value assigned for the sum variable it returns NaN - which means Not a Number. To fix this issue. please remove the var keyword inside the function.