Hey there!
What you have is correct if you are expecting the the final value of sum to be 13.
Note that you are changing the value of sum in the first function addThree(num),
So after you call that function the value of sum changes from 3 to 8 because you are passing an addition of 5 in that function call.
Then you are running addFive() function which then changes the value of sum to 13 as you are adding 5 to the value of 8.
and now the value of sum is 13.
if you do not want to change the value of global scope sum through your function then you have to return the function call as a new value which will not change the original global scope value.
Please see below:
// Setup
var sum = 3;
function addThree(num) {
sum = sum + num;
}
// Only change code below this line
function addFive() {
sum += 5
}
// Only change code above this line
addThree(5);
var result = addFive(); // This is undefined
console.log("Sum= " + sum);
addThree(2)
console.log("Sum= " + sum);
addFive()
console.log("Sum= " + sum);
Above, I am logging the value of sum to the console everytime I make a function call. See how the value of sum changes.
Now please see below how to not change the global scope variable outside the function.
// Setup
var sum = 3;
function addThree(num) {
return sum + num;
}
// Only change code below this line
function addFive() {
return sum + 5
}
// Only change code above this line
console.log(addThree(5));
console.log("Sum= " + sum);
console.log(addFive());
console.log("Sum= " + sum);
console.log(addThree(2));
console.log("Sum= " + sum);
console.log(addFive());
console.log("Sum= " + sum);
Also please note that using “+=” operator changes the value of global scope sum. You are assigning a new value to the sum variable.
Also to address your query on result variable to be undefined. Below is the proper way to use the result variable for the simplicity.
var sum = 3
function addFive() {
var result= sum + 5;
return result;
}
console.log(result);
Hope this helps! Keep on advancing to further lessons as you will have clearer answer to some doubts from previous lessons as you further dig deeper into understanding the logic of functions.
Cheers!! Happy Coding!