Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

Should I use `void 0` or `undefined` in JavaScript


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you are using a modern browser, (which supports javascript 1.8.5) using undefined and void 0 would most likely yield the same result (since undefined is made not writable), except that the void can accept an expression as parameter and evaluate it.

In older browsers, (which do not support javascript 1.8.5) It is better to use void 0. Look at this example:

console.log(undefined);
var undefined = 1;
console.log(undefined);

It will print

1

undefined is actually a global property. (Its not a keyword). So, undefined can be changed, where as void is an operator, which cannot be overridden in javascript and always returns the value undefined. Just check this answer which I gave earlier today for a similiar question https://stackoverflow.com/a/19367635/1903116.

Conclusion:

So, if you are concerned about compatibility, it is better to go with void 0.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...