March 22, 2011, 11:16 a.m.
posted by idm
For instance, there are just three simple data types: string, numeric, and boolean. Each is specifically differentiated by the literal it contains: string, numeric, and boolean. However, there are also built-in objects known as number, string, and boolean. These would seem to be the same thing, but aren't: the first three are classifications of primitive values, while the latter three are complex constructions with a type of their own: object.
Rather than mix type and object, in the next three sections, we'll look at each of the simple data types, how they're created, and how values of one type can be converted to others. In Chapter 4, we'll look at these and other built-in JS objects, and the methods and properties accessible with each.
The String Data Type
"This is a string" 'But this is also a string'
There is no rule as to which type of quote you use, except that the ending quote character must be the same as the beginning one. Any variation of characters can be included in the string:
"This is 1 string." "This is--another string."
An escape sequence is a set of characters in which certain characters are encoded in order to include them within the string. The following snippet of code assigns a string literal containing a line-terminator escape sequence to a variable. When the string is used in a dialog window, the escape sequence, \\n, is interpreted literally, and a new line is published:
var string_value = "This is the first line\nThis is the second line";
This results in:
This is the first line This is the second line
The two different types of quotes, single and double, can be used interchangeably if you need to include a quote within the quoted string:
var string_value = "This is a 'string' with a quote."
var string_value = 'This is a "string" with a quote.'
var string_value = "This is a \"string\" with a quote."
To include a backslash in the string, use two backslashes in a row:
var string_value = "This is a \\string\\ with a backslash."
The result of this line of code is a string with two backslashes, one on either side of the word string.
Using the escape function to escape strings
The result of the program is the following two escaped strings:
Characters that are escaped are spaces, colons, slashes, and other characters meaningful in an HTML context. To return the string to the original, use the unescape function on the modified string.
var sURL = "http://oreilly.com/this_is_a_value&some-value='some value'"; sURL = encodeURI(sURL); document.writeln("<p>" + sURL + "</p>");
Here's the resulting string printed to the page:
The function decodeURI can then be used to retrieve the original, nonescaped string.
There are two other functions for URI encodingencodeURIComponent and decodeURIComponentthat are used in Ajax operations because they also encode &, +, and =, but we'll look at those in Chapter 13.
You can also include Unicode characters in a string by preceding the four-digit hexadecimal value of the character with \\u. For instance, the following outputs the Chinese (simplified) ideogram for "love":
What displays is somewhat browser-dependent; however, most of the more commonly used browsers now have adequate Unicode support.
The empty string is a special case; it's commonly used to initialize a string variable when it's defined. Following are examples of empty strings:
var string_value = ''; var string_value = "";
These are all demonstrations of how to explicitly create a string variable, and variations of string literals that incorporate special characters. The values within a specific variable can also be converted from other data types, depending on the context.
If a numeric or Boolean variable is passed to a function that expects a string, the value is implicitly converted to a string first, before the value is processed:
var num_value = 35.00; alert(num_value);
In addition, when variables are added, depending on the context, nonstring values are also converted to strings. You've seen this in action when nonstring values are added (concatenated) to a string to be published in a dialog window:
var num_value = 35.00; var string_value = "This is a number:" + num_value;
You can also explicitly convert a variable to a string using string (toString in ECMAScript). If the value being converted is a boolean, the resulting string is a text representation of the Boolean value: "true" for true; "false" for false. For numbers, the string is, again, a string representation of the number, such as "123.06" for 123.06, depending on the number of digits and the precision (placement of the decimal point). A value of NaN (Not a Number, discussed later) returns "NaN".
Figure shows the results of using String on different data types.
The last item in Figure discusses how a string conversion works with an object. Within the ECMAScript specification, the conversion routines first call the toPrimitive function, before the type conversion. The toPrimitive function calls the DefaultValue object method, if any, and returns the result. For instance, using toString on the String object itself returns a value of the following in some browsers:
The Boolean Data Type
The function Boolean (ToBoolean in ECMAScript) can convert another value to boolean true or false, according to Figure.
The Number Data Type
-1000 0 2534
The floating-point representation has a decimal, with a decimal component to the right. It could also be represented as an exponent, using either a superscript or exponential notation. All of the following are valid floating-point numbers:
0.3555 144.006 -2.3 442 19.5e-2 (which is equivalent to 19.5-2)
Though larger numbers are supported, some functions can work only with numbers in a range of 2e31 to 2e31 (2,147,483,648 to 2,147,483,648); as such, you should limit your number use to this range.
In addition to base-10 representation, octal and hexadecimal notation can be used, though octal is newer and may be confused for hexadecimal with older browsers. A hexadecimal number begins with a zero, followed by an x:
Octal values begin with zeros, and there is no leading x:
You can convert strings or booleans to numbers; two functions, parseInt and parseFloat, manage the conversion depending on the type of number you want returned.
The parseInt function returns the integer portion of a number in a string, whether the string is formatted as an integer or floating point. The parseFloat function returns the floating-point value until a nonnumeric character is reached. In Figure, three strings containing numeric values are passed to either parseInt or parseFloat, and the values are written to the page.
Converting strings to numbers using different global functions
Using Firefox as a browser, the values printed out are:
0.0123 1.45 33
Notice with the first value, the number is printed out in decimal notation rather than the exponential notation of the original string value. Also note that parseInt truncates the fractional component of the number.
var iValue = parseInt("0266",8); document.writeln("<p>" + iValue + "</p>"); var iValue = parseInt("0x5F",16); document.writeln("<p>" + iValue + "</p>");
These octal and hexidecimal values are printed out to the page:
In addition to parseInt and parseFloat, the Number function also converts numbers. The type returned after conversion is dependent on the representation: floating-point strings return floating-point numbers; integer strings, integers. Conversion to numbers from each type is shown in Figure.
In addition to converting strings to numbers, you can also test the value of a variable to see if it's infinity through the IsFinite function. If the value is infinity or NaN, the function returns false; otherwise, it returns true.
Null and Undefined
A null variable is one that has been defined, but hasn't been assigned a value. The following is an example of a null variable:
In this example, the variable sValue has not not been declared either through the use of the var keyword or by being passed as a parameter to a function. If the variable has been declared but not initialized, it is considered undefined.
var sValue; alert(sValue); // no error, and a window with the word 'undefined' is opened
A variable is not null and not undefined when it is both declared and given an initial value:
var sValue = "";
if (sValue) ... // if not null and initialized, expression is true; otherwise false
We'll look at conditional statements in the next chapter, but the expression consisting of just the variable sValue evaluates to TRue if sValue has been declared and initialized; otherwise, the result of the expression is false:
if (sValue) // not true, as variable has not been declared, and is therefore null var sValue; if (sValue) // variable is not null, but it's still not true, as variable has not been defined (initialized with a value) var sValue = 1; if (sValue) // true now, as variable has been set, which automatically declares it
Using the null keyword, you can specifically test to see whether a value is null:
if (sValue == null)
alert(sValue); // JS error results, "Error: sValue is not defined" var sValue; // no JS error and the window reads, "undefined" which is the value of the object
A variable can be undeclared but initialized, in which case it is not null and not undefined. However, in this instance, it's considered a global variable, and as discussed earlier, not specifically declaring variables with var causes problems more often than not.
Though not related to existence, there is a third unique value related to the type of a variable: NaN, or Not A Number. If a string or Boolean variable cannot be coerced into a number, it's considered NaN and treated accordingly:
var nValue = 1.0; if (nValue == 'one' ) // false, the second operand is NaN
You can specifically test whether a variable is NaN with the isNaN function:
if (isNaN(sValue)) // if string cannot be implicitly converted into number, return true
By its very nature, a null value is NaN, so it is undefined.
However, when using large and complex JS libraries, and applications that can incorporate web service responses, it becomes increasingly important to test variables that originate and/or are set outside of our controlnot to mention to be aware of how null and undefined variables behave when accessed in the application.