I'm new to Javascript and am wondering if intentionally returning a value of undefined from a function is a common practice.
For example, should a divide() function be implemented like this:
var divide1 = function (x, y) {
if (y === 0) {
return undefined;
}
return x/y;
};
or like this?
var divide2 = function (x, y) {
if (y === 0) {
throw new Error("Can't divide by 0");
}
return x/y;
};
I assume that returning undefined is typically reserved for functions with no return values (equivalent of void in Java or C#).
A JavaScript function can have an optional return statement i.e. it’s optional to return a value. This statement should be the last statement in a function. For example, you can pass two numbers in a function and then you can expect the function to return their multiplication to your calling program. Try the following example.
Definition and Usage. The return statement stops the execution of a function and returns a value from that function. Read our JavaScript Tutorial to learn all you need to know about functions.
Consider the case 121. It should actually return 11 in the current context. But it is returning undefined. I have checked how many times the recursive calls happened; they actually happened two times.
Is it required to have a return a value from a JavaScript function? A JavaScript function can have an optional return statement i.e. it’s optional to return a value. This statement should be the last statement in a function.
It's the default:
function foo() {}
console.log(foo());
But it turned out it's not a good choice. Code which can run into an exceptional state shouldn't do so silently. A lot of errors in JavaScript slip through the cracks because the code doesn't break violently when something goes wrong.
So unless you're an exceptional good developer and you can guarantee that everyone who will ever touch this code is on the same level and you never make mistakes, you can return undefined
. I, myself, would throw an exception.
Turns out I'm not a good-enough developer :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With