[Contents] [Previous] [Next] [Index]

Chapter 2
Operators

JavaScript has assignment, comparison, arithmetic, bitwise, logical, string, and special operators. This chapter describes the operators and contains information about operator precedence.

Table 2.1 summarizes all of the JavaScript operators.

Table 2.1 JavaScript operators.  
Operator Category Operator Description
Arithmetic Operators

+
(Addition) Adds 2 numbers.

++
(Increment) Adds one to a variable representing a number (returning either the new or old value of the variable)

-
(Unary negation, subtraction) As a unary operator, negates the value of its argument. As a binary operator, subtracts 2 numbers.

--
(Decrement) Subtracts one from a variable representing a number (returning either the new or old value of the variable)

*
(Multiplication) Multiplies 2 numbers.

/
(Division) Divides 2 numbers.

%
(Modulus) Computes the integer remainder of dividing 2 numbers.

String Operators

+

(String addition) Concatenates 2 strings.

+=

Concatenates 2 strings and assigns the result to the first operand.

Logical Operators

&&

(Logical AND) Returns true if both logical operands are true. Otherwise, returns false.

||

(Logical OR) Returns true if either logical expression is true. If both are false, returns false.

!

(Logical negation) If its single operand is true, returns false; otherwise, returns true.

Bitwise Operators

&
(Bitwise AND) Returns a one in each bit position if bits of both operands are ones.

^
(Bitwise XOR) Returns a one in a bit position if bits of one but not both operands are one.

|
(Bitwise OR) Returns a one in a bit if bits of either operand is one.

~
(Bitwise NOT) Flips the bits of its operand.

<<
(Left shift) Shifts its first operand in binary representation the number of bits to the left specified in the second operand, shifting in zeros from the right.

>>
(Sign-propagating right shift) Shifts the first operand in binary representation the number of bits to the right specified in the second operand, discarding bits shifted off.

>>>
(Zero-fill right shift) Shifts the first operand in binary representation the number of bits to the right specified in the second operand, discarding bits shifted off, and shifting in zeros from the left.

Assignment Operators

=
Assigns the value of the second operand to the first operand.

+=
Adds 2 numbers and assigns the result to the first.

-=
Subtracts 2 numbers and assigns the result to the first.

*=
Multiplies 2 numbers and assigns the result to the first.

/=
Divides 2 numbers and assigns the result to the first.

%=
Computes the modulus of 2 numbers and assigns the result to the first.

&=
Performs a bitwise AND and assigns the result to the first operand.

^=
Performs a bitwise XOR and assigns the result to the first operand.

|=
Performs a bitwise OR and assigns the result to the first operand.

<<=
Performs a left shift and assigns the result to the first operand.

>>=
Performs a sign-propagating right shift and assigns the result to the first operand.

>>>=
Performs a zero-fill right shift and assigns the result to the first operand.

Comparison Operators

==

Returns true if the operands are equal.

!=

Returns true if the operands are not equal.

>

Returns true if left operand is greater than right operand.

>=

Returns true if left operand is greater than or equal to right operand.

<

Returns true if left operand is less than right operand.

<=

Returns true if left operand is less than or equal to right operand.

Special Operators

?:
Lets you perform a simple "if...then...else"

,
Evaluates two expressions and returns the result of the second expression.

delete
Lets you delete an object property or an element at a specified index in an array.

new
Lets you create an instance of a user-defined object type or of one of the built-in object types.

this
Keyword that you can use to refer to the current object.

typeof
Returns a string indicating the type of the unevaluated operand.

void
The void operator specifies an expression to be evaluated without returning a value.

Assignment Operators

An assignment operator assigns a value to its left operand based on the value of its right operand.

Implemented in

Navigator 2.0

The basic assignment operator is equal (=), which assigns the value of its right operand to its left operand. That is, x = y assigns the value of y to x. The other assignment operators are shorthand for standard operations, as shown in Table 2.2.

Table 2.2 Assignment operators
Shorthand 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

Comparison Operators

A comparison operator compares its operands and returns a logical value based on whether the comparison is true or not. The operands can be numerical or string values. When used on string values, the comparisons are based on the standard lexicographical ordering.

