Section B. Data types


B. Data types

Every value has a data type to define what sort of value it is.

For example, 4's data type is number, "Hello world!"'s data type is string, and the function test()'s data type is object.

The six data types

JavaScript knows four important data types and two trivial ones. The important ones are number, string, boolean, and object; the trivial ones are undefined and null, which are two distinct ways of saying "It's not there."

Numbers

Numbers are pretty self-explanatory: they're numbers. You can add, subtract, multiply, and divide numbers, and when your script requires calculations, you always use numbers. Example:

var exampleNumber = 42; 


We'll discuss numbers in 5E.

Strings

Strings are sequences of characters. When you define strings, you always surround them by either single quotes ' or double quotes ". This tells JavaScript that it's dealing with a string. Examples:

var exampleString = 'I am a JavaScript hacker'; var exampleString2 = '49'; 


Note that the second example string contains a number (or rather, two numerical characters), but since it is surrounded by quotes, as far as JavaScript is concerned it's a string.

Strings are by far the most versatile data type JavaScript has to offer, and pretty soon you'll notice that you use strings everywhere. For instance, most of the times you read out something from the DOMsay, a text the user has entered in a form fieldyou get a string.

We'll take a closer look at strings in 5F.

Booleans

Booleans know only two values: true and false. Real boolean variables are only useful when you have to answer a simple Yes/No question ("Is this form free of errors?""Did the user check this checkbox?"). Example:

var exampleBoolean = true; 


Note that there are no quotes around the true; if there were, it'd be a string, not a boolean. We'll take a look at the boolean data type in 5G.

Objects

The object data type encompasses everything that's not a number, string, or boolean. It differs from the other three types because objects are copied, passed, and compared by reference, not by value.

What does that mean? Take the following lines:

var x = 1; var y = document.getElementById('myName'); var a = x; var b = y; 


Variables x and a both contain the value 1. However, y and b both refer to the object returned by getElementById('myName'), in other words, the HTML element with .

Any change to the real, underlying object that y and b refer to shows up in both variables. Take these two lines:

b.className = 'error'; alert(y.className); 


The alert shows the value of the class attribute of the HTML element: 'error'. The fact that we used the variable b to access the element does not matter; y refers to the same object as b, and therefore it gets its data from the same source.

In contrast, x and a contain the same value, but they don't refer to any object. Anything done to the value of x does not affect a or vice versa.

We'll discuss many object data types throughout this chapter, such as arrays and functions. Although they differ in detail, they all are objects as far as data typing is concerned. We'll discuss objects in 5I.

undefined and null

Although undefined and null are closely related, they are not exactly the same.

null usually means "no object," but it may also be returned by a function if no other value fits. This is a rare occurrence, though.

For example, suppose there is no HTML element with :

var x = document.getElementById('test'); alert(x); 


x becomes null. You'll see how this comes in handy when we get to object detection (see 3C and 5G).

The undefined value is returned in three cases:

  1. If you declared a variable but did not assign a value to it.

  2. If you access an undefined property of an object (and in JavaScript you can see anything you like as a property of an object).

  3. If you have defined a function argument, but no value is passed to it. (See 5I for arguments.)

Take, for instance, this code:

var x; alert(x); 


I declared variable x explicitly (see 5D), but it doesn't have a value. Therefore the alert gives undefined.

The second rule has odd consequences:

// y is not declared alert(y); alert(window.y); 


As you'd expect, the first alert gives an error message: y is not declared. However, the second alert accesses y as a property of JavaScript's global object, the window (see 5I). Since undefined properties always have the value undefined, the alert doesn't give an error message, but instead shows "undefined."

The typeof operator

The typeof operator shows the data type of a value. Its syntax is:

typeof x; 


Note two oddities:

  • When used on functions, typeof yields "function". Nonetheless, as far as data types are concerned, functions are really objects.

  • null evaluates to "object".

This operator is extremely useful for debugging. If you think a variable may hold a string instead of a number, you insert a typeof alert. In general, this is the first debugging tool you use when you think you've encountered a data-type problem.

Sometimes typeof is used for object detection. However, since object detection often tries to find out if a certain object exists, but typeof returns "object" whether an object exists or not (i.e., is null, which evaluates to false), it's not really useful in such situations. I advise you not to use typeof for object detection, but instead stick to the rules we discussed in 3C.

Data-type conversion

One of the beauties of JavaScript is that converting values from one data type to another is quite easyin fact, it happens all the time. Take this code:

var a = 4; var b = '4'; var c = a * b; 


As you can see with your newly acquired data-type knowledge, a is a number and b is a string. The third line tries to multiply these twoan operation that obviously requires numbers.

Here's where data-type conversion kicks in. The multiplication operator needs numbers, so JavaScript tries to convert its operands to numbers, if at all possible. In this case it's easy: b is interpreted as the number 4, and c becomes 16.

It is important to realize that b does not become a number. It remains a string, but JavaScript interprets it as a number for the specific purpose of executing the multiplication.

On the other hand, the result of the multiplication (stored in c) is a number. This gives you the best of both worlds: your original variables don't change their data type, but the result of the operation has the correct data type.

Let's return to a previous example in order to show how pervasive data-type conversion is:

var x; alert(x); 


