Reasons and benefits of "return obj = = = void 0" in JavaScript

Source: Internet
Author: User

When learning underscore.js, it is often found in the source code that resembles the following:

if (context = = = void 0) return func;if (array = = null) return void 0;

Have not seen this writing before, to search the Internet some information, just found that stackoverflow on the other people raised similar questions. Summarized here, make a note. Void is actually a function in JavaScript that takes a parameter and the return value is always undefined. It can be said that the purpose of using void is to get undefined in JavaScript. So was void 0 a correct and standard a-produce undefined .

void 0void (0) void "Hello" void (new Date ())//all would return undefined


Why not use undefined directly? There are 2 main reasons:

1. Using void 0 can reduce the use of undefined by 3 bytes. Although this is an advantage, individuals feel little meaning, sacrificing readability and simplicity.

> "undefined" .length9> "void 0". Length6

2,undefined is not a reserved word in JavaScript, we can use undefined as the variable name, and then assign it a value.

alert (undefined); Alerts "undefined" var undefined = "new value"; Alert (undefined)//alerts "new value"

Because of this, your cannot safely rely on undefined have the value that's that you expect.

Void, on the other hand, cannot is overidden. void 0 would always return.

I tested it under Ie10,firefox and chrome, and unfortunately didn't come up with the expected results. Although the above code did not give an error, it did not print out the "new value" we expected.

So in general, the use of void 0 is not very meaningful.

Reference

Http://stackoverflow.com/questions/7452341/what-does-void-0-mean

Http://stackoverflow.com/questions/11409412/how-to-understand-return-obj-void-0-in-the-source-of-underscore


Reasons and benefits of "return obj = = = void 0" in JavaScript

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.