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

6
  • 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. Commented Jun 29, 2016 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. Commented Jun 29, 2016 at 1:29
  • @RobertHarvey What is the 'something' in this situation?. Commented Jun 29, 2016 at 2:29
  • @Mehdi: Whatever the expression inside the function evaluates to (in this case, whatever alert(1+1) returns. Commented Jun 29, 2016 at 3:00
  • 1
    Window.alert() is a method. It doesn't return anything. Commented Jun 29, 2016 at 15:06

1 Answer 1

3

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.

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.