As we saw, the alert shows undefined, since x holds this value. However, alerts show strings, and therefore the value undefined is first converted to the string "undefined".

NaN

The success of data-type conversion depends on the raw materials, and that's particularly important when you convert strings to numbers. Take this example:

var exampleString = 'I am a JavaScript hacker'; var exampleNumber = 42; alert(exampleString * exampleNumber); 


In order to multiply these two values, JavaScript tries to interpret exampleString as a number. That's totally impossible, so the outcome of the multiplication is the special value NaN (Not a Number), which means "This value cannot be interpreted as a number."

NaN as a Warning

If you encounter NaN when you expect a number, you're certain to have made a data-type conversion mistake. One of the numbers you want to use is actually a string that is not convertible to a number. The error could be something obvious like a string that doesn't even contain a number, like "I am a JavaScript hacker". It could also be something more subtle, like the string value "7,000".

As soon as you see NaN appear, go through your variables and make sure they can all be interpreted as numbers.


The + problem

In general you don't have to worry about data-type conversion; it just happens automatically. There's one case, however, where a more formal understanding is necessary: when you use the + operator.

The problem with the + operator is that it can mean two things. If it's used on numbers, it means add these two numbers together, but if it's used on strings it means concatenate or sew these strings together. Concatenation is an addition of sorts, but it's radically different from the mathematical operation.

Take this example:

var a = 4; var b = '4'; var c = a + b; 


You might think c has a value of 8, but in fact it contains the string '44'. JavaScript gives precedence to string concatenation above number addition. Therefore JavaScript interprets a + b as a string concatenation, not an addition. The number is converted to a string instead of vice versa.

Obviously, the solution to this problem is to make sure that both operands are numbers.

var a = 4; var b = '4'; var c = a + (b*1); 


If we multiply b by 1 first, JavaScript uses the value returned by this operation: a number. It subsequently interprets + as add, not as concatenate.

Adding and concatenating in one line of code

Occasionally you want to add some numbers and concatenate a string in the same line of code. Let's take a look at this example:

var amount1 = 42; var amount2 = 24; var message = amount1 + amount2 + ' apples is what you ordered'; 


message now becomes the string '66 apples is what you ordered'. This may seem odd, since we just saw that concatenation is stronger than addition. But it's the order of the variables and operators here that matters.

JavaScript first encounters amount1 + amount2 and has to decide whether the + means addition or concatenation. It looks at the two operands amount1 and amount2, sees that they're both numbers, and therefore adds them, resulting in the number 66.

Then it encounters the next +, which now means 66 + ' apples is what you ordered'. It again looks at the operands, sees that one of them is a string, and interprets the + as concatenate. Therefore message becomes '66 apples is what you ordered'.

As you see, JavaScript goes through + operators from left to right, and decides on an individual basis whether they mean add or concatenate. Therefore, the next example will not do what you want:

var amount1 = 42; var amount2 = 24; var message = 'You ordered' + amount1 + amount2 + ' apples'; 


When JavaScript encounters the 'You ordered' + amount1 bit, it interprets the + as a concatenation, since one of the operands is a string. This results in the string 'You ordered 42'. Since one of their operands is a string, the second and third + also mean concatenate, and the result becomes 'You ordered 4224 apples'.

Fortunately, just as in mathematics, you can use parentheses () to say "Handle this operation first." Therefore, the solution is:

var message = 'You ordered ' + (amount1 + amount2) + ' apples.'; 


JavaScript handles the (amount1 + amount2) operation first, and in this context + clearly means add, resulting in the number 66. Then it goes through the other + operators from left to right, and they clearly mean concatenate. Now message reads 'You ordered 66 apples'.

Converting to boolean

JavaScript has rules to convert every data type into every other data type. You'll rarely need most of these rulessituations in which you want to convert an object to a number are not very common. However, converting the other data types to booleans forms the basis of object detection, as we discussed in 3C.

These are the rules for converting other data types to booleans:

  • The values null and undefined become false.

  • The numbers 0 and NaN become false.

  • An empty string '' becomes false.

  • All other values become true.

We'll get back to this important conversion in 5G.

Explicit data-type conversion

I demonstrated this line of code earlier. It's an example of explicit data-type conversion:

var c = a + (b*1); 


The idea is straightforward: perform the simplest possible operation that converts the variable to the desired data type. Multiplying by 1 is one simple way of converting a string to a number. Subtracting 0 is another:

var c = a + (b-0); 


You can convert a variable to a string by concatenating it with an empty string:

var string = number_or_boolean_or_object + ''; 


Converting a variable to a boolean is best done by performing the NOT (!) operation twice:

var boolean = !!number_or_string_or_object; 


We'll take a closer look at this operation in 5G.

Tricky Operators

Beware of the following two operators:

+ can mean both add and concatenate. (I discussed this in 5B.)

() executes a function. Sometimes, however, you want to transfer an entire function to another variable instead of executing it. In that case, you must omit the (). (See 5I and 7C.)




ppk on JavaScript. Modern, Accessible, Unobtrusive JavaScript Explained by Means of Eight Real-World Example Scripts2006
ppk on JavaScript. Modern, Accessible, Unobtrusive JavaScript Explained by Means of Eight Real-World Example Scripts2006
ISBN: N/A
EAN: N/A
Year: 2005
Pages: 116

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net