Why does an expression for a Javascript function that returns void still execute? [closed]

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

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

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *