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.

Leave a Comment