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
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:
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