Trouble understanding Return Statement in Solution

let sum = 0;

function addSum(num) {
  sum = sum + num;
}

addSum(3);

addSum is a function without a return statement. The function will change the global sum variable but the returned value of the function is undefined .


What does it mean when it says that: the function will change the global ‘sum’ variable, but the returned value of the function is ‘undefined’ ?


Is it because the sum variable is not declared inside of the function?

It will return undefined because there is no return inside the function

1 Like

If you try

const returnedVal = addSum(3);
console.log('returned value', returnedVal);

You’ll see undefined because the function did not define a return value.
However. If you print sum in between calls to addSum, you’ll see that the global variable’s value keeps changing.

1 Like

Hello @Honeybee! Functions return undefined by default. They only return other values when you include a return statement in it. Regardless of whether the function has a return statement, all of the code in it will run like normal (in this case, the function adds the value of num to the sum variable). Does that answer your question?

1 Like

Hey, Colin… Thanks for the detailed explanation! It helped a lot. and your mbti is cool. :slightly_smiling_face:

1 Like

thank you for the help! :slightly_smiling_face:

You’re welcome, I’m always glad to help! Also, I’m glad to meet someone who’s familiar with MBTI. Just out of curiosity, what’s you’re personality type?

1 Like

My personality type is Intp.

1 Like

Oh, cool. We have very similar personality types! I used to question my MBTI results because I thought that I was also an INTP myself, but to be honest, I feel that the descriptions of both personality types describe me well. I’m always glad to meet a like-minded person.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.