8

Possible Duplicate:
what is the point of void in javascript

What is purpose of using void here ? if 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);
}
Community
  • 1
  • 1
nandin
  • 2,549
  • 5
  • 23
  • 27

3 Answers3

5

void is a keyword that runs an expression and returns undefined

void 0 === undefined

void (foo = 42) === undefined

As to how href="javascript:..." work.

unless the returned value is undefined.

You need to return undefined or else the page is overwritten. Using the void keyword is the easiest way to achieve this.

Raynos
  • 166,823
  • 56
  • 351
  • 396
4

Yes. it will work without void.

it isn't necessary to use void there.

Falcon
  • 1,461
  • 3
  • 15
  • 29
  • 6
    .. except for the part where it'll replace the contents of the page. – drudge May 25 '11 at 19:27
  • 1
    ...which won't happen, because the statements are not an expression in a `javascript:` link. – bobince May 25 '11 at 19:58
  • it is part of a javascript: bookmarklet. [google reader subscription bookmarklet](http://forums.mozillazine.org/viewtopic.php?f=23&t=2513807) – Andrew Mar 04 '13 at 06:58
3

I googled your code snippet and it looks like its typically embedded in a link with "javascript:" in front of it. To quote the Mozilla reference for the void operator:

JavaScript URIs

When a browser follows a javascript: URI, it evaluates the code in the URI and then replaces the contents of the page with the returned value, unless the returned 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 over other alternatives, such as events.

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

So it keeps the contents of the page from being overwritten when the code is executed inside of a link.

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

patorjk
  • 2,164
  • 1
  • 20
  • 30