Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: What is additional Zero in the if syntax? [duplicate]

Tags:

javascript

I have been reading the javascript source of my company project and came across this

if (options.parse === void 0) options.parse = true;

Not sure what 0 does here?

like image 935
daydreamer Avatar asked Jan 13 '23 13:01

daydreamer


1 Answers

The void operator is very interesting: It accepts an operand, evaluates it, and then the result of the expression is undefined. So the 0 isn't extraneous, because the void operator requires an operand.

People use void 0 sometimes to avoid the fact that the undefined symbol can be overridden (if you're not using strict mode). E.g.:

undefined = 42;

Separately, the undefined in one window is not === the undefined in another window.

So if you're writing a library and want to be a bit paranoid, either about people redefining undefined or that your code may be used in a multi-window situation (frames and such), you might not use the symbol undefined to check if something is undefined. The usual answer there is to use typeof whatever === "undefined", but === void 0 works (well, it may not work in the multi-window situation, depending on what you're comparing it to) and is shorter. :-)

like image 152
T.J. Crowder Avatar answered Jan 31 '23 07:01

T.J. Crowder