November 20, 1999 - The void Operator
November 20, 1999 The void Operator Tips: November 1999
Yehuda Shiran, Ph.D.
|
void
operator specifies an expression to be evaluated without returning a value. Its syntax may be similar to one of the following:
void foo()
javascript:void foo()
or:
void(foo())
javascript:void(foo())
Let's examine the following example:
function foo() {
alert("Function Entered");
return true;
}
alert(foo());
The preceding script segment displays two alert boxes. The first box displays the string "Function Entered"
, as expected. The second box displays what the function foo()
returns, the Boolean true
. Now, let's look at a slightly different foo()
:
function foo() {
alert("Function Entered");
return true;
}
alert(void foo());
This script also generates two alerts, but the second one reads "undefined"
, because the void
operator evaluates the function without returning a value.
A more important use of this operator is in hypertext links, where it is used to evaluate a JavaScript expression in line. The expression is evaluated but it is not loaded back into the current document. The following link does nothing because the expression "0"
has no effect in JavaScript:
<A HREF="javascript:void(0)">Click here to do nothing</A>
The following link generates an alert box when the link is clicked:
<A HREF="javascript:void(alert('Wow'))">Click here to display a message</A>
The parentheses are optional. We chose to use them in order to make the script more readable.