Working with Variables and Data Types in JavaScript
- 6/15/2013
- Data types in JavaScript
- Defining and using variables
- Using the RegExp object
- Learning about type conversions
- Exercises
After completing this chapter, you will be able to
Understand the primitive data types used in JavaScript.
Use functions associated with the data types.
Create variables.
Define objects and arrays.
Understand the scope of variables.
Debug JavaScript using Firebug.
Data types in JavaScript
The data types of a language describe the basic elements that can be used within that language. You’re probably already familiar with data types, such as strings or integers, from other languages. Depending on who you ask, JavaScript defines anywhere from three to six data types. (The answer depends largely on the definition of a data type.) You work with all these data types regularly, some more than others.
The six data types in JavaScript discussed in this chapter are as follows:
Numbers
Strings
Booleans
Null
Undefined
Objects
The first three data types—numbers, strings, and Booleans—should be fairly familiar to programmers in any language. The latter three—null, undefined, and objects—require some additional explanation. I examine each of the data types in turn and explain objects further in Chapter 8.
Additionally, JavaScript has several reference data types, including the Array, Date, and RegExp types. The Date and RegExp types are discussed in this chapter, and the Array type is discussed in Chapter 8.
Working with numbers
Numbers in JavaScript are just what you might expect them to be: numbers. However, what might be a surprise for programmers who are familiar with data types in other languages like C is that integers and floating point numbers do not have special or separate types. All these are perfectly valid numbers in JavaScript:
4 51.50 -14 0xd
The last example, 0xd, is a hexadecimal number. Hexadecimal numbers are valid in JavaScript, and you won’t be surprised to learn that JavaScript allows math to be performed using all of the listed number formats. Try the following exercise.
Performing hexadecimal math with JavaScript
Using Microsoft Visual Studio, Eclipse, or another editor, edit the file example1.html in the Chapter04 sample files folder in the companion content.
Within the webpage, replace the TODO comment with the boldface code shown here:
<!doctype html> <html> <head> <title>Hexadecimal Numbers</title> <script type="text/javascript"> var h = 0xe; var i = 0x2; var j = h * i; alert(j); </script> </head> <body> </body> </html>
View the webpage in a browser. You should see a dialog box similar to this one:
The preceding script first defines two variables (you learn about defining variables later in this chapter) and sets them equal to two hexadecimal numbers, 0xe (14 in base 10 notation) and 0x2, respectively:
var h = 0xe; var i = 0x2;
Then a new variable is created and set to the product of the previous two variables, as follows:
var j = h * i;
The resulting variable is then passed to the alert() function, which displays the dialog box in the preceding step 3. It’s interesting to note that even though you multiplied two hexadecimal numbers, the output in the alert dialog box is in base 10 format.
Numeric functions
JavaScript has some built-in functions (and objects, too, which you learn about soon) for working with numeric values. The European Computer Manufacturers Association (ECMA) standard defines several of them. One more common numeric function is the isNaN() function. By common, I mean that isNaN() is a function that I use frequently in JavaScript programming. Your usage might vary, but an explanation follows nonetheless.
NaN is an abbreviation for Not a Number, and it represents an illegal number. You use the isNaN() function to determine whether a number is legal or valid according to the ECMA-262 specification. For example, a number divided by zero would be an illegal number in JavaScript. The string value “This is not a number” is obviously also not a number. Although people might have a different interpretation of what is and isn’t a number, the string “four” is not a number to the isNaN() function, whereas the string “4” is. The isNaN() function requires some mental yoga at times because it attempts to prove a negative—that the value in a variable is not a number. Here are a couple of examples that you can try to test whether a number is illegal.
Testing the isNaN() function (test 1)
In Microsoft Visual Studio, Eclipse, or another editor, create a new HTML file or edit the isnan.html file in the companion content.
In the file, place the following markup. If you’ve created a new file with Vision Studio, delete any existing contents first.
<!doctype html> <html> <head> <title>isNaN</title> </head> <body> <script type="text/javascript"> document.write("Is Not a Number: " + isNaN("4")); </script> </body> </html>
View this page in a browser. In Visual Studio, press F5. You’ll see a page like this one:
The function isNaN() returns false from this expression because the integer value 4 is a number. Remember that the meaning of this function is, “Is 4 Not a Number?” Well, 4 is a number, so the result is false.
Now consider the next example.
Testing the isNaN() function (test 2)
If you’re running through Microsoft Visual Studio, stop the project. For those not running Visual Studio, close the web browser.
Edit isnan.html.
Change the isNaN() function line to read:
document.write("Is Not a Number: " + isNaN("four"));
View the page in a browser, or rerun the project in Visual Studio. You’ll now see a page like this:
In second test case, because the numeral 4 is represented as a string of nonnumeric characters (four), the function returns true: the string four is not a number. I purposefully used double quotation marks in each code example (that is, “4” and “four”) to show that the quotation marks don’t matter for this function. Because JavaScript is smart enough to realize that “4” is a number, JavaScript does the type conversion for you. However, this conversion can sometimes be a disadvantage, such as when you’re counting on a variable or value to be a certain type.
The isNaN() function is used frequently when validating input to determine whether something—maybe a form variable—was entered as a number or as text.
The Math object
The Math object is a special built-in object used for working with numbers in JavaScript, and it has several properties that are helpful to the JavaScript programmer, including properties that return the value of pi, the square root of a number, a pseudo-random number, and an absolute value. Some properties are value properties, meaning they return a value, whereas others act like functions and return values based on the arguments sent into them. Consider this example of the Math.PI value property. Place this code between the opening <SCRIPT TYPE=“text/javascript”> and closing </-SCRIPT> tags in your sample page:
document.write(Math.PI);
The result is shown in Figure 4-1.
Figure 4-1 Viewing the value of the Math.PI property.
Several other properties of the Math object can be helpful to your program. Some of them act as functions or methods on the object, several of which are listed in Table 4-2. You can obtain a complete list of properties for the Math object in the ECMA-262 specification at http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf.
Table 4-2 Select function properties of the Math object
Property |
Definition |
Math.random() |
Returns a pseudo-random number |
Math.abs(x) |
Returns the absolute value of x |
Math.pow(x,y) |
Returns x to the power of y |
Math.round(x) |
Returns x rounded to the nearest integer value |
Working with strings
Strings are another basic data type available in JavaScript. They consist of one (technically zero) or more characters surrounded by quotation marks. The following examples are strings:
“Hello world”
“B”
“This is ‘another string’”
The last example in the preceding list requires some explanation. Strings are surrounded by either single or double quotation marks. Strings enclosed in single quotation marks can contain double quotation marks. Likewise, a string enclosed in double quotation marks, like the ones you see in the preceding example, can contain single quotation marks. So basically, if the string is surrounded by one type of quotation mark, you can use the other type within it. Here are some more examples:
‘The cow says “moo”.’
‘The talking clock says the time is “Twelve Noon”.’
“‘Everyone had a good time’ was the official slogan.”
Escaping quotation marks
If you use the same style of quotation mark both within the string and to enclose the string, the quotation marks must be escaped so that they won’t be interpreted by the JavaScript engine. A single backslash character (\) escapes the quotation mark, as in these examples:
‘I\’m using single quotation marks both outside and within this example. They\’re neat.’
“This is a \“great\” example of using \“double quotes\” within a string that’s enclosed with \“double quotes\” too.”
Other escape characters
JavaScript enables other characters to be represented with specific escape sequences that can appear within a string. Table 4-3 shows those escape sequences.
Table 4-3 Escape sequences in JavaScript
Escape character |
Sequence value |
\b |
Backspace |
\t |
Tab |
\n |
Newline |
\v |
Vertical tab |
\f |
Form feed |
\r |
Carriage return |
\\ |
Literal backslash |
Here’s an example of some escape sequences in action.
Using escape sequences
In Visual Studio, Eclipse, or another editor, open your sample page.
Within the <SCRIPT> section, place the following line of JavaScript:
document.write("hello\t\t\"hello\"goodbye");
View the page in a browser. You’ll see a page like the following. Notice that the tab characters don’t show through because the browser interprets HTML and not tab characters.
This rather contrived example shows escape sequences in action. In the code, the word hello is followed by two tabs, represented by their escape sequence of \t, followed by an escaped double-quote \” and then the word hello followed by another escaped double-quote \”, finally followed by the word goodbye.
String methods and properties
JavaScript defines several properties and methods for working with strings. These properties and methods are accessed using dot notation (“.”), explained earlier in this chapter and familiar to many programmers.
The length property on a string object gives the length of a string, not including the enclosing quotation marks. The length property can be called directly on a string literal, as in this example:
alert("This is a string.".length);
However, it’s much more common to call the length property on a variable, like this:
var x = "This is a string."; alert(x.length);
Both examples give the same result.
Some commonly used string methods, besides substring, include slice, substr, concat, toUpperCase, toLowerCase, and the pattern matching methods of match, search, and replace. I discuss each of these briefly.
Methods that change strings include slice, substring, substr, and concat. The slice and substring methods return string values based on another string. They accept two arguments: the beginning position and an optional end position. Here are some examples:
var myString = "This is a string."; alert(myString.substring(3)); //Returns "s is a string." alert(myString.substring(3,9)); //Returns "s is a" alert(myString.slice(3)); //Returns "s is a string." alert(myString.slice(3,9)); //Returns "s is a"
A subtle difference between slice and substring is how they handle arguments with negative values. The substring method will convert any negative values to 0, while slice will treat negative arguments as the starting point from the end of the string (counting backwards from the end, essentially).
The substr method also accepts two arguments: the first is the beginning position to return, and, in contrast to substring/slice, the second argument is the number of characters to return, not the stopping position. Therefore, the code examples for substring/slice work a little differently with substr:
var myString = "This is a string."; alert(myString.substr(3)); //Returns "s is a string." (The same as substring/slice) alert(myString.substr(3,9)); //Returns "s is a st" (Different from substring/slice)
The concat method concatenates two strings together:
var firstString = "Hello "; var finalString = firstString.concat("World"); alert(finalString); //Outputs "Hello World"
It’s somewhat more common to use the plus sign (+) for concatenation, so the same output could be accomplished with this:
var finalString = firstString + "World";
The toUpperCase and toLowerCase methods, and their brethren toLocaleUpperCase and toLocaleLowerCase, convert a string to all uppercase or all lowercase, respectively:
var myString = "this is a String"; alert(myString.toUpperCase()); // "THIS IS A STRING" alert(myString.toLowerCase()); // "this is a string"
As I stated, numerous string properties and methods exist. The remainder of the book features other string properties and methods, and you can always find a complete list within the ECMA specification at http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf.
Booleans
Booleans are kind of a hidden, or passive, data type in JavaScript. By hidden, or passive, I mean that you don’t work with Booleans in the same way that you work with strings and numbers; you can define and use a Boolean variable, but typically you just use an expression that evaluates to a Boolean value. Booleans have only two values, true and false, and in practice, you rarely set variables as such. Rather, you use Boolean expressions within tests, such as an if/then/else statement.
Consider this statement:
If (myNumber > 18) { //do something }
A Boolean expression is used within the if statement’s condition to determine whether the code within the braces will be executed. If the content of the variable myNumber is greater than the integer 18, the Boolean expression evaluates to true; otherwise, the Boolean evaluates to false.
Null
Null is another special data type in JavaScript (as it is in most languages). Null is, simply, nothing. It represents and evaluates to false. When a value is null, it is nothing and contains nothing. However, don’t confuse this nothingness with being empty. An empty value or variable is still full; it’s just full of emptiness. Emptiness is different from null, which is just plain nothing. For example, defining a variable and setting its value to an empty string looks like this:
var myVariable = '';
The variable myVariable is empty, but it is not null.
Undefined
Undefined is a state, sometimes used like a value, to represent a variable that hasn’t yet contained a value. This state is different from null, although both null and undefined can evaluate the same way. You’ll learn how to distinguish between a null value and an undefined value in Chapter 5.
Objects
Like functions, objects are special enough to get their own chapter (Chapter 8, to be exact). But I still discuss objects here briefly. JavaScript is an object-based language, as opposed to a full-blown object-oriented language. JavaScript implements some functionality similar to object-oriented functionality, and for most basic usages of JavaScript, you won’t notice the difference.
Objects in JavaScript are a collection of properties, each of which can contain a value. These properties—think of them as keys—enable access to values. Each value stored in the properties can be a value, another object, or even a function. You can define your own objects with JavaScript, or you can use the several built-in objects.
Objects are created with curly braces, so the following code creates an empty object called myObject:
var myObject = {};
Here’s an object with several properties:
var dvdCatalog = { "identifier": "1", "name": "Coho Vineyard" };
The preceding code example creates an object called dvdCatalog, which holds two properties: one called identifier and the other called name. The values contained in each property are 1 and “Coho Vineyard”, respectively. You could access the name property of the dvdCatalog object like this:
alert(dvdCatalog.name);
Here’s a more complete example of an object, which can also be found in the sample code in the file object.txt:
// Create four new objects var star = {}; // Create properties for each of four stars. star["Polaris"] = new Object; star["Deneb"] = new Object; star["Vega"] = new Object; star["Altair"] = new Object;
Examples later in the book show how to add properties to these objects and how to access properties. There’s much more to objects, and Chapter 8 gives that additional detail.
Arrays
You’ve seen in the previous example how to create an object with a name. You can also use array elements that are accessed by a numbered index value. These are the traditional arrays, familiar to programmers in many languages. You just saw several objects, each named for a star. The following code creates an array with four elements.
var star = new Array(); star[0] = "Polaris"; star[1] = "Deneb"; star[2] = "Vega"; star[3] = "Altair";
The same code can also be written like this, using literal notation, represented by square brackets:
var star = ["Polaris", "Deneb", "Vega", "Altair"];
Arrays can contain nested values, creating an array of arrays, as in this example that combines the star name with the constellation in which it appears:
var star = [["Polaris", "Ursa Minor"],["Deneb","Cygnus"],["Vega","Lyra"], ["Altair","Aquila"]];
Finally, although less common, you can call the Array() constructor with arguments:
var star = new Array("Polaris", "Deneb", "Vega", "Altair");
The new ECMA-262 edition 5 specification added several new methods for iterating and working with arrays. Arrays, including methods that iterate through them and work with them, are covered in more detail in Chapter 8.