Implemented in

Navigator 2.0

They are described in Table 2.3. In the examples in this table, assume var1 has been assigned the value 3 and var2 had been assigned the value 4.

Table 2.3 Comparison operators
Operator Description Examples returning true
Equal (==)

Returns true if the operands are equal.

3 == var1
Not equal (!=)

Returns true if the operands are not equal.

var1 != 4
Greater than (>)

Returns true if left operand is greater than right operand.

var2 > var1
Greater than or equal (>=)

Returns true if left operand is greater than or equal to right operand.

var2 >= var1
var1 >= 3
Less than (<)

Returns true if left operand is less than right operand.

var1 < var2
Less than or equal (<=)

Returns true if left operand is less than or equal to right operand.

var1 <= var2
var2 <= 5

Arithmetic Operators

Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value. The standard arithmetic operators are addition (+), subtraction (-), multiplication (*), and division (/). These operators work as they do in other programming languages.

Implemented in

Navigator 2.0

% (Modulus)

The modulus operator is used as follows:

var1 % var2
The modulus operator returns the first operand modulo the second operand, that is, var1 modulo var2, in the preceding statement, where var1 and var2 are variables. The modulo function is the integer remainder of dividing var1 by var2. For example, 12 % 5 returns 2.

++ (Increment)

The increment operator is used as follows:

var++ or ++var

This operator increments (adds one to) its operand and returns a value. If used postfix, with operator after operand (for example, x++), then it returns the value before incrementing. If used prefix with operator before operand (for example, ++x), then it returns the value after incrementing.

For example, if x is three, then the statement y = x++ sets y to 3 and increments x to 4. If x is 3, then the statement y = ++x increments x to 4 and sets y to 4.

-- (Decrement)

The decrement operator is used as follows:

var-- or --var

This operator decrements (subtracts one from) its operand and returns a value. If used postfix (for example, x--), then it returns the value before decrementing. If used prefix (for example, --x), then it returns the value after decrementing.

For example, if x is three, then the statement y = x-- sets y to 3 and decrements x to 2. If x is 3, then the statement y = --x decrements x to 2 and sets y to 2.

- (Unary Negation)

The unary negation operator precedes its operand and negates it. For example, y = -x negates the value of x and assigns that to y; that is, if x were 3, y would get the value -3 and x would retain the value 3.

Bitwise Operators

Bitwise operators treat their operands as a set of bits (zeros and ones), rather than as decimal, hexadecimal, or octal numbers. For example, the decimal number nine has a binary representation of 1001. Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values.

Table 2.4 summarizes JavaScript's bitwise operators

Table 2.4 Bitwise operators
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.

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

Implemented in

Navigator 2.0

Conceptually, the bitwise logical operators work as follows:

For example, the binary representation of nine is 1001, and the binary representation of fifteen is 1111. So, when the bitwise operators are applied to these values, the results are as follows:

Bitwise Shift Operators

Implemented in

Navigator 2.0

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

Shift operators convert their operands to thirty-two-bit integers and return a result of the same type as the left operator.

<< (Left Shift)

This operator shifts the first operand the specified number of bits to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right.

For example, 9<<2 yields thirty-six, because 1001 shifted two bits to the left becomes 100100, which is thirty-six.

>> (Sign-Propagating Right Shift)

This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Copies of the leftmost bit are shifted in from the left.

For example, 9>>2 yields two, because 1001 shifted two bits to the right becomes 10, which is two. Likewise, -9>>2 yields -3, because the sign is preserved.

>>> (Zero-Fill Right Shift)

This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Zero bits are shifted in from the left.

For example, 19>>>2 yields four, because 10011 shifted two bits to the right becomes 100, which is four. For non-negative numbers, zero-fill right shift and sign-propagating right shift yield the same result.

Logical Operators

Logical operators take Boolean (logical) values as operands and return a Boolean value.

Implemented in

Navigator 2.0

They are described in Table 2.5.

Table 2.5 Logical operators
Operator Usage Description
and (&&)

expr1 && expr2
Returns expr1 if it converts to false. Otherwise, returns expr2.

