void (Operator/unary)

Force an undefined value to replace an operand.


ECMAScript edition - 2
JavaScript - 1.1
JScript - 2.0
Internet Explorer - 4.0
Netscape - 3.0
Opera - 3.0
Property/method value type:Undefined primitive
JavaScript syntax:-void (anExpression)
-void anExpression
Argument list:anExpressionAn expression to be evaluated

The void operator is used to allow the operand to be evaluated in the normal way (perhaps it is an expression or function call), but to force an undefined value to be returned in its place.

A very useful place for this is when you create JavaScript: URLs. Making sure the result of the expression is void helps the browser cope with the fact you are calling a script and not fetching a document. Don't use void however if you want the result of the JavaScript execution to be used as the content of a window.

This shows how to use void in a click handler:

   <a HREF="javascript:void(callHandler('testString'));">

This shows how to force JavaScript result data into a window:

   <a HREF="javascript:'<HR>Some text here</HR>'">

You can also use the void operator to manufacture an undefined value in older browsers that have no keyword already defined. The expression (void 0) is just such a value. This is unnecessary now that JScript 5.5 supports an undefined value in compliance with ECMA edition 2.

The associativity is from right to left.

Refer to the operator precedence topic for details of execution order.

This keyword also represents a Java data type and the void keyword allows for the potential extension of JavaScript interfaces to access Java applet parameters and return values.

This technique is also useful if you want to evaluate an expression merely for the benefit of its side effects and without any interest in the value it returns.


Example code:

   if(document.myUndefinedProperty == (void 0))
   document.write("An undefined property has been referenced");
   document.write("A defined property was used");

See also:Assignment expression, Associativity, javascript: URL, LiveConnect, Operator, Operator Precedence, typeof, Unary expression, Unary operator, undefined


ECMA 262 edition 2 - section - 11.4.2

ECMA 262 edition 3 - section - 11.4.2

Wrox Instant JavaScript - page - 21