I've seen some people using void
operator in their code. I have also seen this in href
attributes: javascript:void(0)
which doesn't seem any better than javascript:;
So, what is the justification of using the void
operator?
I've seen some people using void
operator in their code. I have also seen this in href
attributes: javascript:void(0)
which doesn't seem any better than javascript:;
So, what is the justification of using the void
operator?
Consider the following:
The first link will swap the values of the text fields. The second link will open a new page with the text "one fish". If you use a
javascript: link
, the minute an expression returns something other thannull
orundefined
, the browser will interpret that as what the link should do. By wrapping all expressions/statments in avoid()
function, you ensure your entire snippet of code will run. These days, this is primarily of use in Bookmarklets, as using anonclick
attribute, or setting up event handlers in separate Javascript blocks/files is the "norm".As for
javascript:
vs.javascript:void()
, the first statement is ambiguous. You're saying, "hey, I want to run some javascript", but then you don't provide any code. It's not necessarily clear what the browser should do here. With the second statement you're saying "hey, run some javascript", and your code eventually returns undefined, which the browser knows means "do nothing".Since I'm here, I'll also point out that using either
javascript:
orjavascript:void();
has fallen out of favor with most people who care about markup. The better thing to do is have your onclick handler return false, and have the link pointed towards a page/resource that makes sense for people who have javascript turned off, or are using a javascript blocker such as NoScript.The
undefined
value was not directly accessible in JavaScript until ES1.3.An operator
void <expression>
was therefore included to permit access to this value.It is sometimes useful, particularly when working with the Web API (e.g. event handlers), to ensure that the result of an expression is consistently
undefined
.When the
undefined
property was added to the global object in ES1.3 the utility ofvoid
became non-obvious.Hence your question.
Explanation of its use in links: