Simple function code error

Tell us what’s happening:
Hi, I’m just wondering if someone can explain this:
I was doing JS and at first I wrote code that is commented out, and it gave “undefined” error
The code that you see works, but why exactly that commented out code doesn’t? Shouldn’t it do the same thing?

Your code so far


function functionWithArgs(a, b){
console.log(a+b);
// a+b;
}

// console.log(functionWithArgs(1,2));

functionWithArgs(1,2);


Your browser information:

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

Challenge: Passing Values to Functions with Arguments

Link to the challenge:

Welcome, damians.

This has to do with values of functions. In general, functions are written to return a value. In your case, neither of your code will return any value with functionWithArgs. So, the value of functionWithArgs is undefined. Some examples:

function func1(a,b) {
  return a+b;
}
console.log(func1(2,3)); // Expected Output: 5
function func2(a,b) {
  a+b;
}
console.log(func2(2,3)); //Expected Output: undefined
function func3(a,b) {
  console.log(a+b);
}
func3(2,3); // Expected Output: 5
function func4(a,b) {
  console.log(a+b);
}
console.log(func4(2,3));
// Expected Output: 5
//                  undefined

I hope that helps

1 Like

Thx for your reply, so code inside curly braces must have some kind of return syntax, like return or console.log(), and can’t be just a+b

Well, you are welcome to put whatever you want inside a function. The issue is a function like this does absolutely nothing useful:

function myFunc(a,b) {
  a+b;
}

But, a function does not need to return something (this is just common). A function could just change something:

var a = 2;
function addOne(x) {
 x = x + 1;
}
console.log(addOne(a)); // Expected Output: undefined
console.log(a); // Expected Output: 3;
// the variable a has changed

Hope this helps

1 Like