Reputation: 2491
I see people write void(0)
all the time, but I don't understand why people use parentheses. As far as I can tell, they have no purpose. void
is not a function, it's an operator. So why do people use the parens? Do they serve a purpose? Even on MDN the parens are used.
Upvotes: 14
Views: 537
Reputation: 2251
This link explains it for you.
One thing this clarifies is that void is an operator (not a function).Because of this void(0) is technically incorrect though in practice implementations allow it to be used this way it should be used without parentheses e.g. void 0.
So its technically wrong to use void(0)
but in practise void has two different syntaxes:
void (expression)
void expression
MDN already tells you that, though no explicit statement has been made regarding the two syntaxes, as its not technically correct.
Courtesy:
Upvotes: 2
Reputation: 173642
I have to admit that I've used that same construct many times in the past, mainly because I've seen it being used on other sites. I'm no longer using this because unobtrusive JavaScript is preferred over inline JavaScript; in fact, it's almost exclusively used inline to make sure the page doesn't refresh.
Having said that, as you have rightfully pointed out, it's an operator and not a function; the reason it still works is simply because (0)
and 0
are the same thing, so this is how it would be evaluated:
void (0);
Which is identical to:
void 0;
I guess the reason it's being written as a function invocation is because people feel more comfortable with functions when used inline :)
<a href="javascript:void 0">...</a> // hold on, that can't work, can it?!
<a href="javascript:void(0)">...</a> // ahhh, normality restored
Upvotes: 6
Reputation: 48779
"So why do people use the parens?"
People do silly things.
"Do they serve a purpose?"
No, they're not needed.
Upvotes: 2