What kind of expressions do * side effects * produce?

I find it hard to understand this paragraph on the page https://developer.mozilla.org/en/JavaScript/Reference/Operators/Special/void :

This operator allows you to insert expressions that cause side effects in places where undefined is required.

What kind of expressions produce side effects?

+6
source share
5 answers

A function does two things normally: do something and return a value. Some functions perform only one of these things, some do both. For example, the function:

function square(x) { return x * x; } 

It is a side effect since everything that it does returns a value, and its call can always be replaced by its return value. On the other hand, something like alert() is called only for its side effects (warning the user) and never for the return value.

So, what the void operator does is make JavaScript ignore the return value and indicate that all you are interested in are side effects of the function.

+6
source

A simple example is a function call. If you need the value "undefined", but you also want to call a function that (say) performs some manipulations with the DOM, you can "distinguish" the result from void and get the result undefined.

I definitely don't think this would be in the “good parts” of the language, although it circumvented the strange fact that “undefined” is not really a reserved word. The expression void 0 will certainly be truly undefined.

+2
source

The expression (i+=1) is evaluated as i+1 , but has the side effect of incrementing i by 1.

The goal of void is not to mask side effects, specifically when you want to get side effects, but don't want the result of an expression.

+2
source

"Side effects" is the result of a function that void takes as an argument. In this case, the F1 function returns false, but wrapping it in void essentially swallows the result or side effect:

 var F1 = function() { return false; } void(F1()); 

I apologize for the free use of quotes ... ha ha.

+1
source

Here is an example:

 <a href="javascript:void(**do stuff here**)">link</a> 

Emptiness forces him to return nothing. Without void, potentially some return value will cause the link to remove the user from the page.

+1
source

Source: https://habr.com/ru/post/891779/


All Articles