Functions with return - undefined

Tell us what’s happening:

Hello all.

So i’m on the lesson where we are learning about functions without return statements.

in the example given, on the text bit (link to lesson: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/understanding-undefined-value-returned-from-a-function) it says that calling the function (using an argument of 3) will change the global sum variable but the returned value of the output is undefined.

two questions:

  1. does this mean that if i called the function again with an argument of 5 (ie addThree(5); ) that will change the value of the global sum variable to 8?

  2. what does it mean by output is undefined? As far as i can see, we haven’t asked for an output (ie a console.log(function) anywhere in the code, so i can’t see where/what is being output as undefined?

Hope that makes sense, thanks in advance!

Matt

Your code so far


// Setup
var sum = 0;

function addThree() {
sum = sum + 3;
}

// Only change code below this line


// Only change code above this line

addThree();
addFive();

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36.

Challenge: Understanding Undefined Value returned from a Function

Link to the challenge:

Yup! That’s why we generally stay away from modifying global variables.

It’s not that anything is being output as undefined, it’s just that’s what the function returns.

If we had

function plusThree(num) {
   return num + 3;
}
plusThree(3);

then plusThree would still return a number, even though we didn’t do anything with it here. With the function in the challenge, if you were to add var retVal = addThree() then the value of retVal would be undefined.

2 Likes