Skip to content Skip to sidebar Skip to footer

Why Does The Void Operator Invoke Getvalue(expr) When It Always Evaluates To Undefined?

The void operator in JavaScript will call the internal GetValue(expr), but always return undefined, regardless of what value or expressions are. The spec says: 11.4.2 The void Op

Solution 1:

If you're writing a program with no side effects, then a function that always returns undefined isn't helpful because it does not return useful information back to the caller. In that case, you might as well not call the function at all if you always know what you'll be getting back.

However, if a language has "side effects", even functions that return undefined can still be programatically useful. "Side-effects" is a technical term for some effect that's not a part of the return value of a function. As a concrete example, mutating the DOM is a side effect that doesn't compute and return a useful value, but you still want the state of your DOM tree to mutate. Playing a sound is also a side effect.

As a side note, void can be useful since, grammatically, it forces an expression context, so that things like function expression values can be expressed unambiguously. e.g.

void function(){alert('hi')}()

Solution 2:

I've seen this a few times with use cases such as:

javascript:voidwindow.open("http://foo.com")

This can be used in bookmarklets to avoid changing the value on the address bar, but still executing the code - so you would obviously want to evaluate that function and not just ignore it.

It's also sometimes used by paranoid programmers who don't trust that undefined was not overridden somewhere. If you really need to know undefined, you can compare it to void 0 (since void is a reserved keyword, it cannot be used as a function name).

Post a Comment for "Why Does The Void Operator Invoke Getvalue(expr) When It Always Evaluates To Undefined?"