# Conceptual help needed - Understanding Undefined Value returned from a Function

Conceptual help needed - Understanding Undefined Value returned from a Function
0

#1

Tell us what’s happening:
Although I am able to complete the task, I was wondering why we are doing what we are doing:-

why aren’t we using “var” while assigning value to variable “sum” within the function?

Even in the example, “var” is not used while assigning value to variable “sum” within the function.

and when I tried to put “var” before variable “sum” just outta curiosity, it gave me an error.

when should “var” be used and when it shouldn’t be?

``````
// Example
var sum = 0;
sum = sum + 3;
}

// Only change code below this line
var sum = 0;
sum = sum + 5;
}

// Only change code above this line
``````

User Agent is: `Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0`.

#2

If you are talking about the addThree function, sum (inside the function) refers to the global variable sum (outside the function) which has an initial value of 0. If you were to call the addThree function like below:

``````addThree();
``````

then the global variable sum would be 3 after the function call, so you could write:

``````var sum = 0;
sum = sum + 3;
}
console.log(sum); // displays 0
console.log(sum);  // displays 3
``````

Notice before the addThree function is called, sum is 0 and then after the function is called sum is 3.

That is because in the example, the intent was to change the global variable sum and not create a local variable sum inside the function. If I created a local variable inside addThree, it would look like:

``````var sum = 0;
var sum = 100;
sum = sum + 3;
}
console.log(sum); // displays 0