Richard G Baldwin (512) 223-4758, baldwin@austin.cc.tx.us, http://www.austin.cc.tx.us/baldwin/

JavaScript Programming, Operators

Java/Web Programming, Lecture Notes # 2115, Revised 05/23/98.

Preface

The material was prepared as part of a new tutorial that I plan to publish on Web programming in general.  It is not part of the Java academic curriculum at ACC.

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.

 

Introduction

Earlier lessons have discussed how literal values, variables, function calls, and operators are combined to create expressions.  It has also been pointed out that expressions are combined to create statements and statements are combined to create programs.

JavaScript has the following types of operators:

This lesson discusses the various operators and also contains information about operator precedence.
 

Operators

An operator is said to operate on an operand.  JavaScript provides a set of operators that can be used to perform an action on one or two operands.  There is also one operator that requires three operands.

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 operators used in the above statements are the division, assignment, multiplication, and string concatenation operators.  These operators are listed below. (It isn't possible to tell the difference between an addition operator and a string concatenation operator without seeing the operator in context.)
 
  /
  =
  *
  +  
 
Of particular interest in this list is the plus sign (+). In JavaScript, the plus sign can be used to perform arithmetic addition. It can also be used to concatenate strings. When the plus sign is used to concatenate strings, if the operand on the right is a numeric or boolean value, it is automatically converted to a character string before being concatenated with the operand on the left.

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> 
 
Binary operators use infix notation, which means that the operator appears between its operands.

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

JavaScript supports various arithmetic operators on floating point and integer numbers (although JavaScript doesn't make a distinction between integer and floating point).

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
 
Also as mentioned earlier, the plus operator (+) is also used to concatenate
strings as in the following code fragment:
 
"MyVariable has a value of  " + MyNumVar + " in this script."
 
Note that this operation also coerces the value of MyNumVar to a string representation for use in the expression only. The value stored in the variable is not modified in any lasting way.

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.
 
The result of the increment and decrement operators being either prefix or postfix was discussed earlier.

Comparison Operators

JavaScript supports the binary comparison operators (often called relational operators in other languages) shown in the following table. Comparison or relational operators return either true or false as a boolean type.
 
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
 
Relational operators are frequently used in the conditional expressions of control statement such as
 
if(LeftVariable <= RightVariable). . .
 
We will discuss such statements is a subsequent lesson.

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>
 
You should also take a look at a later section on string operators to see some comments regarding the application of the comparison operators to strings.
 

Logical Operators

The relational or comparison operators are often combined with another set of operators known as logical operators to construct more complex expressions.

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
 
This table shows the result of applying the logical operators to operands which are both of type boolean.  The first operator is the logical AND operator.  The second operator is the logical OR operator.  The third operator is the logical NOT operator.

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&lt;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&lt;B && A&lt;B: " + (A<B && A<B) + "<BR>");
      document.write(
             "A&lt;B && A&gt;B: " + (A<B && A>B) + "<BR>");
      document.write(
             "A&lt;B || A&lt;B: " + (A<B || A<B) + "<BR>");
      document.write(
             "A&lt;B || A&gt;B: " + (A<B || A>B) + "<BR>");
      document.write(
             "A&gt;B || A&gt;B: " + (A>B || A>B) + "<BR>");
      document.write("!(A&gt;B) " + (!(A>B)) + "<BR>");
      document.write("!(A&lt;B) " + (!(A<B)) + "<BR>");
      // End hiding  -->
    </SCRIPT>
  </HEAD>

  <BODY>
    <P> Done.
  </BODY>
</HTML>
 
So far, this is all pretty straight forward.  However, it can become very complex because JavaScript doesn't require that the operands of the logical operator be boolean.  For example, the following table comes directly from a current Netscape document.
 
 
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. 
As of this point in time, I have been unable to directly correlate the information in this table with experimental results.  I have researched additional Netscape material plus two different books on JavaScript to see if I could find some clarification of just what the wording in the Description column means, but so far to no avail.

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>
 
The above script illustrates the use of the " escape sequence to cause a quotation mark to appear in the output.

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)
 
Another way to say this is that the following rules apply:

.

Bitwise Operators

Bitwise operators treat their operands as a set of bits (zeros and ones), rather than as decimal, hexadecimal, or octal values.

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.
 

Bitwise Logical Operators

According to Netscape, the bitwise logical operators work as follows:
 
  • The operands are converted to thirty-two-bit integers and expressed by a series of bits (zeros and ones).
  • Each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on.
  • The operator is applied to each pair of bits, and the result is constructed bitwise.
.

Bitwise Shift Operators

The bitwise shift operators take two operands. The left operand is a quantity to be shifted, and the right operand specifies the number of bit positions by which the left operand is to be shifted. The direction of the shift operation is controlled by the operator used.

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>
.
 

Assignment Operators

The (=) is a value assigning binary operator in JavaScript. The value stored in memory and represented by the right operand is copied into the memory represented by the left operand. The value of the right operand is not changed.

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
 .

String Operators

The comparison operators can be used on strings.  When used on string values, the comparisons are based on the standard lexicographical ordering. Basically, the comparison as to which string is greater than another string depends on the relative positions of the characters in the collating table used by the language.

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 &gt; ABC: " + ("ABC" > "ABC") + "<BR>");
      document.write("ABC == ABC: " + ("ABC" == "ABC") + "<BR>");
      document.write("ABC &lt; ABC: " + ("ABC" < "ABC") + "<BR>");
      document.write("ABC &lt; abc: " + ("ABC" < "abc") + "<BR>");
      document.write("ABC &lt; ABCD: " + ("ABC" < "ABCD") + "<BR>");
      document.write("ABC == ABCD: " + ("ABC" == "ABCD") + "<BR>");
      document.write("ABD &lt; ACD: " + ("ABD" < "ACD") + "<BR>");
      document.write("ABC &lt; 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.
 

Special Operators

conditional operator

The conditional operator requires three operands. The operator can return either one of two values based on the evaluation of an expression shown here as condition. The syntax is
 
(condition) ? X : Y
 
If the condition expression evaluates to true, the operator returns the value of X. Otherwise it returns the value of Y.  I like to think of this as a very compact alternative to an if statement. (if statements are covered in a subsequent lesson.)

comma operator

The comma operator (,) simply evaluates both of its operands and returns the value of the second operand. This operator is primarily used inside a for loop, to allow multiple variables to be updated each iteration of the loop.

We will see some examples of the use of this operator when we study for loops.

delete

The delete operator deletes an object's property or an element at a specified index in an array. Its syntax is
 
delete objectName.property
delete objectname[index]
delete property
 
where The third form is legal only within a with statement. This will probably all make more sense to you once we study objects and arrays.

If the deletion succeeds, the delete operator sets the property or element to undefined. delete always returns undefined.

new

You can use the new operator to create an instance of a user-defined object type or of one of the predefined object types.  We will become very familiar with the use of the new operator when we study objects.

typeof

The typeof operator is used in either of the following ways: The typeof operator returns a string indicating the type of the unevaluated operand. operand is the string, variable, keyword, or object for which the type is to be returned. The parentheses are optional.

void

The void operator is used in either of the following ways:  
The void operator specifies an expression to be evaluated without returning a value. expression is a JavaScript expression to evaluate.

The parentheses surrounding the expression are optional.
 

Operator Precedence

The precedence of operators determines the order they are applied when evaluating an expression. You can override operator precedence by using parentheses.

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
 
The following table describes the precedence of operators, from lowest to highest. When an expression contains two or more operators at the same level of precedence, they are evaluated from left to right.

  
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  ()   []   .
 
-end-