This is true because that is how JavaScript was designed.
But I don’t think the answer you were looking for, so think about it ...
Try putting yourself in the shoes of Brendan Eich , the person who developed JavaScript!
In static languages, there is usually a difference between a function that returns nothing ( void ) and a function that returns some value. Brendan chose a dynamic language, that is, a language that does not require determining the types of returned functions. Therefore, JavaScript does not check what you return from a function , giving you complete freedom.
You may have a function that returns a number ...
function computeSomething() { return 2; }
... or 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 do not need to calculate anything - you just need to do it .
Therefore, you are not returning anything.
function doSomething() { console.log('doing something'); }
We may, however, want to exit the function in the middle of it, and since return <value> already doing just that, it makes sense to allow return without 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 of JavaScript adoption.
Yes, there rub: what happens if we put a simple return in a function that needs to calculate something? Please note that we cannot forbid this : one of our previous decisions was to make JavaScript a dynamic language, where we do not 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 might have decided to make a mistake in this case, but he wisely decided not to, because it would lead to hard-to-reach errors and too easily destructible code.
Thus, an empty return got the value "return undefined ".
But what's the difference between a function returning early or late? They should not be, from a code point of view. The call code does not need to know exactly when the return function is; he is only interested in the return value (if any).
The only logical conclusion, therefore, would be to make undefined default return value if the function does not specify one through the explicit return <value> operator. Thus, the correspondence of return and the semantics performed by functions, and.
Python, another dynamic language that came before JavaScript, solves this problem the same way: None returned if the function does not specify a return value .