Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it typical for a Javascript function to return a value of undefined intentionally? [closed]

Tags:

javascript

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#).

like image 969
Joe B Avatar asked May 05 '14 13:05

Joe B


People also ask

How to return a value from a function in JavaScript?

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.

What is a return statement in JavaScript?

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.

How many times does the recursive function 121 return undefined?

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 function?

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.


1 Answers

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

like image 77
Aaron Digulla Avatar answered Sep 19 '22 12:09

Aaron Digulla