Does Every JavaScript Function Have to Return a Value

Does every Javascript function have to return a value?

The short answer is no.

The real answer is yes: the JS engine has to be notified that some function has finished its business, which is done by the function returning something. This is also why, instead of "finished", a function is said to "have returned".

A function that lacks an explicit return statement will return undefined, like a C(++) function that has no return value is said (and its signature reflects this) to return void:

void noReturn()//return type void
{
printf("%d\n", 123);
return;//return nothing, can be left out, too
}

//in JS:
function noReturn()
{
console.log('123');//or evil document.write
return undefined;//<-- write it or not, the result is the same
return;//<-- same as return undefined
}

Also, in JS, like in most every language, you're free to simply ignore the return value of a function, which is done an awful lot:

(function()
{
console.log('this function in an IIFE will return undefined, but we don\'t care');
}());
//this expression evaluates to:
(undefined);//but we don't care

At some very low level, the return is translated into some sort of jump. If a function really returned nothing at all, there would be no way of knowing what and when to call the next function, or to call event handlers and the like.

So to recap: No, a JS function needn't return anything as far as your code goes. But as far as the JS engines are concerned: a function always returns something, be it explicitly via a return statement, or implicitly. If a function returns implicitly, its return value will always be undefined.

Do I have to return something in javascript function?

No; Javascript functions are not required to return a value.

If you call a function that doesn't return a value, you'll get undefined as the return value.

Does A Function Always Return A Value

Yes it always returns a value, if explicit one is not given, it returns undefined. This is same as you will write return undefined or just return.

Why JavaScript functions always return a value?

It's true—because that's how JavaScript was designed.

But I don't think that's the answer you were looking for, so let's think about it...

Try to put yourself in the shoes of Brendan Eich, the person who designed JavaScript!

In static languages, there is usually a distinction between a function that doesn't return anything (void function), and a function that returns some value. Brendan chose to design a dynamic language, that is, a language that doesn't require you to define function return types. So JavaScript doesn't check what you return from the function, giving you full freedom.

You can have a function that returns a number...

function computeSomething() {
return 2;
}

... or a string ...

function computeSomething() {
return 'hi';
}

... or, in fact, any of them:

function computeSomething() {
if (Math.random() > 0.5) {
return 2;
} else {
return 'hello';
}
}

Sometimes you don't need to compute anything—you only need to do something.

So you don't return anything.

function doSomething() {
console.log('doing something');
}

We may, however, want to exit a function in the middle of it, and since return <value> already does exactly that, it makes sense to allow writing return without a value to support this use case:

function doSomething(num) {
if (num === 42) {
return;
}

while (true) {
doSomethingElse();
}
}

This is also consistent with C/Java syntax, which was one of the goals to ensure JavaScript adoption.

Aye, there's the rub: what happens if we put a plain return into a function supposed to compute something? Note that we can't outlaw this: one of our earlier decisions was to make JavaScript a dynamic language, where we don't check what the function returns.

function computeSomething(num) {
if (num === 42) {
return; // just return? o_O
}

if (Math.random() > 0.5) {
return 2;
} else {
return 'hello';
}
}

var x = computeSomething(2); // might be 2, might be 'hello'
var y = computeSomething(42); // ???

Of course Brendan could have decided to raise an error in this case, but he wisely decided not to, because it would lead to hard-to-find errors and too easily breakable code.

So an empty return got a meaning “return undefined”.

But what's the difference between the function returning early, or at its end? There shouldn't be any, from the calling code's point of view. Calling code is not supposed to know when exactly the function returned; it is only interested in return value (if any).

The only logical conclusion thus would be to make undefined the “default” return value if function does not specify one via explicit return <value> operator. Thus, return and function-executed-to-its-end semantics match.

Python, another dynamic language that came before JavaScript, solves this problem in the same way: None is returned if function doesn't specify return value.

Should functions always return something (Javascript)

They don't have to return anything. If you leave it blank it simply returns 'undefined' which in this case is fine because you never intend to use the return value. The Javascript syntax is pretty simplistic and as far as I know there just isn't any real distinction between functions that do and functions that don't return a value (other than the 'return' keyword)

Javascript function: no return statement identical to return undefined?

I know the results but I want to know more in-depth. Is that mean in Javascript functions, no return statement identical to return undefined?

It is in effect, yes. The specification differentiates between the two, but in pragmatic terms, calling a function that "falls off the end" vs. return; vs. return undefined; all have exactly the same end result in terms of what have the call results in: undefined.

In my answer to the dupetarget (I should have realized!) I explain how the spec differentiates them, but again, it's just a spec distinction, not something you can observe in actual code.

What does javascript function return in the absence of a return statement?

A function without a return statement (or one that ends its execution without hitting one) will return undefined.

And if you use the unary negation operator twice on an undefined value, you will get false.

You are not seeing anything on the console because Firebug doesn't prints the result of an expression when it's undefined (just try typing undefined; at the console, and you will see nothing).

However if you call the console.log function directly, and you will be able to see it:

function foo(){}

console.log(foo()); // will show 'undefined'

Should I always give a return value to my function?

A "pure" functional programming environment would have no side effects -- each function's work would be entirely in computing its return value; that's not really feasible in typical uses of Javascript, and so it's perfectly acceptable, when a function has done its work through side effects, to have it return nothing at all, i.e., be a "procedure" rather than a function.

Is 'return' necessary in the last line of JS function?

what's the best practice of finishing the JS function if it doesn't
return anything?

A function returns undefined by default. The use of return is therefore only necessary if you want to override the default behaviour.


Why most leave it out when they can

The Javascript community seem to dislike unnecessary verbose code. It might even be said to be a sport to make the code as short and compact as possible.

Why this may not be the best practice for all

The habit of always using return may serve as a good reminder that a function always returns something and thereby remind you to reflect on whether the default behaviour should be overridden.

However an experienced programmer will have such considerations deeply internalized and therefore rarely have need for such reminders.

Conclusion

As one gains experience the sport for less verbose code intensifies and in that context writing code just confirming default behaviour is an absolute no-go.

So: in the long run I would say most people end up leaving it out and that it is justified to do so because of the high degree of internalization.

Javascript function does not return values

getConnection does not return anything. find is what you need:

const getConnection = function(cid){
return allEvents.find(event => {
return event.connectionId === cid;
});
}


Related Topics



Leave a reply



Submit