spacer
Yehuda Shiran November 20, 1999
The void Operator
Tips: November 1999

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
Microsoft Shows Off Silverlight 4, IE9 Plans
Metasploit Expands Vulnerability Test Framework
HyperCard Reborn?

The 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.


People who read this tip also read these tips:

Look for similar tips by subject:

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs

webref The latest from WebReference.com Browse >
Rolling Out Your Own HTML Application Version Control · HTML 5: Client-side Storage · Working with Ajax Server Extensions
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Wi-Fi Product Watch, November 2009 · Chip Market Recovering From '08 Collapse · Low-Cost Tools to Kickstart Your New Business