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 />

Even though uninitialized variables are automatically assigned a value of<br />

undefined, it is advisable to always initialize variables. That way, when typeof<br />

returns “undefined”, you’ll know that it’s because a given variable hasn’t been<br />

declared rather than simply not having been uninitialized.<br />

The Null Type<br />

The Null type is the second data type that has only one value: the special value null . Logically, a null<br />

value is an empty object pointer, which is why typeof returns “object” when it ’ s passed a null value<br />

in the following example:<br />

var car = null;<br />

alert(typeof car);<br />

//”object”<br />

When defining a variable that is meant to later hold an object, it is advisable to initialize the variable to<br />

null as opposed to anything else. That way, you can explicitly check for the value null to determine if<br />

the variable has been filled with an object reference at a later time, such as in this example:<br />

if (car != null){<br />

//do something with car<br />

}<br />

The value undefined is a derivative of null , so ECMA - 262 defines them to be superficially equal as follows:<br />

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

//true<br />

Using the equality operator ( == ) between null and undefined always returns true , though keep in<br />

mind that this operator converts its operands for comparison purposes (covered in detail later in this<br />

chapter).<br />

Even though null and undefined are related, they have very different uses. As mentioned previously,<br />

you should never explicitly set the value of a variable to undefined , but the same does not hold true for<br />

null . Any time an object is expected but is not available, null should be used in its place. This helps to<br />

keep the paradigm of null as an empty object pointer and further differentiates it from undefined .<br />

The Boolean Type<br />

The Boolean type is one of the most frequently used types in ECMAScript and has only two literal<br />

values: true and false . These values are distinct from numeric values, so true is not necessarily equal<br />

to 1, and false is not necessarily equal to 0. Assignment of Boolean values to variables is as follows:<br />

var found = true;<br />

var lost = false;<br />

Note that the Boolean literals true and false are case-sensitive, so True and False (and other mixings<br />

of uppercase and lowercase) are valid as identifiers but not as Boolean values.<br />

30

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

Saved successfully!

Ooh no, something went wrong!