Reasons and benefits of using & quot; return obj ==void 0 & quot; in javascript
When I learned about underscore. js, I found that the following code often appears in the source code:
if (context === void 0) return func;if (array == null) return void 0;
I have never seen this method before. I searched some materials on the Internet and found that some people in stackoverflow raised similar questions. Here we will summarize and take a note. Void is actually a function in javascript. It accepts a parameter and the return value is always undefined. It can be said that void is used to obtain undefined in javascript. Sovoid 0
Is a correct and standard way to produceundefined
.
void 0void (0)void hellovoid (new Date())//all will return undefined
Why not use undefined directly? There are two main reasons:
1. void 0 can be reduced by 3 bytes than undefined. Although this is an advantage for individuals, it doesn't make much sense and sacrifices 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 assign it a value.
alert(undefined); //alerts undefinedvar undefined = new value;alert(undefined) //alerts new value
Because of this, you cannot safely rely on undefined having the value that you have CT.
Void, on the other hand, cannot be overidden. void 0 will always return.
I tested IE10, Firefox, and chrome. Unfortunately, no expected results were returned. Although no error is reported in the above Code, the expected new value is not printed.
In general, using void 0 is of little significance.