or (||)

expr1 || expr2
Returns expr1 if it converts to true. Otherwise, returns expr2.

not (!)

!expr
If expr is true, returns false; if expr is false, returns true.

Examples

Consider the following script:

<script language="JavaScript1.2">"
v1 = "Cat";
v2 = "Dog";
v3 = false;
document.writeln("t && t returns " + (v1 && v2));
document.writeln("f && t returns " + (v3 && v1));
document.writeln("t && f returns " + (v1 && v3));
document.writeln("f && f returns " + (v3 && (3 == 4)));
document.writeln("t || t returns " + (v1 || v2));
document.writeln("f || t returns " + (v3 || v1));
document.writeln("t || f returns " + (v1 || v3));
document.writeln("f || f returns " + (v3 || (3 == 4)));
document.writeln("!t returns " + (!v1));
document.writeln("!f returns " + (!v3));
</script>
This script displays the following:

t && t returns Dog
f && t returns false
t && f returns false
f && f returns false
t || t returns Cat
f || t returns Cat
t || f returns Cat
f || f returns false
!t returns false
!f returns true

Short-Circuit Evaluation

As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the following rules:

The rules of logic guarantee that these evaluations are always correct. Note that the anything part of the above expressions is not evaluated, so any side effects of doing so do not take effect.

String Operators

In addition to the comparison operators, which can be used on string values, the concatenation operator (+) concatenates two string values together, returning another string that is the union of the two operand strings. For example, "my " + "string" returns the string "my string".

Implemented in

Navigator 2.0

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.

Special Operators

?: (Conditional operator)

The conditional operator is the only JavaScript operator that takes three operands. This operator is frequently used as a shortcut for the if statement.

Implemented in

Navigator 2.0

Syntax

condition ? expr1 : expr2

Parameters

condition
an expression that evaluates to true or false

expr1, expr2
expressions with values of any type.

Description

If condition is true, the operator returns the value of expr1; otherwise, it returns the value of expr2. For example, to display a different message based on the value of the isMember variable, you could use this statement:

document.write ("The fee is " + (isMember ? "$2.00" : "$10.00"))

, (Comma operator)

The comma operator is very simple. It evaluates both of its operands and returns the value of the second operand.

Implemented in

Navigator 2.0

Syntax

expr1, expr2

Parameters

expr1, expr2
Any expressions

Description

You can use the comma operator when you want to include multiple expressions in a location that requires a single expression. The most common usage of this operator is to supply multiple parameters in a for loop.

For example, if a is a 2-dimensional array with 10 elements on a side, the following code uses the comma operator to increment two variables at once. The code prints the values of the diagonal elements in the array:

for (var i=0, j=10; i <= 10; i++, j--)
   document.writeln("a["+i+","+j+"]= " + a[i,j])

delete

Deletes an object's property or an element at a specified index in an array.

Implemented in

Navigator 2.0

Syntax

delete objectName.property
delete objectName[index]
delete property

Parameters

objectName
The name of an object.

property
An existing property.

index
An integer representing the location of an element in an array

Description

The third form is legal only within a with statement.

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

new

An operator that lets you create an instance of a user-defined object type or of one of the built-in object types that has a constructor function.

Implemented in

Navigator 2.0

Syntax

objectName = new objectType (param1 [,param2] ...[,paramN])

Arguments

objectName
Name of the new object instance.

objectType
Object type. It must be a function that defines an object type.

param1...paramN
Property values for the object. These properties are parameters defined for the objectType function.

Description

Creating a user-defined object type requires two steps:

  1. Define the object type by writing a function.

  2. Create an instance of the object with new.
To define an object type, create a function for the object type that specifies its name, properties, and methods. An object can have a property that is itself another object. See the examples below.

You can always add a property to a previously defined object. For example, the statement car1.color = "black" adds a property color to car1, and assigns it a value of "black". However, this does not affect any other objects. To add the new property to all objects of the same type, you must add the property to the definition of the car object type.

You can add a property to a previously defined object type by using the Function.prototype property. This defines a property that is shared by all objects created with that function, rather than by just one instance of the object type. The following code adds a color property to all objects of type car, and then assigns a value to the color property of the object car1. For more information, see prototype

