The purpose of this series of lessons is to teach you how to program in JavaScript. The goal is to provide a programming tutorial that will be accessible to persons with no programming experience and will be equally useful to persons who already have programming experience using JavaScript or some other language.
JavaScript has the following types of operators:
An operator which operates on one operand is called a unary operator, and an operator that operates on two operands is called a binary operator.
JavaScript also provides one operator that operates on three operands. This operator is called a ternary operator and will be discussed in the section on special operators.
Some operators can function either as a unary or as a binary operator, the best known of which is probably the minus sign. As a binary operator, the minus sign causes its right operand to be subtracted from its left operand. As a unary operator, the minus sign causes the algebraic sign of the right operand to be changed.
It may be important for you to know that in many respects, the JavaScript operators behave in an identical fashion to the same operators used in both Java and C++. Thus, once you have learned how the operators behave in JavaScript, you are well on your way to knowing how to use operators in these other two important programming languages as well.
The following statements illustrate the use of several operators in
the sample JavaScript scripts from previous lessons.
return incomingParameter/2; theArea = 3.14159 * theRadius * theRadius; area = getArea(3.1); document.write("Area is: " + area + "<BR>"); |
/ = * + |
The use of a single operator symbol for two purposes is known as operator overloading. While JavaScript provides overloaded behavior for the (+), it does not give the programmer the ability to overload operators as is the case in some other languages such as C++.
An extremely important unary operator that is used in JavaScript is the increment operator (++).
This operator is somewhat complex because it is used in both prefix and postfix notation. Basically, the increment operator causes the value of the variable to which it is applied to be increased by one.
With the prefix version, the operand appears to the right of the operator ( ++X), while with the postfix version, the operand appears to the left of the operator (X++).
The difference in prefix and postfix has to do with the point in time that the increment actually occurs if the operator and its operand appear as part of a larger overall expression.
With the prefix version, the variable is incremented before it is used to evaluate the larger overall expression.
With the postfix version, the variable is used to evaluate the larger overall expression and then it is incremented.
The use of both the prefix and postfix versions of the
increment operator is illustrated in the following JavaScript script.
<!-- File Js00000080.htm Copyright 1998, R.G.Baldwin This JavaScript script is designed to illustrate the use of the increment operator. The output from running this script is: a = 5 b = 5 a + b++ = 10 b = 6 c = 5 d = 5 c + ++d = 11 d = 6 Done. ----------------------------------------------------------> <HTML> <HEAD> <SCRIPT LANGUAGE="JavaScript1.2"> <!-- Hide script var a = 5, b = 5, c = 5, d = 5; document.write("a = " + a + "<BR>"); document.write("b = " + b + "<BR>"); document.write("a + b++ = " + (a + b++) + "<BR>"); document.write("b = " + b + "<BR>"); document.write("<BR>"); document.write("c = " + c + "<BR>"); document.write("d = " + d + "<BR>"); document.write("c + ++d = " + (c + ++d) + "<BR>"); document.write("d = " + d + "<BR>"); // End hiding --> </SCRIPT> </HEAD> <BODY> <P> Done. </BODY> </HTML> |
As a result of performing the specified action, an operator is said
to return a value (or evaluate to a value) of a given type. The
type of value returned depends on the operator and the type of the operands.
To evaluate to a value means that after the action is performed, the operator and its operands is effectively replaced in the expression by the value that is returned. |
Arithmetic operators take numeric operands (either literals or variables),
perform the specified arithmetic, and return a single numeric value.
The following table lists the binary arithmetic operators supported
by JavaScript.
Operator | Description |
+ | Addition: Adds its operands |
- | Subtraction: Subtracts the right operand from the left operand |
* | Multiplication: Multiplies the operands |
/ | Division: Divides the left operand by the right operand |
% | Modulus: Returns integer remainder of dividing the left operand by the right operand |
"MyVariable has a value of " + MyNumVar + " in this script." |
JavaScript supports the following unary arithmetic operators.
Operator | Description |
+ | Indicates a positive value. Essentially does nothing. |
- | Negates, or changes the algebraic sign. |
++ | Adds one to the operand, both prefix and postfix as discussed earlier. |
-- | Subtracts one from the operand, both prefix and postfix. |
Operator | Returns true if |
> | Left operand is greater than right operand |
>= | Left operand is greater than or equal to right operand |
< | Left operand is less than right operand |
<= | Left operand is less than or equal to right operand |
== | Left operand is equal to right operand |
!= | Left operand is not equal to right operand |
if(LeftVariable <= RightVariable). . . |
The following script illustrates the result of applying relational operators in JavaScript. The output is shown in the comments at the beginning of the script.
Note that the string concatenation operator coerced the boolean value
returned by the relational operator into a string and concatenated it to
the string on the left of the concatenation operator.
<!-- File Js00000090.htm Copyright 1998, R.G.Baldwin This JavaScript script is designed to illustrate the use of the comparison or relational operators. The output from running this script is: The relational 6<5 is false The relational 6>5 is true Done. ----------------------------------------------------------> <HTML> <HEAD> <SCRIPT LANGUAGE="JavaScript1.2"> <!-- Hide script document.write( "The relational 6<5 is " + (6<5) + "<BR>" ); document.write("The relational 6>5 is " + (6>5) ); // End hiding --> </SCRIPT> </HEAD> <BODY> <P> Done. </BODY> </HTML> |
JavaScript supports three logical operators as shown in the following
table.
Operator | Typical Use | Returns true if |
&& |
Left && Right |
Left and Right are both true |
|| |
Left || Right |
Either Left or Right is true |
! |
! Right |
Right is false |
Examples of the use of these operators are provided in the following script.
This script also illustrates that when using JavaScript to generate
HTML, it is necessary to always be vigilant to make certain that valid
HTML is generated. In order to create the text A<B, it
was necessary to use an HTML entity and write it as A<B.
Otherwise, the script simply didn't produce the correct output. In case
you don't know about the use of entities in HTML, you can find that information
in the HTML tutorial that I referred you to in an earlier lesson.
<!-- File Js00000100.htm Copyright 1998, R.G.Baldwin This JavaScript script is designed to illustrate the use of the logical operators for boolean operands. Note that it does not illustrate the use of the logical operators for those cases where the operands are not boolean (where the operands are strings for example). The output from running this script is: A equals: 65 B equals: 66 A<B && A<B: true A<B && A>B: false A<B || A<B: true A<B || A>B: true A>B || A>B: false !(A>B) true !(A<B) false Done. ----------------------------------------------------------> <HTML> <HEAD> <SCRIPT LANGUAGE="JavaScript1.2"> <!-- Hide script A=65, B=66; document.write("A equals: " + A + "<BR>"); document.write("B equals: " + B + "<BR>"); document.write( "A<B && A<B: " + (A<B && A<B) + "<BR>"); document.write( "A<B && A>B: " + (A<B && A>B) + "<BR>"); document.write( "A<B || A<B: " + (A<B || A<B) + "<BR>"); document.write( "A<B || A>B: " + (A<B || A>B) + "<BR>"); document.write( "A>B || A>B: " + (A>B || A>B) + "<BR>"); document.write("!(A>B) " + (!(A>B)) + "<BR>"); document.write("!(A<B) " + (!(A<B)) + "<BR>"); // End hiding --> </SCRIPT> </HEAD> <BODY> <P> Done. </BODY> </HTML> |
Operator | Usage | Description | Example |
---|---|---|---|
and (&&) |
expr1 && expr2 |
Returns expr1 if it converts to false. Otherwise, returns expr2. | var1 && var2 returns "Dog".
var2 && var3 returns false |
or (||) |
expr1 || expr2 |
Returns expr1 if it converts to true. Otherwise, returns expr2. | var1 || var2 returns "Cat".
var3 || var1 returns "Cat". var3 || (3==4) returns false. |
not (!) |
!expr |
If expr is true, returns false; if expr is false, returns true. | !var1 returns false.
!var3 returns true. |
1 Assume var1 is "Cat", var2 is "Dog", and var3 is false. |
The following script demonstrates that JavaScript will execute logical expressions where the operands are strings so there is clearly something to this. It seems to me that the results of this script for the logical and and the logical or seem to be backwards relative to the explanation given in the Description column above. However, I probably don't know how to interpret the explanation given in that column.
<!-- File Js00000110.htm Copyright 1998, R.G.Baldwin This JavaScript script is designed to illustrate the use of the logical operators for string operands. The output from running this script is: "cat" && "cat": cat "cat" && "dog": dog "dog" && "cat": cat "cat" || "cat": cat "cat" || "dog": cat "dog" || "dog": dog !("dog") false !("cat") false Done. ----------------------------------------------------------> <HTML> <HEAD> <SCRIPT LANGUAGE="JavaScript1.2"> <!-- Hide script document.write( "\"cat\" && \"cat\": " + ("cat" && "cat") + "<BR>"); document.write( "\"cat\" && \"dog\": " + ("cat" && "dog") + "<BR>"); document.write( "\"dog\" && \"cat\": " + ("dog" && "cat") + "<BR>"); document.write( "\"cat\" || \"cat\": " + ("cat" || "cat") + "<BR>"); document.write( "\"cat\" || \"dog\": " + ("cat" || "dog") + "<BR>"); document.write( "\"dog\" || \"dog\": " + ("dog" || "dog") + "<BR>"); document.write("!(\"dog\") " + (!("dog")) + "<BR>"); document.write("!(\"cat\") " + (!("cat")) + "<BR>"); // End hiding --> </SCRIPT> </HEAD> <BODY> <P> Done. </BODY> </HTML> |
An important characteristic of the behavior of the && and || operators in JavaScript is that the expressions are evaluated from left to right, and the evaluation of the expression is terminated as soon as the result of evaluating the expression can be determined.
For example, in the following expression, if the variable a is
less than the variable b , so that the first term evaluates to true,
there is no need to evaluate the right operand of the || to
determine the value of the entire expression. Thus, evaluation will terminate
as soon as the answer can be determined.
(a < b) || (c < d) |
Bitwise logical operators perform a logical operation between the corresponding bits in two numeric values.
Bitwise shift operators shift each bit into the neighboring bit position, either left or right.
If you don't have a good understanding of the binary representation of numeric data, you should probably skip this section until you gain such an understanding.
The following table summarizes JavaScript's bitwise operators. Note that the bitwise AND operator is a single & whereas the logical AND operator discussed elsewhere in this lesson is a double &&.
Similarly, the bitwise OR operator is a single | whereas the logical OR operator discussed elsewhere is a double ||. Getting these mixed up and using the incorrect form is a common programming error.
Operator | Usage | Description |
---|---|---|
Bitwise AND |
a & b |
Returns a one in each bit position if bits of both operands are ones. |
Bitwise OR |
a | b |
Returns a one in a bit if bits of either operand is one. |
Bitwise XOR |
a ^ b |
Returns a one in a bit position if bits of one but not both operands are one. |
Bitwise NOT |
~ a |
Flips the bits of its operand. |
Left shift |
a << b |
Shifts a in binary representation b bits to left, shifting in zeros from the right. |
Sign-propagating right shift |
a >> b |
Shifts a in binary representation b bits to right, discarding bits shifted off. Most significant bit is reproduced into bits to its right. |
Zero-fill right shift |
a >>> b |
Shifts a in binary representation b bits to the right, discarding bits shifted off, and shifting in zeros from the left. |
|
Again, according to Netscape, shift operators convert their operands to thirty-two-bit integers and return a result of the same type as the left operand.
The following script illustrates the use of the various bitwise operators. Pay particular attention to the result of applying an unsigned right shift to a signed data value (highlighted in bold italics). If the data is intended to be treated as signed data, this is a corrupting operation.
You might also want to note that shifting is the logical equivalent
of multiplication and division, provided the sign is properly taken into
account. Each bit that an operand is shifted to the right is equivalent
to dividing that operand by two. Similarly, each bit that an operand
is shifted to the left is equivalent to multiplying that operand by two.
Therefore, shifting to the right or left by two bit positions has the effect
of dividing or multiplying by four. You can see that in the following
results where the value 4096 is converted by shifting to either 1024 or
16384.
<!-- File Js00000120.htm Copyright 1998, R.G.Baldwin This JavaScript script is designed to illustrate the use of Bitwise operators. The output from running this script is: Bitwise AND: 21 & 42: 0 Bitwise inclusive OR: 21 | 42: 63 Bitwise AND: 0xFFFFFFFF & 0xE: 14 Bitwise inclusive OR: 0xFFFFFFFF | 0xE: -1 Bitwise exclusive OR: 0xFFFFFFFF ^ 0xE: -15 Signed right shift on positive data: 4096 >>> 2: 1024 Unsigned right shift on positive data: 4096 >> 2: 1024 Unsigned right shift on negative data: -4096 >>> 2: 1073740800 Signed right shift on negative data: -4096 >> 2: -1024 Left shift on positive data: 4096 << 2: 16384 Left shift on negative data: -4096 << 2: -16384 Done. --------------------------------------------------------------> <HTML> <HEAD> <SCRIPT LANGUAGE="JavaScript1.2"> <!-- Hide script document.write("Bitwise AND: "); document.write("21 & 42: " + ((1+4+16) & (2+8+32))); document.write("<BR>"); document.write("Bitwise inclusive OR: ") document.write("21 | 42: " + ((1+4+16) | (2+8+32))); document.write("<BR>"); document.write("Bitwise AND: "); document.write("0xFFFFFFFF & 0xE: " + (0xFFFFFFFF & 0xE)); document.write("<BR>"); document.write("Bitwise inclusive OR: "); document.write("0xFFFFFFFF | 0xE: " + (0xFFFFFFFF | 0xE)); document.write("<BR>"); document.write("Bitwise exclusive OR: "); document.write("0xFFFFFFFF ^ 0xE: " + (0xFFFFFFFF ^ 0xE)); document.write("<BR>"); document.write("Signed right shift on positive data: "); document.write("4096 >>> 2: " + (4096 >>> 2)); document.write("<BR>"); document.write("Unsigned right shift on positive data: "); document.write("4096 >> 2: " + (4096 >> 2)); document.write("<BR>"); document.write("Unsigned right shift on negative data: "); document.write("-4096 >>> 2: " + (-4096 >>> 2)); document.write("<BR>"); document.write("Signed right shift on negative data: "); document.write("-4096 >> 2: " + (-4096 >> 2)); document.write("<BR>"); document.write("Left shift on positive data: "); document.write("4096 << 2: " + (4096 << 2)); document.write("<BR>"); document.write("Left shift on negative data: "); document.write("-4096 << 2: " + (-4096 << 2)); document.write("<BR>"); // End hiding --> </SCRIPT> </HEAD> <BODY> <P> Done. </BODY> </HTML> |
JavaScript also supports the following list of shortcut assignment
operators. These operators allow you to perform an assignment and another
operation with a single operator.
Shortcut Operator | Meaning |
---|---|
x += y |
x = x + y |
x -= y |
x = x - y |
x *= y |
x = x * y |
x /= y |
x = x / y |
x %= y |
x = x % y |
x <<= y |
x = x << y |
x >>= y |
x = x >> y |
x >>>= y |
x = x >>> y |
x &= y |
x = x & y |
x ^= y |
x = x ^ y |
x |= y |
x = x | y |
The following script illustrates the application of the comparison operator to strings of different lengths having the same and different characters. This is an important concept because string comparisons are often used in sorting operations.
A few things are obvious from the following results, some intuitive and some not so intuitive:
<!-- File Js00000130.htm Copyright 1998, R.G.Baldwin This JavaScript script is designed to illustrate the use of comparison or relational operators on strings. The output from running this script is: ABC > ABC: false ABC == ABC: true ABC < ABC: false ABC < abc: true ABC < ABCD: true ABC == ABCD: false ABD < ACD: true ABC < BCD: true Done. --------------------------------------------------------------> <HTML> <HEAD> <SCRIPT LANGUAGE="JavaScript1.2"> <!-- Hide script document.write("ABC > ABC: " + ("ABC" > "ABC") + "<BR>"); document.write("ABC == ABC: " + ("ABC" == "ABC") + "<BR>"); document.write("ABC < ABC: " + ("ABC" < "ABC") + "<BR>"); document.write("ABC < abc: " + ("ABC" < "abc") + "<BR>"); document.write("ABC < ABCD: " + ("ABC" < "ABCD") + "<BR>"); document.write("ABC == ABCD: " + ("ABC" == "ABCD") + "<BR>"); document.write("ABD < ACD: " + ("ABD" < "ACD") + "<BR>"); document.write("ABC < BCD: " + ("ABC" < "BCK") + "<BR>"); // End hiding --> </SCRIPT> </HEAD> <BODY> <P> Done. </BODY> </HTML> |
As mentioned earlier, the concatenation operator (+) concatenates two strings, returning another string where the right string has been attached to the end of the left string. For example, "my " + "string" returns the string "my string".
If the right operand is either a boolean value or a numeric value, it will be converted to a string for concatenation onto the left operand.
The shorthand assignment operator += can also be used to concatenate
strings. For example, if the variable mystring has the value "alpha",
then the expression mystring += "bet" evaluates to "alphabet"
and assigns this value to mystring. In this case, the left operand will
be modified through assignment.
(condition) ? X : Y |
We will see some examples of the use of this operator when we study for loops.
delete objectName.property delete objectname[index] delete property |
If the deletion succeeds, the delete operator sets the property or element to undefined. delete always returns undefined.
The parentheses surrounding the expression are optional.
As you will see in the following example, it is very important that you take precedence into account when writing expressions. Otherwise, the result of evaluating the expression might not be what you expect.
Usually the easiest way to deal with precedence is to group terms using pairs of matching parentheses. Then the expression inside the parentheses will be evaluated before that result is used in the evaluation of the expression outside the expression.
This is illustrated in the following box which shows how the result
of evaluating an expression containing the same values and the same operators
can be dramatically modified by grouping terms inside parentheses.
6 * 3 + 4 evaluates to 22 6 * (3 + 4) evaluates to 42 |
Operator type | Individual operators |
---|---|
assignment | = += -= *= /= %= <<= >>= >>>= &= ^= |= |
conditional | ?: |
logical-or | || |
logical-and | && |
bitwise-or | | |
bitwise-xor | ^ |
bitwise-and | & |
equality | == != |
relational | < <= > >= |
bitwise shift | << >> >>> |
addition/subtraction | + - |
multiply/divide | * / % |
negation/increment | ! ~ - ++ -- typeof void |
call, member | () [] . |