Undefined Value

Can someone explain me why returned value will be undefined?

var sum = 0;
function addSum(num) {
  sum = sum + num;
}
addSum(3);

You’re not retuning anything , there is no return value defined.

2 Likes

But if I put this equation out of function like this:

var sum = 0
sum = sum + 3
console.log(sum)

It’s gonna show 3 in console instead of undefined. Why is that?

Because you’re using the debugging tooling provided by JS to log a value to the debug console.

The function still doesn’t have a return value defined, and so still returns undefined.

Just to clarify, the console functions are designed to never affect what happens in your program. They are there so that you can inspect what’s going on at certain points in your program.

Your code does increase the variable sum. So if you type sum on the console or write console.log(sum) you will see that the function actually increased sum. However, it does still return undefined. You could return sum by writing:

var sum = 0;
function addSum(num) {
  sum = sum + num;
  return sum; 
}
addSum(3);

Which will return 3 in your case.

Why? When you do not define a return statement, JavaScript kind of adds a return undefined as the last line and no matter what your function does, it will return undefined if no return-statement is used. Returning undefined (implicitly) is not a bad thing, even though it might look like a problem. However, using return can help you to write functions which do not refer to variables outside the function and are thus easier to understand (since you only need to read the function and not care for what is defined elsewhere)

1 Like

Ok, thanks guys. I understand that now .

1 Like