return void 0; vs return; [duplicate]

2019-02-12 14:09发布

问题:

This question already has an answer here:

  • Return void(0); vs return; interrupting functions [duplicate] 2 answers

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

http://underscorejs.org/docs/underscore.html#section-41

Here's the _.first method:

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

Question:

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.

回答1:

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).

Clarification

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.