Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

share|improve this 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 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 at 1:29
    
@RobertHarvey What is the 'something' in this situation?. – Mehdi Jun 29 at 2:29
    
@Mehdi: Whatever the expression inside the function evaluates to (in this case, whatever alert(1+1) returns. – Robert Harvey Jun 29 at 3:00
1  
Window.alert() is a method. It doesn't return anything. – Robert Harvey Jun 29 at 15:06
up vote 4 down vote accepted

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.

share|improve this answer
    
I digested it, thanks a lot. – Mehdi Jun 29 at 15:18

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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