Sams Teach Yourself HTML, CSS & JavaScript Web Publishing in One Hour a Day

(singke) #1
ptg16476052

The JavaScript Language 489

17


Boolean values represent a state of either true or false. You’ve already seen some exam-
ples that involve Boolean values. For example, if statements and while loops require
conditional expressions that return a Boolean value. Any JavaScript value or expression
can ultimately be converted to a Boolean. The values that are treated as false are the
number zero, empty strings, null, undefined, and NaN. Everything else is true.


To explicitly convert data from one type to another, you can type casting functions. They
are Number(), Boolean(), and String(). Type casts to Boolean are the most interesting
because they allow you to see the Booelan value of an expression. For exam ple, to con-
firm that NaN is false, you could type the following in the Console:


Boolean(Math.sqrt("a"))


Arrays


Arrays are lists of things. They can be lists of values, lists of objects, or even lists of lists.
There are a couple of ways to declare arrays. The first is to create your own Array object,
like this:


var list = new Array(10);


That declares an array with 10 slots. Arrays are numbered (or indexed) starting at 0, so
an array with ten elements has indexes from 0 to 9. You can refer to a specific item in an
array by placing the index inside square brackets after the array name. So, to assign the
first element in the array, you use the following syntax:


list[0] = "Element 1";


If you want to add elements to your array when you declare it, you can use what’s called
an array literal, like this:


var list = ["red", "green", "blue"];


To find out how many elements are in an array, you can use a property of the array called
length. Here’s an example :


listLength = list.length


Objects


You’ve already been introduced to a few objects—most recently, the Array object.
JavaScript features a number of built-in objects, and the browser supplies even more (as
discussed in the next section). The first thing you need to know about objects is that they
have properties. You just saw one property: the length property of the Array object.

Free download pdf