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.
JavaScript void 0 means returning undefined (void) as a primitive value. You might come across the term “JavaScript:void(0)” while going through HTML documents. It is used to prevent any side effects caused while inserting an expression in a web page.
Description. This operator allows evaluating expressions that produce a value into places where an expression that evaluates to undefined is desired. The void operator is often used merely to obtain the undefined primitive value, usually using void(0) (which is equivalent to void 0 ).
When to use Javascript void(0) Use javascript:void(0) if, when a link is clicked, you don't want the browser to load a new page or refresh the same page (depending on the URL specified). Instead it will just perform the JavaScript attached to that link.
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
"So why do people use the parens?"
People do silly things.
"Do they serve a purpose?"
No, they're not needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With