1

Possible Duplicate:
what is the point of void in javascript
What does “javascript:void(0)” mean?

Everywhere I see this javascript:void(0); to do nothing I think. (instead of this javascript:; can be used I think)

And that day I see javascript:void(x=document.getElementById('mytext').value);void(document.getElementById('mylabel').innerHTML=x); code in the page.

My question is very simple, why void? What void does?

Community
  • 1
  • 1
totten
  • 2,558
  • 3
  • 24
  • 40
  • 1
    Please don't remove the automatically added text. The system adds it according to links provided by users. Both those links contain answers that can together answer your question here. – Lix Sep 13 '12 at 19:18
  • 1
    It's less about a duplicate question - and more about the fact that an existing answer could also answer your question here. – Lix Sep 13 '12 at 19:19

3 Answers3

3

MDN documentation page

This operator allows inserting expressions that produce side effects 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"). In these cases, the global variable undefined can be used instead (assuming it has not been assigned to a non-default value).

3on
  • 6,117
  • 3
  • 23
  • 22
2

void is an operator which returns undefined, although evaluation the following expression. The brackets are not needed.

In javascript:-urls it is used because any return value would overwrite the current document (like document.write()).

Bergi
  • 513,640
  • 108
  • 821
  • 1,164
1

I believe this is a sort of alternative to simply terminating the click even in jQuery for example. When you attach a click handler to an anchor tag, you should always return false at the end of the handler -

$("#btn").on('click',function(){
  // make toast
  return false;
});

Returning false cancels any other actions that would have been executed by the event.

When you attach a javasctipt:void(0) to the onclick of an element, you are preventing that event from doing anything and leaving all the work to your JavaScript.

Lix
  • 45,171
  • 10
  • 95
  • 118
  • 2
    'javascript:'-urls are assigned to the `href` attribute. `void 0` is like setting the default action to "nothing". – Bergi Sep 14 '12 at 09:59