Chapter 7 | WebReference

Chapter 7

Chapter 7


An expression tells JavaScript what to do with the data you provide. For example, an expression can be used in an if statement to test for a certain condition -- if the user's name is Fred, for instance, the script displays a personalized message just for him. Everyone else gets a standardized greeting.

Expressions are also used to perform basic math functions using JavaScript (additional math functionality is provided with the JavaScript Math object, detailed in Chapter 4, "Objects.") For example, a typical expression adds a value to another value stored in a variable. In this way, JavaScript can keep track of what's going on around it, storing important information it might need later.

This chapter describes using expressions in JavaScript, including expressions to create variables, expressions for use in conditional statements (like if), and expressions for use in math calculations.

Creating Expressions

An expression tells JavaScript what you want to do with information given to it. An expression consists of two parts:

Sounds complex at first, but all we're really talking about is 2+2.

In JavaScript programs, expressions can be used when defining the contents of variables, as in

Test1 = 1+1;
Test2 = (15*2)+1;
Test3 = "This is" + " a test";

JavaScript processes the expression, and places the result in the variable.

Expressions can also be part of a more elaborate scheme using other JavaScript constructs. Used in this way, expressions provide a way for your scripts to think on their own (although they may seem to act on their own more than you'd like them to!). Expressions are most commonly used with the for, if, and while JavaScript statements.

Following is a list of operators, and how they are used to construct expressions. Most of the operators work with numbers only, but some can also be used with strings. The list is divided into three parts:

In all cases, you substitute the operands v1 and v2 as your values or variables, as described below.

Assignment Operators

These operators assign values to variables. You are likely to only use the = assignment operator for the bulk of your JavaScript programs, but it's nice to know the others are available in case you need them. If you're new to the concept of variables be sure to read Chapter 9, "Variables."

Operator Function
"=" Assigns value to variable -- e.g. Var=1
+= Adds value to value already in variable -- e.g. Var+=1
-= Subtracts value to value already in variable -- e.g. Var-=1
*= Multiples value with value already in variable -- e.g. Var*=1
/= Divides value with value already in variable -- e.g. Var/=1
%= Divides value with value already in variable; returns remainder -- e.g.Var%=1

Additional assignment operators are provided for bitwise operations. These are detailed separately in "Using the Bitwise Operators", later in this chapter.

Using the = (Equals)Assignment Operator

Use the = (equals sign) assignment operator whenever you wish to assign a new value to variable. If the variable previously contained a value, that value is replaced. Examples:

MyStringVar = "This is a string"  // assign text to variable
MyNumverVar = 100   // assign number to variable
MyObjectVar = document.form[0]  // assign document.form[0] object to

Using the Shorthand Assignment Operators

The shorthand assignment operators let you add, subtract, multiply, and divide values to values already in a variable. The most commonly used shorthand assignment is +=.

A number example:

Var = 1;
Var += 5;
// Var now contains 6 

Another way you could write the above:

Var = 1;
Var = Var + 5;

A text string example:

Var = "Java";
Var += "Script";
// Var now contains "JavaScript

Another way you could write the above:

Var = "Java";
Var = Var + "Script";

The remaining shorthand operators let you subtract, multiply, and divide values.

Examples (the variable Val contains 5 in each case):

Val -= 3  // result: 2
Val *= 3  // result: 15
Val /= 3  // result: 1.666 (etc.)
Val %= 3 // result: 2

Math Operators

These operators perform math calculations with one or more numbers.

Operator Function
- value Treats the value as a negative number.
v1 + v2 Adds values v1 and v2 together. Can also be used to connect (concatenate) two or more strings together
v1 - v2 Subtracts value v2 from v1.
v1 * v2 Multiplies values v1 and v2.
v1 / v2 Divides value v1 by v2.
v1 % v2 Divides value v1 by v2. The result is the floating-point remainder of the division.
v1++ Adds 1 to v1.
v1-- Subtracts 1 from v1.

The + operator is dual use. When used with numbers, the + operator adds them together. When used with strings, the + operator connects the strings (called concatenation) and makes them one.

The ++ and -- operators (borrowed from C, C++, and Java) can be used in a number of ways. The most common is v1++ where you increment the value already in v1 by 1. (Similarly, the instruction v1-- decrements the value already in v1 by 1.) You can actually use the ++ and -- increment/decrement operators before or after the value.

Suppose the Var variable contains the number 10. In each of the following Var is incremented by 1. But the RetVal variable will contain different values, because of the order JavaScript uses in incrementing and returning the value.

RetVal = Var++ // returns 10
RetVal = ++Var // returns 11

The similar postfix/prefix technique works with the -- decrement operator.

RetVal = Var-- // returns 10
RetVal = --Var // returns 9

Relational Operators

Relational operators compare two values to see if they are equal, not equal, greater than, or less than (and sometimes a combination of these).

Operator Function
v1 == v2 Test that v1 and v2 are equal (note the two equal signs).
v1 <> v2 Test that v1 and v2 are not equal.
v1 > v2 Test that v1 is greater than v2.
v1 >= v2 Test that v1 is greater than or equal to v2.
v1 < v2 Test that v1 is less than v2.
v1 <= v2 Test that v1 is less than or equal to v2.
! value Evaluates the logical NOT of value. The logical NOT is the inverse of an expression: true becomes false, and vice versa.
v1 && v2 Evaluates the logical AND of v1 and v2.
v1 || v2 Evaluates the logical OR of v1 and v2.

Relational operators are also known as Boolean or true/false operators. Whatever they test, the answer is either yes (true) or no (false). For example, the expression 2==2 would be true, but the expression "2==3" would be false.

How to Use the && (AND) and || (OR) Relational Operators

The && and || (AND and OR) operators work with numbers and expressions that result in a true/false condition. They are not used with strings, unless the strings are a part of a true/false expression. JavaScript balks if you try to use the operators with a string alone. For example, the following is not allowed.

This = "Java";
That = "Script";
Result = This && That;

This results in an error. Instead of combining the This and That variables into Result, JavaScript responds with a not-too-kind error message. As you've read earlier in this chapter, the correct way to combine the two strings is to use the + operator, as in This+That.

It's helpful to view the action of the AND and OR operators with the use of something called a "truth table." The table shows all the possible outcomes given to values in an expression. Truth values are shown for Boolean true and false, and also for the numeric digits 0 and 1. JavaScript's Boolean operators work the same with either kind of value. (Note: In JavaScript, true/false values are distinct from 1/0.)

AND Truth Table

Val1 Val2 Result
false (0) false (0) false (0)
false (0) true (1) false (0)
true (1) false (0) false (0)
true (1) true (1) true (1)

OR Truth Table

Val1 Val2 Result
false (0) false (0) false (0)
false (0) true (1) true (1)
true (1) false (0) true (1)
true (1) true (1) true (1)

Using the AND and OR Operators in More Complex if Expressions

A common use of the && (AND) and || (OR) relational operators is in if expressions (and also in expressions using the while statement). These expressions are sometimes built to test for one of several conditions, or a number of conditions together.

When at least one of the conditions is true, that portion of the script is complete and JavaScript proceeds to the next. An example:

if (Var1 == 100) {
} else if (Var1 == 200) {
} else if (Var1 == 300) {
} else {

The structure of the routine is referred to as OR logic. If Var1 is equal to 100 OR 200 OR 300, the script executes the isTrue function. Any other condition causes the script to execute the isFalse function. Many of the scripts in this book revolve around OR logic for if expressions.

What if you want to build expressions that executes the isTrue function only if ALL of the conditions are met? This structure is more commonly called AND logic, and it can be easily done in scripts by moving the instructions around a bit.

Following are four test scripts that you can use to experiment with the operation of AND and OR logic. The following examples show how to create AND and OR logic by using multiple if statements, as well as using the && (AND) and || (OR) operators. You will find that in general, using the AND and OR operators is the easier method. You can practice with all four examples by including them in the following script:

<TITLE>And/Or test</TITLE>
function doTest() {
// insert AND/OR script segment here
function isTrue() {
alert ("It is true")
function isfalse() {
alert ("It is false")
<INPUT TYPE="button" VALUE="Test" onClick="doTest()">

AND -- Separate if Statements

var Var1=1, Var2=1;
if (Var1 == 1) {
if (Var2 == 1) 
} else

OR -- Separate if Statements

var Var1=1, Var2=1;
if (Var1 == 1) {
} else if (Var2 == 1)

AND -- Single IF Statement

var Var1=1, Var2=1;
if ((Var1 == 1) && (Var2 == 1))

OR -- Single if Statement

var Var1=1, Var2=1;
if ((Var1 == 1) || (Var2 == 1))
Important! Be sure to format the expression with parentheses and brace characters (the { and } characters) as shown; otherwise JavaScript might have trouble parsing it into a meaningful function.

Here's an example of a real-world application of OR/AND in testing the response from the user.

RetVal=prompt("Go again (Y/N)?", "Y")
if ((RetVal == "Y") || (RetVal == "y"))
	alert ("You pressed Y or y")

The && (AND) and || (OR( operators are not limited to if expressions. Here is an example of how to use the AND operator in a while loop. The example ensures that the value entered at the prompt dialog box is between 100 and 200.

while (CtrlLoop) {
Value=prompt ("Enter a value between 100 and 200", Value);
if ((Value>=100) && (Value<=200)) 
alert (Value)

The ! (NOT) Operator

The ! (NOT) operator is used whenever you want to negate a true or false expression. The statement !true becomes false, and !false becomes true.

Ordinarily, you use this to reverse the outcome of an expression that results in a true/false answer. You might want to test if a certain condition is NOT met, so you can write a more efficient if statement (you can also apply the ! (NOT) operator in for and while loops for additional flexibility.

Let's try an example of the ! (NOT) operator. Suppose you want to ask the user to respond to a prompt. You do not want them to respond with a blank entry, so you write the following code to allow your JavaScript to redisplay the prompt dialog if the entry blank is, er, blank. Notice also the extra if statement that determines if the user chooses the cancel button. This returns a null value, and the loop ends with a break statement.

while (CtrlLoop) {
	Value=prompt ("Type something", Value);
	if (Value == null)
	if (Value != "") {
	alert (Value)

Using the ? Conditional Expression Statement

JavaScript supports an alternative method to creating conditional expressions. It is a "shorthand" method used in C and some other languages, and is useful if you want to construct a quick and simple test. The syntax is:

(condition) ? istrue : isfalse

Note: You must include statements for both the true and false outcomes, and include the colon character.

For example the following displays an alert box depending on what you type in response to the prompt box:

Ret = prompt ("Type something or click Cancel", "");
(Ret == null) ? alert ("You clicked cancel") : alert ("You typed:
While the conditional expression can aid as a shortcut, I personally feel it makes for hard-to-read code. The logic of the if statement, though a bit more "bulky," is generally easier to decipher, especially when reading other people's scripts. Of course, adopt or ignore the JavaScript conditional expression as you choose.

The Bitwise Operators

JavaScript supports a unique operators that work with numbers only. These are the bitwise operators, because they actually deal with the individual bits that make up each number. The bitwise operators have only occasional use in JavaScript programs. If you have a programming background, the following operators may be of use to you in creating more complex scripts. The bitwise operators are:

Operator Name Function
& Bitwise AND Performs AND test on each bit in a number
| Bitwise OR Performs OR test on each bit in a number
^ Bitwise XOR Performs XOR test on each bit in a number
<< Shift left Shifts the values of the bits 1 or more bits to the left
>> Shift right Shifts the values of the bits 1 or more bits to the right
>>> Shift right/zero fill Same as Shift right, but also fills the digits to the left with zeros.

For example, the following displays 8, which is the value of 2 when shifted to the left four bits (binary 10 to binary 1000):

Temp = 2;
Temp = Temp << 2;
alert (Temp);

Using the Bitwise Operators

Bitwise operators manipulate numbers one bit at a time. Suppose you put a 9 into variable This and 14 in variable That. Use the bitwise AND operator with them and you get 8 as a result. In the following discussion, I use the words AND, OR, and XOR to denote the names of the bitwise operators, rather than their symbols as used in a script: &, | and ^.

Refer to the tables earlier in this chapter for the AND and OR truth tables. Notice what happens when you AND two binary digits together (recall that a binary digit is a 0 or a 1). Only when both digits are a 1 does the result equal 1. All other instances the result is 0. That's where the name AND comes in: "If A AND B..."

With the logical OR expression, the output is 0 when both input digits are 0. In all other instances, the output is 1. Finally, with the logical XOR (which means eXclusive OR) expression, the output is 1 if either digit is a 1, and the other is a 0. But if both digits are a 1 or a 0, then the output is 0.

To visualize how JavaScript come up with a result of 8 when it ANDed the numbers "9" and "14" together, you have to reduce those numbers to their binary equivalents.

Binary Number Binary Equivalent
9 1001
14 1110

Using the truth table, manually compute what happens when you AND these two numbers together.

1001 = 9

1110 = 14

AND ____

1000 = 8

Binary 1000 is equivalent to decimal 8. Using the same numbers, perform an OR computation.

1001 = 9

1110 = 14

OR ____

1111 = 15

For your reference, here are the binary equivalents of the first 16 numbers (counting zero as the first digit, and ending with 15). You can count higher by adding an extra 1 or 0 digit on the left. The extra digit increases the count by a power of two -- 31, 63, 127, 255, 511, 1023, etc.

Decimal Number	Binary Equivalent
0   		0000
1   		0001
2   		0010
3   		0011
4   		0100
5   		0101
6   		0110
7   		0111
8   		1000
9   		1001
10   		1010
11   		1011
12   		1100
13   		1101
14   		1110
15   		1111

How can bitwise operations be used in a JavaScript program? One way is to combine more than one numeric value in a single variable, then use the AND bitwise operator (&) to determine what numbers are in the variable. This process uses "powers of two" numbers; that is, 1, 2, 4, 8, 16, 32, 64, and so forth. Each of these numbers contains a single 1 bit; the other bits are 0.

Consider for example the numbers 2, 8, and 16. Here are the binary representations of these numbers:

Number	Binary Equivalent
2  	00010
8  	01000
16  	10000

Add these numbers together, and you get 26 (2+8+16). The binary equivalent of 26 is 11010. Notice that there's a 1 in the binary equivalent for every 1 in the numbers that were summed. This is very important.

Now comes the task of finding out what powers-of-two numbers are contained in 26. This is done by ANDing the number with 26. Let's take each powers-of-two number in turn to see what the result is. If the answer is 0, then the powers-of-two number used in the expression is not part of the value 26.

00001 = 1

11010 = 26

AND ____

00000 = 0 -- no match

00010 = 2

11010 = 26

AND ____

00010 = 2 -- a match!

00100 = 4

11010 = 26

AND ____

00000 = 0 -- no match

01000 = 8

11010 = 26

AND ____

01000 = 8 -- a match!

10000 = 16

11010 = 26

AND ____

10000 = 16 -- a match!

As you can see from the above tests, the answer is 0 for the values that are not contained (1 and 4) within the number 26. The other tests result in the same number used as the testing value.

Now for a practical use. Suppose you want to pass a single variable to a user-defined procedure you have created. This function displays any of a combination of four messages in a JavaScript alert box dialog box. You specify which message you want to appear by using the values 1, 2, 4, and/or 8. You can use these values, or add them together if you want to show multiple messages.

function test ()  {
Ret=showMessage (15);
alert (Ret);
function showMessage (MessageVal) {
OutputString = "\n";
if (MessageVal & 1)
	OutputString += "You've just won a million dollars!\n";
if (MessageVal & 2)
	OutputString += "Payment will begin next Monday!\n";
if (MessageVal & 4)
	OutputString += "We'll pay you in cash!\n";
if (MessageVal & 8)
	OutputString += "You will be audited by the IRS!\n";
return (OutputString);

Some example single message results:

MessageVal 	String
0   		Nothing
1   		You've just won a million dollars!
2   		Payment will begin next Monday!
4   		We'll pay you in cash!
8   		You will be audited by the IRS!

Some sample multiple message results:

MessageVal 	Strings
3   		You've just one a million dollars!
		Payment will begin next Monday!
10   		Payment will begin next Monday!
		You will be audited by the IRS!

Note: A MessageVal of 15 displays all four messages.

Operators and Strings

Recall that in a JavaScript program a string is any assortment of text characters. You can't perform math calculations with text, but you can compare one string of text against another.

With the exception of && (AND) and || (OR), the relational operators can be used with strings for the purpose of comparing them. For instance, you may want to see if two strings are the same, as in:

if ("MyString" == "StringMy");

This results in false, because they are not the same. In a working script, no doubt you'd construct the string comparison to work with variables, as in

if (StringVar1 == StringVar2);

JavaScript compares the contents of the two variables, and reports true or false, accordingly.

JavaScript considers the case of the characters when you compare strings. The strings must match exactly, including the case of the string. Examples:

String 1 String 2 Result
hello hello Match
Hello hello No match
HELLO hello No match

While the == (equals) operator is used extensively in comparing strings, you can use !<, !>, <, >, <=, and >= as well. The != (not equal) operator is an obvious choice -- you can use it to check if one string is not equal to another. But why the others? Don't they check if one value is greater or lesser than the other? How can one string have "less" or "more" value than the other?

The < and > operators do indeed test for greater than and less than, and while they will work with strings, they don't work in exactly the way you may think. Strings -- whether they are composed of one character or many -- have a numeric value in JavaScript.

String comparisons using the < and > operators are not often used, except when performing certain special operations, like sorting. See Chapter 13, "Plug and Play Routines," for a sort routine that uses comparisons to put strings in alphabetical order.

Multiple Operators

JavaScript can handle more than one operator in an expression. This allows you to string three or more numbers, strings, or variables together to make complex expressions, such as 5+10/2*7.

With this feature of multiple operators comes a penalty: You must be careful of the order of precedence, the order in which JavaScript evaluates an expression. Like many programming languages and electronic spreadsheets programs, JavaScript doesn't merely start at the left side of the expression and calculate to the other side. Rather, it calculates multiplication and division first, then addition and subtraction, and so forth, following a general left-to-right progression..

Here is the order in which JavaScript evaluates an expression, from highest to lowest:

Order Operator
1 -(unary minus), +(unary plus), ~(bitwise not), !(logical not), ++, --
2 *(multiply), /(divide), %, /
3 +(add), -(subtract)
4 <<(shift left) >>(shift right), >>>(shift right, zero-fill)
5 <(less than), <=(less than or equal to), >(greater than), >=(greater than or equal to), !>(not equal), ==(equal)
6 &(bitwise and)
7 ^(bitwise xor)
8 |(bitwise or)
9 AND(logical and)
10 XOR(logical xor)
11 OR(logical or)
12 ?:(conditional)
13 assignment
14 , (comma)

JavaScript doesn't distinguish between operators on the same level or precedence. If it encounters a + for addition and a - for subtraction, it will evaluate the expression by using the first operator it encounters, going from left to right. You have to be careful, though, and discern the difference between subtraction and a number that you have identified as negative.

As you can see, you can get some wild results if you let the "natural" order or precedence JavaScript uses take control. You can specify another calculation order by using parentheses. Values and operators inside the parentheses are evaluated first. You can write complex expressions using parentheses inside other parentheses. JavaScript always starts at the innermost parentheses, and works outward, such as


This expression is evaluated as follows (the answer is 9.4, with rounding).

  1. Add 45 plus 2
  2. Divide the result obtained in step 1 by 10.
  3. Multiply the result obtained in step two by 2.

Logical (true/false) expressions also use parentheses to control the order of evaluation. Controlling the order of evaluation is particularly important in logical expressions, as leaving out parentheses, or using them incorrectly, can cause JavaScript to evaluate a true expression as false, and vice versa. The general syntax is

((true/false test1) && (true/false test2))

Note the parentheses around the two true/false tests, and a third set around everything. JavaScript doesn't mind if you put extra spaces between the parenthesis of your expressions. An expression with ( ( is just as valid as ((. The spaces can help you visualize the structure of the expression. Use whatever method is the most comfortable for you.

Here is the basic rule of thumb for setting the order of precedence for logical expressions: Each complete logical expression should be enclosed in its own parentheses. You can then apply additional logical operators. The entire expression is then enclosed in parentheses for the script state (if, while, for, etc.). Examples:

// If MyVar equals 10, AND YourVar equals 30, then true
if ((MyVar == 10)&& (YourVar == 30))
// If either Path or MyPath is "", then true
if ((Path == "") || (MyPath == ""))
// If Name is either "Fred" or "John," then true
if ((Name == "Fred") || (Name == "John"))

Comments are welcome

Copyright © 1996 Gordon McComb and
Revised: October 29, 1996