4

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?

daydreamer
  • 87,243
  • 191
  • 450
  • 722

1 Answers1

9

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. :-)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 3
    Wish I could give another +1 because of the use of 42 as an example number. Don't forget your towel. – howderek Apr 25 '13 at 17:51
  • Thanks a lot @T.J.Crowder, that explains it really well – daydreamer Apr 25 '13 at 17:52
  • 1
    One thing I like to do myself if I'm really paranoid about it is to throw all my JavaScript into a self-executing anonymous function and declare an extra formal parameter `undefined` (to which I don't pass anything). That will hide the global `undefined` and allow me to control the value and guarantee that it is actually undefined by simply not passing a value in for that parameter. – Platinum Azure Apr 25 '13 at 17:52
  • 1
    @PlatinumAzure I don't think that code will validate with `use strict`. ECMA5 defines `undefined` as a reserved word, therefore you can't use the name. – Andrei Nemes Apr 25 '13 at 17:59
  • @AndreiNemes Yeah that's true, I found out the hard way – Ian Apr 25 '13 at 18:06
  • @AndreiNemes Shame, it would have been nice if they allowed that as a workaround or something. Thanks for pointing that out. – Platinum Azure Apr 25 '13 at 20:43