return void 0; vs return; [duplicate]

I'm studying the annotated source code of Underscore.js.

Here's the _.first method:

  _.first = _.head = _.take = function(array, n, guard) {
    if (array == null) return void 0;
    return (n == null) || guard ? array[0] :, 0, n);


Why 'return void 0;' and not just 'return;' ? As far as I know return implicitly returns undefined (the value!) from a function. Just like 'return void 0' does.



In the MDN reference for the void operator it states:

The void operator is often used merely to obtain the undefined primitive value, usually using "void(0)" (which is equivalent to "void 0"). In these cases, the global variable undefined can be used instead (assuming it has not been assigned to a non-default value).

So it is indeed equivalent to undefined but the problem with the undefined variable is that it can be redefined as something else. Personally I would always simply return; because it consistently yields the exact same result (as in: (function() {})() === void 0).


Since some commenter consider this not an appropriate answer:

(function() {})() === void 0 always yields true which means that it is exactly the same as return;. So you can consider this an inconsistency in the Underscore library as plain return statements are used in other places (yes, even there it can happen).

Minification and optimization

Another addendum, it looks as if it also doesn't optimize any better during minification. Using the closure compiler the return void 0; vs return; version of the above code sample is still about 5% bigger.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.