Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Many people write `javascript:void(0)` instead of `javascript:void 0` in hrefs. Do the parentheses do anything?

Tags:

javascript

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.

like image 471
dmnd Avatar asked Dec 01 '12 04:12

dmnd


People also ask

What is JavaScript void 0 in href?

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.

What does JavaScript void () do?

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

Should I use JavaScript 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.


2 Answers

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
like image 170
Ja͢ck Avatar answered Sep 28 '22 15:09

Ja͢ck


"So why do people use the parens?"

People do silly things.

"Do they serve a purpose?"

No, they're not needed.

like image 45
I Hate Lazy Avatar answered Sep 28 '22 15:09

I Hate Lazy