2

Why is the JavaScript "do-nothing" snippet void(0) often written as such? Why not just void 0? Is there any particular reason why the 0 is so often enclosed in (unnecessary) parenthesis?

MDN says that void(0) is equivalent to void 0, as void is an operator.

Could this possibly be the same type of confusion as enclosing the typeof operand in parenthesis? (Like typeof(value) === 'string'?) Is it the same case where many people seem to believe void is a function?

This answer states that

void(0) is just the smallest script possible that evaluates as undefined.

But void 0 is actually one character shorter, and seems to behave equivalently, at least in Chrome 43.

Community
  • 1
  • 1
Jackson
  • 9,188
  • 6
  • 52
  • 77
  • 1
    A style choice? I don't see this as being answerable. You already stated that the two are functionally equivalent. Speaking personally, I couldn't give a rat's arse about `void 0` being "one character shorter"; `void(0)` looks nicer. Anyway, who needs to use `void(0)` any more? It's 2015. :-) – Lightness Races in Orbit Jun 29 '15 at 20:52
  • 1
    this two cases are same, but when you enclose 0 in parenthesis, this operator look a like simple function, so it can be more accustomed for some developer – Grundy Jun 29 '15 at 20:52
  • Exactly, this question _is not answerable_ void is an **operator**. The history behind the use of parenthesis on operators isn't really a valid query for this website. – Olivier Poulin Jun 29 '15 at 20:54
  • It's a style thing, and beyond that it's a style for something that is only very rarely necessary. – Pointy Jun 29 '15 at 20:55
  • 1
    actually, this is a duplicate http://stackoverflow.com/questions/13656453/many-people-write-javascriptvoid0-instead-of-javascriptvoid-0-in-hrefs – Olivier Poulin Jun 29 '15 at 20:57
  • As you are right, parens make not much sense for `void 0` however, there are cases, even though they are rare, when parens do make sense. E.g. `if(typeof(a || b) === "string")` when `a` is undefined and `b` is set or for readability. – Sebastian Nette Jun 29 '15 at 21:03
  • RE "style": I thought maybe there was a smidgen of a chance some legacy browser required the parentheses... or something. Sorry for the duplicate, didn't see anything when I first searched this. – Jackson Jun 29 '15 at 21:25

1 Answers1

2

You're 100% right. The void is an operator rather than a function, one doesn't gain anything by using the parenthesis. It is simply like he would write void (0) (because 0 === (0))

Tomek Sułkowski
  • 7,081
  • 2
  • 17
  • 15