04.11.2015 Views

javascript

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 3: Language Basics<br />

In this example, the variable message is declared without initializing it. When compared with the literal<br />

value of undefined , the two are equal. This example is identical to the following:<br />

var message = undefined;<br />

alert(message == undefined);<br />

//true<br />

Here the variable message is explicitly initialized to be undefined . This is unnecessary because, by<br />

default, any uninitialized variable gets the value of undefined .<br />

Generally speaking, you should never explicitly set a variable to be undefined.<br />

The literal undefined value is provided mainly for comparison and wasn’t added<br />

until ECMA-262 Third Edition to help formalize the difference between an empty<br />

object pointer and an uninitialized variable.<br />

Note that a variable containing the value of undefined is different from a variable that hasn ’ t been<br />

defined at all. Consider the following:<br />

var message;<br />

//this variable is declared but has a value of undefined<br />

//make sure this variable isn’t declared<br />

//var age<br />

alert(message); //”undefined”<br />

alert(age); //causes an error<br />

In this example, the first alert displays the variable message , which is undefined. In the second alert, an<br />

undeclared variable called age is passed into the alert() function, which causes an error because the<br />

variable hasn ’ t been declared. Only one operation can be performed on an undeclared variable: you can<br />

call typeof on it.<br />

The typeof operator returns “undefined” when called on an uninitialized variable, but it also returns<br />

“undefined” when called on an undeclared variable, which can be a bit confusing. Consider this<br />

example:<br />

var message;<br />

//this variable is declared but has a value of undefined<br />

//make sure this variable isn’t declared<br />

//var age<br />

alert(typeof message); //”undefined”<br />

alert(typeof age); //”undefined”<br />

In both cases, calling typeof on the variable returns the string “undefined” . Logically, this makes<br />

sense because no real operations can be performed with either variable even though they are technically<br />

very different.<br />

29

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!