I'm so confused about how Void operator (in javascript) works and what is it's role. as i read, Void is an operator that evaluate an expression without returning a value, but by executing that script for example:



  <a href="javascript:void(alert(1+1))">Click me!</a>


After clicking on the link, the browser shows the value 2, which mustn't be shown since the evaluated expression (alert(1+1)) shouldn't return a value due to being an operand of the Void operator.
Can someone clear it up for me please?.

  • Your code is doing what you are telling it to. The void method says to ignore any returned value from the inner expression (e.g., alert(1+1) ). That doesn't stop it from being processed. – Adam Zuckerman Jun 29 '16 at 0:11
  • Right; specifying void as the return type only prevents something from being returned from the Javascript function; it doesn't prevent the alert expression from being evaluated. – Robert Harvey Jun 29 '16 at 1:29
  • @RobertHarvey What is the 'something' in this situation?. – Mehdi Jun 29 '16 at 2:29
  • @Mehdi: Whatever the expression inside the function evaluates to (in this case, whatever alert(1+1) returns. – Robert Harvey Jun 29 '16 at 3:00
  • 1
    Window.alert() is a method. It doesn't return anything. – Robert Harvey Jun 29 '16 at 15:06

Return values and side effects are two different things. void eliminates the return value, it has no effect on side effects:

This operator allows inserting expressions that produce side effects into places where an expression that evaluates to undefined is desired.

alert() produces a window as a side effect, not a return value. 1+1 is an expression that does return a value, but that return value is handled by alert(), not the void operator.

Note that alert() might not return a value normally, it does not in Firefox 47, making the void wrapper redundant in this particular case.

Not the answer you're looking for? Browse other questions tagged or ask your own question.