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?

Your code so far


// Example
var sum = 0;
function addThree() {
  sum = sum + 3;
}

// Only change code below this line
var sum = 0;
function addFive() {
  sum = sum + 5;
}

// Only change code above this line
var returnedValue = addFive();

Your browser information:

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

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/understanding-undefined-value-returned-from-a-function


#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;
function addThree() {
  sum = sum + 3;
}
console.log(sum); // displays 0
addThree();
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;
function addThree() {
  var sum = 100;
  sum = sum + 3; 
}
console.log(sum); // displays 0
addThree();
console.log(sum); // displays 0
// After the addThree function is executed, the local variable sum (inside the function) gets assigned the value 103, but the global variable sum is still 0.

I am not exactly sure what you try when you got the error, but if you run the following code, Can you post the exact code you tried and I will try to explain why you get the error?

If you want to use a different variable inside a function, but use the same name of a global variable (outside the function), you would need to declare the variable inside the function. In general, you only need to declare a variable (using var) one time per scope.


#3

Thanks @RandellDawson, you have cleared my concept about var and its usage in and outside of the function.