-3

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:

<html>
 <head>

 </head>
 <body>

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

 </body>
</html>

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?.

closed as off-topic by gnat, Adam Zuckerman, Jörg W Mittag, psr, TZHX Jul 5 '16 at 20:10

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions asking for assistance in writing or debugging existing code are off-topic on Programmers. These questions can be asked on Stack Overflow if they include the desired behavior, a specific problem or error, and the shortest code necessary to reproduce it in the question itself. See How To Create a Minimal, Complete, and Verifiable Example." – gnat, Adam Zuckerman, Jörg W Mittag, psr, TZHX
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 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
4

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.