JavaScript `undefined` vs `void 0`

旧巷老猫 提交于 2019-12-28 01:57:45

问题


What exactly is the difference between undefined and void 0 ?

Which is preferred and why?


回答1:


The difference is that some browsers allow you to overwrite the value of undefined. However, void(anything) always returns real undefined.

undefined = 1;
console.log(!!undefined); //true
console.log(!!void(0)); //false



回答2:


undefined has normal variable semantics that not even strict mode can fix and requires run-time look-up. It can be shadowed like any other variable, and the default global variable undefined is not read-only in ES3.

void 0 is effectively a compile time bulletproof constant for undefined with no look-up requirements. It is like writing null or true, instead of looking up a variable value. It works out of the box without any safety arguments and is shorter to write. It is better in every way.




回答3:


Use undefined. Its more commonly known than void(0).




回答4:


JS is very loose at syntax, parentheses here are optional, void 0 and void(0) are equivalent.

For second question, you need to use undefined directly while avoiding unneeded operand evaluation to retrieve the same undefined value.

More info in the reference: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/void



来源:https://stackoverflow.com/questions/5716976/javascript-undefined-vs-void-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!