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.

Leave a Comment