+ 1
Why is my JavaScript function not returning the expected value?
I was trying to write a simple JavaScript function that calculates the square of a number. But instead of returning the correct result, it gives me undefined. Here is my code: function square(num) { let result = num * num; console.log(result); } let output = square(5); console.log(output); The console prints 25 inside the function, but when I log output, it shows undefined. Can anyone explain why this is happening and how to fix it so the function actually returns the result?
3 Antwoorden
+ 1
In your function you used console.log(result) but didn’t return it.
If a JavaScript function doesn’t return anything, it gives undefined by default.
That’s why when you do let output = square(5);, the value of output becomes undefined.
To fix this, replace console.log(result); with return result;.
✅ Correct code:
function square(num) {
let result = num * num;
return result; // now it will return 25
}
let output = square(5);
console.log(output); // 25
So basically, console.log() only shows the value in the console, but to actually send the value outside the function you need return.
+ 2
Xrantu your code should be
console.log(result);
As a
return result;
function square(num) {
let result = num * num;
return result; // return 25
}
let output = square(5);
console.log(output);
Otherwise the second output is undefined
As:
console.log(output): //undefined in your code
0
Yes