User:Moncur/05
5. Using Variables, Strings, and Arrays
[wax ka badal]Using Variables
[wax ka badal]Unless you skipped the first few hours of this book, you've already used a few variables. You probably can also figure out how to use a few more without any help. Nevertheless, there are some aspects of variables you haven't learned yet. We will now look at some of the details.
Choosing Variable Names
[wax ka badal]Variables are named containers that can store data (for example, a number, a text string, or an object). As you learned earlier in this book, each variable has a name. There are specific rules you must follow when choosing a variable name:
- Variable names can include letters of the alphabet, both upper- and lowercase. They can also include the digits 09 and the underscore (_) character.
- Variable names cannot include spaces or any other punctuation characters.
- The first character of the variable name must be either a letter or an underscore.
- Variable names are case sensitive: totalnum, Totalnum, and TotalNum are separate variable names.
- There is no official limit on the length of variable names, but they must fit within one line.
Using these rules, the following are examples of valid variable names:
total_number_of_fish LastInvoiceNumber temp1 a _var39
- By the Way
- You can choose to use either friendly, easy-to-read names or completely cryptic ones. Do yourself a favor: use longer, friendly names whenever possible. Although you might remember the difference between a, b, x, and x1 right now, you might not after a good night's sleep.
Using Local and Global Variables
[wax ka badal]Some computer languages require you to declare a variable before you use it. JavaScript includes the var keyword, which can be used to declare a variable. You can omit var in many cases; the variable is still declared the first time you assign a value to it.
To understand where to declare a variable, you will need to understand the concept of scope. A variable's scope is the area of the script in which that variable can be used. There are two types of variables:
- Global variables have the entire script (and other scripts in the same HTML document) as their scope. They can be used anywhere, even within functions.
- Local variables have a single function as their scope. They can be used only within the function they are created in.
To create a global variable, you declare it in the main script, outside any functions. You can use the var keyword to declare the variable, as in this example:
var students = 25;
This statement declares a variable called students and assigns it a value of 25. If this statement is used outside functions, it creates a global variable. The var keyword is optional in this case, so this statement is equivalent to the previous one:
students = 25;
Before you get in the habit of omitting the var keyword, be sure you understand exactly when it's required. It's actually a good idea to always use the var keyword - you'll avoid errors and make your script easier to read, and it won't usually cause any trouble.
- By the Way
- For the most part, the variables you've used in earlier hours of this book have been global.
A local variable belongs to a particular function. Any variable you declare with the var keyword in a function is a local variable. Additionally, the variables in the function's parameter list are always local variables.
To create a local variable within a function, you must use the var keyword. This forces JavaScript to create a local variable, even if there is a global variable with the same name.
You should now understand the difference between local and global variables. If you're still a bit confused, don't worry—if you use the var keyword every time, you'll usually end up with the right type of variable.
Assigning Values to Variables
[wax ka badal]As you learned in [Hour 2], "Creating a Simple Script," you can use the equal sign to assign a value to a variable. For example, this statement assigns the value 40 to the variable lines:
lines = 40;
You can use any expression to the right of the equal sign, including other variables. You have used this syntax earlier to add one to a variable:
lines = lines + 1;
Because incrementing or decrementing variables is quite common, JavaScript includes two types of shorthand for this syntax. The first is the += operator, which enables you to create the following shorter version of the preceding example:
lines += 1;
Similarly, you can subtract a number from a variable using the -= operator:
lines -= 1;
If you still think that's too much to type, JavaScript also includes the increment and decrement operators, ++ and --. This statement adds one to the value of lines:
lines++;
Similarly, this statement subtracts one from the value of lines:
lines--;
You can alternately use the ++ or -- operators before a variable name, as in ++lines. However, these are not identical. The difference is when the increment or decrement happens:
- If the operator is after the variable name, the increment or decrement happens after the current expression is evaluated.
- If the operator is before the variable name, the increment or decrement happens before the current expression is evaluated.
This difference is only an issue when you use the variable in an expression and increment or decrement it in the same statement. As an example, suppose you have assigned the lines variable the value 40. The following two statements have different effects:
alert(lines++); alert(++lines);
The first statement displays an alert with the value 40, and then increments lines to 41. The second statement first increments lines to 41, then displays an alert with the value 41.
- By the Way
- These operators are strictly for your convenience. If it makes more sense to you to stick to lines = lines + 1, do it—your script won't suffer.
Understanding Expressions and Operators
[wax ka badal]An expression is a combination of variables and values that the JavaScript interpreter can evaluate to a single value. The characters that are used to combine these values, such as + and /, are called operators.
- Did you Know?
- Along with variables and constant values, you can also use calls to functions that return results within an expression.
Using JavaScript Operators
[wax ka badal]You've already used some operators, such as the + sign (addition) and the increment and decrement operators. Table 5.1 lists some of the most important operators you can use in JavaScript expressions.
+ Table 5.1. Common JavaScript Operators | ||
Operator | Description | Example |
---|---|---|
+ | Concatenate (combine) strings | message="this is" + "a test"; |
+ | Add | result = 5 + 7; |
- | Subtract | score = score - 1; |
* | Multiply | total = quantity * price; |
/ | Divide | average = sum / 4; |
% | Modulo (remainder) | remainder = sum % 4; |
++ | Increment | TRies++; |
-- | Decrement | total--; |
Along with these, there are also many other operators used in conditional statements—you'll learn about these in [Hour 7], "Controlling Flow with Conditions and Loops."
Operator Precedence
[wax ka badal]When you use more than one operator in an expression, JavaScript uses rules of operator precedence to decide how to calculate the value. [Table 5.1] lists the operators from lowest to highest precedence, and operators with highest precedence are evaluated first. For example, consider this statement:
result = 4 + 5 * 3;
If you try to calculate this result, there are two ways to do it. You could multiply 5 * 3 first and then add 4 (result: 19) or add 4 + 5 first and then multiply by 3 (result: 27). JavaScript solves this dilemma by following the precedence rules: Because multiplication has a higher precedence than addition, it first multiplies 5 * 3 and then adds 4, producing a result of 19.
- By the Way
- If you're familiar with any other programming languages, you'll find that the operators and precedence in JavaScript work, for the most part, the same way as those in C, C++, and Java.
Sometimes operator precedence doesn't produce the result you want. For example, consider this statement:
result = a + b + c + d / 4;
This is an attempt to average four numbers by adding them all together and then dividing by four. However, because JavaScript gives division a higher precedence than addition, it will divide the d variable by 4 before adding the other numbers, producing an incorrect result.
You can control precedence by using parentheses. Here's the working statement to calculate an average:
result = (a + b + c + d) / 4;
The parentheses ensure that the four variables are added first, and then the sum is divided by four.
- Did you Know?
- If you're unsure about operator precedence, you can use parentheses to make sure things work the way you expect and to make your script more readable.
Data Types in JavaScript
[wax ka badal]In some computer languages, you have to specify the type of data a variable will store: for example, a number or a string. In JavaScript, you don't need to specify a data type in most cases. However, you should know the types of data JavaScript can deal with.
These are the basic JavaScript data types:
- Numbers, such as 3, 25, or 1.4142138. JavaScript supports both integers and floating-point numbers.
- Boolean, or logical values. These can have one of two values: true or false. These are useful for indicating whether a certain condition is true.
- By the Way
- You'll learn more about Boolean values, and about using conditions in JavaScript, in [Hour 7].
- Strings, such as "I am a jelly doughnut". These consist of one or more characters of text. (Strictly speaking, these are String objects, which you'll learn about later in this hour.)
- The null value, represented by the keyword null. This is the value of an undefined variable. For example, the statement document.write(fig) will result in this value (and an error message) if the variable fig has not been previously used or defined.
Although JavaScript keeps track of the data type currently stored in each variable, it doesn't restrict you from changing types midstream. For example, suppose you declared a variable by assigning it a value:
total = 31;
This statement declares a variable called total and assigns it the value of 31. This is a numeric variable. Now suppose you changed the value of total:
total = "albatross";
This assigns a string value to total, replacing the numeric value. JavaScript will not display an error when this statement executes; it's perfectly valid, although it's probably not a very useful total.
- By the Way
- Although this feature of JavaScript is convenient and powerful, it can also make it easy to make a mistake. For example, if the total variable was later used in a mathematical calculation, the result would be invalid—but JavaScript does not warn you that you've made this mistake.
Converting Between Data Types
[wax ka badal]JavaScript handles conversions between data types for you whenever it can. For example, you've already used statements like this:
document.write("The total is " + total);
This statement prints out a message such as "The total is 40". Because the document.write function works with strings, the JavaScript interpreter automatically converts any nonstrings in the expression (in this case, the value of total) to strings before performing the function.
This works equally well with floating-point and Boolean values. However, there are some situations where it won't work. For example, the following statement will work fine if the value of total is 40:
average = total / 3;
However, the total variable could also contain a string; in this case, the preceding statement would result in an error.
In some situations, you might end up with a string containing a number, and need to convert it to a regular numeric variable. JavaScript includes two functions for this purpose:
- parseInt()Converts a string to an integer number.
- parseFloat()Converts a string to a floating-point number.
Both of these functions will read a number from the beginning of the string and return a numeric version. For example, these statements convert the string "30 angry polar bears" to a number:
stringvar = "30 angry polar bears"; numvar = parseInt(stringvar);
After these statements execute, the numvar variable contains the number 30. The nonnumeric portion of the string is ignored.
- By the Way
- These functions look for a number of the appropriate type at the beginning of the string. If a valid number is not found, the function will return the special value NaN, meaning not a number.
Using String Objects
[wax ka badal]You've already used several strings during the first few hours of this book. Strings store a group of text characters, and are named similarly to other variables. As a simple example, this statement assigns the string This is a test to a string variable called test:
test = "This is a test";
Creating a String Object
[wax ka badal]JavaScript stores strings as String objects. You usually don't need to worry about this, but it will explain some of the techniques for working with strings, which use methods (built-in functions) of the String object.
There are two ways to create a new String object. The first is the one you've already used, whereas the second uses object-oriented syntax. The following two statements create the same string:
test = "This is a test"; test = new String("This is a test");
The second statement uses the new keyword, which you use to create objects. This tells the browser to create a new String object containing the text This is a test, and assigns it to the variable test.
- By the Way
- Although you can create a string using object-oriented syntax, the standard JavaScript syntax is simpler, and there is no difference in the strings created by these two methods.
Assigning a Value
[wax ka badal]You can assign a value to a string in the same way as any other variable. Both of the examples in the previous section assigned an initial value to the string. You can also assign a value after the string has already been created. For example, the following statement replaces the contents of the test variable with a new string:
test = "This is only a test.";
You can also use the concatenation operator (+) to combine the values of two strings. [Listing 5.1] shows a simple example of assigning and combining the values of strings.
- Listing 5.1. Assigning Values to Strings and Combining Them
<html> <head> <title>String Test</title> </head> <body> <h1>String Test</h1> <script language="JavaScript" type="text/javascript">; test1 = "This is a test. "; test2 = "This is only a test."; both = test1 + test2; alert(both); </script> </body> </html>
This script assigns values to two string variables, test1 and test2, and then displays an alert with their combined value. If you load this HTML document in a browser, your output should resemble [Figure 5.1].
In addition to using the + operator to concatenate two strings, you can use the += operator to add text to a string. For example, this statement adds a period to the current contents of the string sentence:
sentence += ".";
- By the Way
- The plus sign (+) is also used to add numbers in JavaScript. The browser knows whether to use addition or concatenation based on the types of data you use with the plus sign. If you use it between a number and a string, the number is converted to a string and concatenated.
Calculating the String's Length
[wax ka badal]From time to time, you might find it useful to know how many characters a string variable contains. You can do this with the length property of String objects, which you can use with any string. To use this property, type the string's name followed by .length.
For example, test.length refers to the length of the test string. Here is an example of this property:
test = "This is a test."; document.write(test.length);
The first statement assigns the string This is a test to the test variable. The second statement displays the length of the string—in this case, 15 characters. The length property is a read-only property, so you cannot assign a value to it to change a string's length.
- By the Way
- Remember that although test refers to a string variable, the value of test.length is a number and can be used in any numeric expression.
Converting the String's Case
[wax ka badal]Two methods of the String object enable you to convert the contents of a string to all uppercase or all lowercase:
- toUpperCase()Converts all characters in the string to uppercase.
- toLowerCase()Converts all characters in the string to lowercase.
For example, the following statement displays the value of the test string variable in lowercase:
document.write(test.toLowerCase());
Assuming that this variable contained the text This Is A Test, the result would be the following string:
this is a test
Note that the statement doesn't change the value of the text variable. These methods return the upper- or lowercase version of the string, but they don't change the string itself. If you want to change the string's value, you can use a statement like this:
test = test.toLowerCase();
- By the Way
- Note that the syntax for these methods is similar to the length property introduced earlier. The difference is that methods always use parentheses, whereas properties don't. The toUpperCase and toLowerCase methods do not take any parameters, but you still need to use the parentheses.
Working with Substrings
[wax ka badal]So far, you've worked with entire strings. JavaScript also enables you to work with substrings, or portions of a string. You can use the substring method to retrieve a portion of a string, or the charAt method to get a single character. These are explained in the following sections.
Using Part of a String
[wax ka badal]The substring method returns a string consisting of a portion of the original string between two index values, which you must specify in parentheses. For example, the following statement displays the fourth through sixth characters of the text string:
document.write(text.substring(3,6));
At this point, you're probably wondering where the 3 and the 6 come from. There are three things you need to understand about the index parameters:
- Indexing starts with 0 for the first character of the string, so the fourth character is actually index 3.
- The second index is noninclusive. A second index of 6 includes up to index 5 (the sixth character).
- You can specify the two indexes in either order. The smaller one will be assumed to be the first index. In the previous example, (6,3) would have produced the same result. Of course, there is rarely a reason to use the reverse order.
As another example, suppose you defined a string called alpha to hold the alphabet:
alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
The following are examples of the substring() method using this string:
- alpha.substring(0,4) returns ABCD.
- alpha.substring(10,12) returns KL.
- alpha.substring(12,10) also returns KL. Because it's smaller, 10 is used as the first index.
- alpha.substring(6,7) returns G.
- alpha.substring(24,26) returns YZ.
- alpha.substring(0,26) returns the entire alphabet.
- alpha.substring(6,6) returns the null value, an empty string. This is true whenever the two index values are the same.
Getting a Single Character
[wax ka badal]The charAt method is a simple way to grab a single character from a string. You specify the character's index, or position, in parentheses. The indexes begin at 0 for the first character. Here are a few examples using the alpha string:
- alpha.charAt(0) returns A.
- alpha.charAt(12) returns M.
- alpha.charAt(25) returns Z.
- alpha.charAt(27) returns an empty string because there is no character at that position.
Finding a Substring
[wax ka badal]Another use for substrings is to find a string within another string. One way to do this is with the indexOf method. To use this method, add indexOf to the string you want to search, and specify the string to search for in the parentheses. This example searches for "this" in the test string:
loc = test.indexOf("this");
- By the Way
- As with most JavaScript methods and property names, indexOf is case sensitive. Make sure you type it exactly as shown here when you use it in scripts.
The value returned in the loc variable is an index into the string, similar to the first index in the substring method. The first character of the string is index 0.
You can specify an optional second parameter to indicate the index value to begin the search. For example, this statement searches for the word fish in the temp string, starting with the 20th character:
location = temp.indexOf("fish",19);
- By the Way
- One use for the second parameter is to search for multiple occurrences of a string. After finding the first occurrence, you search starting with that location for the second one, and so on.
A second method, lastIndexOf(), works the same way, but finds the last occurrence of the string. It searches the string backwards, starting with the last character. For example, this statement finds the last occurrence of Fred in the names string:
location = names.lastIndexOf("Fred");
As with indexOf(), you can specify a location to search from as the second parameter. In this case, the string will be searched backward starting at that location.
Using Numeric Arrays
[wax ka badal]An array is a numbered group of data items that you can treat as a single unit. For example, you might use an array called scores to store several scores for a game. Arrays can contain strings, numbers, objects, or other types of data. Each item in an array is called an element of the array.
Creating a Numeric Array
[wax ka badal]Unlike most other types of JavaScript variables, you typically need to declare an array before you use it. The following example creates an array with four elements:
scores = new Array(4);
To assign a value to the array, you use an index in brackets. Indexes begin with 0, so the elements of the array in this example would be numbered 0 to 3. These statements assign values to the four elements of the array:
scores[0] = 39; scores[1] = 40; scores[2] = 100; scores[3] = 49;
You can also declare an array and specify values for elements at the same time. This statement creates the same scores array in a single line:
scores = new Array(39,40,100,49);
In JavaScript 1.2 and later, you can also use a shorthand syntax to declare an array and specify its contents. The following statement is an alternative way to create the scores array:
scores = [39,40,100,49];
- Did you Know?
- Remember to use parentheses when declaring an array with the new keyword, as in a=new Array(3,4,5), and use brackets when declaring an array without new, as in a=[3,4,5]. Otherwise, you'll run into JavaScript errors.
Understanding Array Length
[wax ka badal]Like strings, arrays have a length property. This tells you the number of elements in the array. If you specified the length when creating the array, this value becomes the length property's value. For example, these statements would print the number 30:
scores = new Array(30); document.write(scores.length);
You can declare an array without a specific length, and change the length later by assigning values to elements or changing the length property. For example, these statements create a new array and assign values to two of its elements:
test = new Array(); test[0]=21; test[5]=22;
In this example, because the largest index number assigned so far is 5, the array has a length property of 6—remember, elements are numbered starting at 0.
Accessing Array Elements
[wax ka badal]You can read the contents of an array using the same notation you used when assigning values. For example, the following statements would display the values of the first three elements of the scores array:
scoredisp = "Scores: " + scores[0] + "," + scores[1] + "," + scores[2]; document.write(scoredisp);
- Did you Know?
- Looking at this example, you might imagine it would be inconvenient to display all the elements of a large array. This is an ideal job for loops, which enable you to perform the same statements several times with different values. You'll learn all about loops in [Hour 7].
Using String Arrays
[wax ka badal]So far, you've used arrays of numbers. JavaScript also allows you to use string arrays, or arrays of strings. This is a powerful feature that enables you to work with a large number of strings at the same time.
Creating a String Array
[wax ka badal]You declare a string array in the same way as a numeric array—in fact, JavaScript does not make a distinction between them:
names = new Array(30);
You can then assign string values to the array elements:
names[0] = "Henry J. Tillman"; names[1] = "Sherlock Holmes";
As with numeric arrays, you can also specify a string array's contents when you create it. Either of the following statements would create the same string array as the preceding example:
names = new Array("Henry J. Tillman", "Sherlock Holmes"); names = ["Henry J. Tillman", "Sherlock Holmes"];
You can use string array elements anywhere you would use a string. You can even use the string methods introduced earlier. For example, the following statement prints the first five characters of the first element of the names array, resulting in Henry:
document.write(names[0].substring(0,5));
Splitting a String
[wax ka badal]JavaScript includes a string method called split, which splits a string into its component parts. To use this method, specify the string to split and a character to divide the parts:
test = "John Q. Public"; parts = test.split(" ");
In this example, the test string contains the name John Q. Public. The split method in the second statement splits the name string at each space, resulting in three strings. These are stored in a string array called parts. After the example statements execute, the elements of parts contain the following:
- parts[0] = "John"
- parts[1] = "Q."
- parts[2] = "Public"
JavaScript also includes an array method, join, which performs the opposite function. This statement reassembles the parts array into a string:
fullname = parts.join(" ");
The value in the parentheses specifies a character to separate the parts of the array. In this case, a space is used, resulting in the final string John Q. Public. If you do not specify a character, commas are used.
Sorting a String Array
[wax ka badal]JavaScript also includes a sort method for arrays, which returns an alphabetically sorted version of the array. For example, the following statements initialize an array of four names and sort it:
names[0] = "Public, John Q."; names[1] = "Tillman, Henry J."; names[2] = "Bush, George W."; names[3] = "Mouse, Mickey"; sortednames = names.sort();
The last statement sorts the names array and stores the result in a new array, sortednames.
Sorting a Numeric Array
[wax ka badal]Because the sort method sorts alphabetically, it won't work with a numeric array—at least not the way you'd expect. If an array contains the numbers 4, 10, 30, and 200, for example, it would sort them as 10, 200, 30, 4—not even close. Fortunately, there's a solution: You can specify a function in the sort method's parameters, and that function will be used to compare the numbers. The following code sorts a numeric array correctly:
function numcompare(a,b) { return a-b; } nums = new Array(30, 10, 200, 4); sortednums = nums.sort(numcompare);
This example defines a simple function, numcompare, which subtracts the two numbers. After you specify this function in the sort method, the array is sorted in the correct numeric order: 4, 10, 30, 200.
- By the Way
- JavaScript expects the comparison function to return a negative number if a belongs before b, 0 if they are the same, or a positive number if a belongs after b. This is why a-b is all you need for the function to sort numerically.
- Try It Yourself
- Sorting and Displaying Names
To gain more experience working with JavaScript's string and array features, you can create a script that enables the user to enter a list of names, and displays the list in sorted form.
Because this will be a larger script, you will create separate HTML and JavaScript files, as described in [Hour 3], "Getting Started with JavaScript Programming." First, the sort.html file will contain the HTML structure and form fields for the script to work with. [Listing 5.2] shows the HTML document.
- Listing 5.2. The HTML Document for the Sorting Example
<html> <head> <title>Array Sorting Example</title> <script type="text/javascript" language="javascript" src="sort.js"> </script> </head> <body> <h1>Sorting String Arrays</h1> <p>Enter two or more names in the field below, and the sorted list of names will appear in the text area.</p> <form name="theform"> Name: <input type="text" name="newname" size="20"> <input type="button" name="addname" value="Add" onclick="SortNames();"> <br> <h2>Sorted Names</h2> <textarea cols="60" rows="10" name="sorted"> The sorted names will appear here. </textarea> </form> </body> </html>
Because the script will be in a separate document, the <script> tag in the header of this document uses the src attribute to include a JavaScript file called sort.js. You will create this file next.
This document defines a form named theform, a text field named newname, an addname button, and a textarea named sorted. Your script will use these form fields as its user interface. [Listing 5.3] shows the JavaScript file.
- Listing 5.3. The JavaScript File for the Sorting Example
// initialize the counter and the array var numnames=0; var names = new Array(); function SortNames() { // Get the name from the text field thename=document.theform.newname.value; // Add the name to the array names[numnames]=thename; // Increment the counter numnames++; // Sort the array names.sort(); document.theform.sorted.value=names.join("\n"); }
The script begins by defining two variables with the var keyword: numnames will be a counter that increments as each name is added, and the names array will store the names.
When you type a name into the text field and click the button, the onclick event handler calls the SortNames function. This function stores the text field value in a variable, thename, and then adds the name to the names array using numnames as the index. It then increments numnames to prepare for the next name.
The final section of the script sorts the names and displays them. First, the sort() method is used to sort the names array. Next, the join() method is used to combine the names, separating them with line breaks, and display them in the textarea.
To test the script, save it as sort.js, and then load the sort.html file you created previously into a browser. You can then add some names and test the script. [Figure 5.2] shows the result after sorting several names.
Summary
[wax ka badal]During this hour, you've focused on variables and how JavaScript handles them. You've learned how to name variables, how to declare them, and the differences between local and global variables. You also explored the data types supported by JavaScript and how to convert between them.
You also learned about JavaScript's more complex variables, strings and arrays, and looked at the features that enable you to perform operations on them, such as converting strings to uppercase or sorting arrays.
In the next hour, you'll continue your JavaScript education by learning more about two additional key features: functions and objects.
Q&A
[wax ka badal]- Q1
- What is the importance of the var keyword? Should I always use it to declare variables?
- A1
- You only need to use var to define a local variable in a function. However, if you're unsure at all, it's always safe to use var. Using it consistently will help you keep your scripts organized and error free.
- Q2
- Is there any reason I would want to use the var keyword to create a local variable with the same name as a global one?
- A2
- Not on purpose. The main reason to use var is to avoid conflicts with global variables you might not know about. For example, you might add a global variable in the future, or you might add another script to the page that uses a similar variable name. This is more of an issue with large, complex scripts.
- Q3
- What good are Boolean variables?
- A3
- Often in scripts you'll need a variable to indicate whether something has happenedfor example, whether a phone number the user has entered is in the right format. Boolean variables are ideal for this; they're also useful in working with conditions, as you'll see in Hour 7.
- Q4
- Can I store other types of data in an array? For example, can I have an array of dates?
- A4
- Absolutely. JavaScript allows you to store any data type in an array.
- Q5
- What about two-dimensional arrays?
- A5
- These are arrays with two indexes (such as columns and rows). JavaScript does not directly support this type of array, but you can use objects to achieve the same effect. You will learn more about objects in the next hour.
Quiz Questions
[wax ka badal]Test your knowledge of JavaScript by answering the following questions:
1. Which of the following is not a valid JavaScript variable name?
- 2names
- first_and_last_names
- FirstAndLast
2. If the statement var fig=2 appears in a function, which type of variable does it declare?
- A global variable
- A local variable
- A constant variable
3. If the string test contains the value The eagle has landed., what would be the value of test.length?
- 4
- 21
- The
4. Using the same example string, which of these statements would return the word eagle?
- test.substring(4,9)
- test.substring(5,9)
- test.substring("eagle")
5. What will be the result of the JavaScript expression 31 + "angry polar bears"?
- An error message
- 32
- "31 angry polar bears"
Quiz Answers
[wax ka badal]1. a. 2names is an invalid JavaScript variable name because it begins with a number. The others are valid, although they're probably not ideal choices for names.
2. b. Because the variable is declared in a function, it is a local variable. The var keyword ensures that a local variable is created.
3. b. The length of the string is 21 characters.
4. a. The correct statement is test.substring(4,9). Remember that the indexes start with 0, and that the second index is noninclusive.
5. c. JavaScript converts the whole expression to the string "31 angry polar bears". (No offense to polar bears, who are seldom angry and rarely seen in groups this large.)
Exercises
[wax ka badal]To further explore JavaScript variables, strings, and arrays, you can perform the following exercises:
- Modify the sorting example in [Listing 5.3] to convert the names to all upper-case before sorting and displaying them.
- Modify [Listing 5.3] to display a numbered list of names in the textarea.