Car.prototype.color=null
car1.color="black"
birthday.description="The day you were born"

Examples

Example 1: object type and object instance. Suppose you want to create an object type for cars. You want this type of object to be called car, and you want it to have properties for make, model, and year. To do this, you would write the following function:

function car(make, model, year) {
   this.make = make
   this.model = model
   this.year = year
}
Now you can create an object called mycar as follows:

mycar = new car("Eagle", "Talon TSi", 1993)
This statement creates mycar and assigns it the specified values for its properties. Then the value of mycar.make is the string "Eagle", mycar.year is the integer 1993, and so on.

You can create any number of car objects by calls to new. For example,

kenscar = new car("Nissan", "300ZX", 1992)
Example 2: object property that is itself another object. Suppose you define an object called person as follows:

function person(name, age, sex) {
   this.name = name
   this.age = age
   this.sex = sex
}
And then instantiate two new person objects as follows:

rand = new person("Rand McNally", 33, "M")
ken = new person("Ken Jones", 39, "M")
Then you can rewrite the definition of car to include an owner property that takes a person object, as follows:

function car(make, model, year, owner) {
   this.make = make;
   this.model = model;
   this.year = year;
   this.owner = owner;
}
To instantiate the new objects, you then use the following:

car1 = new car("Eagle", "Talon TSi", 1993, rand);
car2 = new car("Nissan", "300ZX", 1992, ken)
Instead of passing a literal string or integer value when creating the new objects, the above statements pass the objects rand and ken as the parameters for the owners. To find out the name of the owner of car2, you can access the following property:

car2.owner.name

this

A keyword that you can use to refer to the current object. In general, in a method this refers to the calling object.

Implemented in

Navigator 2.0

Syntax

this[.propertyName]

Examples

Suppose a function called validate validates an object's value property, given the object and the high and low values:

function validate(obj, lowval, hival) {
   if ((obj.value < lowval) || (obj.value > hival))
      alert("Invalid Value!")
}
You could call validate in each form element's onChange event handler, using this to pass it the form element, as in the following example:

<B>Enter a number between 18 and 99:</B>
<INPUT TYPE = "text" NAME = "age" SIZE = 3
   onChange="validate(this, 18, 99)">

typeof

The typeof operator is used in either of the following ways:

1. typeof operand
2. typeof (operand)
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.

Implemented in

Navigator 3.0

Suppose you define the following variables:

var myFun = new Function("5+2")
var shape="round"
var size=1
var today=new Date()
The typeof operator returns the following results for these variables:

typeof myFun is object
typeof shape is string
typeof size is number
typeof today is object
typeof dontExist is undefined
For the keywords true and null, the typeof operator returns the following results:

typeof true is boolean
typeof null is object
For a number or string, the typeof operator returns the following results:

typeof 62 is number
typeof 'Hello world' is string
For property values, the typeof operator returns the type of value the property contains:

typeof document.lastModified is string
typeof window.length is number
typeof Math.LN2 is number
For methods and functions, the typeof operator returns results as follows:

typeof blur is function
typeof eval is function
typeof parseInt is function
typeof shape.split is function
For predefined objects, the typeof operator returns results as follows:

typeof Date is function
typeof Function is function
typeof Math is function
typeof Option is function
typeof String is function

void

The void operator is used in either of the following ways:

1. javascript:void (expression)
2. javascript:void expression
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, but it is good style to use them.

Implemented in

Navigator 3.0

You can use the void operator to specify an expression as a hypertext link. The expression is evaluated but is not loaded in place of the current document.

The following code creates a hypertext link that does nothing when the user clicks it. When the user clicks the link, void(0) evaluates to 0, but that has no effect in JavaScript.

<A HREF="javascript:void(0)">Click here to do nothing</A>
The following code creates a hypertext link that submits a form when the user clicks it.

<A HREF="javascript:void(document.form.submit())">
Click here to submit</A>


[Contents] [Previous] [Next] [Index]

Last Updated: 10/31/97 12:29:53


Copyright ?1997 Netscape Communications Corporation