What is the purpose of using `void` here?

Possible duplicate:
what is the javascript invalidation point

What is the purpose of using void here? if you just remove void() , it should also work, right?

 var b=document.body; if(b&&!document.xmlVersion) { void(z=document.createElement('script')); void(z.src='http://www.google.ca/reader/ui/subscribe-bookmarklet.js'); void(b.appendChild(z)); } else { location='http://www.google.com/reader/view/feed/'+encodeURIComponent(location.href); } 
+8
javascript
source share
3 answers

I was looking for your piece of code and it looks like it is usually embedded in a link with "javascript:" in front of it. To specify a Mozilla link for the void operator:

JavaScript URI

When the browser follows the javascript: URI, it computes the code in the URI and then replaces the contents of the page with the return value, unless the return value is undefined. The void operator can be used to return undefined. For example:

 <a href="javascript:void(0);">Click here to do nothing</a> <a href="javascript:void(document.body.style.backgroundColor='green');">Click here for green background</a> 

Note, however, that javascript: URIs are now often discouraged by other alternatives, such as events.

source: https://developer.mozilla.org/en/JavaScript/Reference/Operators/Special/void

Thus, the contents of the page will be overwritten when the code is executed inside the link.

In this case, if the code is executed without Javascript: URI, the void operator should not have any value. The void operator simply evaluates its input expression and returns undefined.

+3
source share

void is a keyword that starts an expression and returns undefined

void 0 === undefined

void (foo = 42) === undefined

How href="javascript:..." works.

if the return value is not equal to undefined.

You need to return undefined , otherwise the page will be overwritten. Using the void keyword is the easiest way to achieve this.

+5
source share

Yes. he will work without emptiness.

no need to use void.

+4
source share

All Articles