Chapter 5
Operators
Assignment Operators
An assignment operator assigns a value to its left operand based on the value of its right operand.a[i++] += 5 //i is evaluated only once
a[i++] = a[i++] + 5 //i is evaluated twice
Comparison Operators
A comparison operator compares its operands and returns a logical value based on whether the comparison is true.ECMA-262 includes all comparison operators except === and !==. |
- Two strings are equal when they have the same sequence of characters, same length, and same characters in corresponding positions.
- Two numbers are equal when they are numerically equal (have the same number value). NaN is not equal to anything, including NaN. Positive and negative zeros are equal.
- Two objects are equal if they refer to the same Object.
-
Two Boolean operands are equal if they are both
trueorfalse. - Null and Undefined types are equal.
1
These examples assume that var1 has been assigned the value 3 and var2 has been assigned the value 4.
|
Using the Equality Operators
The standard equality operators (== and !=) compare two operands without regard to their type. The strict equality operators (=== and !==) perform equality comparisons on operands of the same type. Use strict equality operators if the operands must be of a specific type as well as value or if the exact type of the operands is important. Otherwise, use the standard equality operators, which allow you to compare the identity of two operands even if they are not of the same type. When type conversion is needed, JavaScript convertsString, Number, Boolean, or Object operands as follows.
-
When comparing a number and a string, the string is converted to a number value. JavaScript attempts to convert the string numeric literal to a
Numbertype value. First, a mathematical value is derived from the string numeric literal. Next, this value is rounded to nearestNumbertype value. -
If one of the operands is
Boolean, the Boolean operand is converted to 1 if it istrueand +0 if it isfalse. -
If an object is compared with a number or string, JavaScript attempts to return the default value for the object. Operators attempt to convert the object to a primitive value, a
StringorNumbervalue, using thevalueOfandtoStringmethods of the objects. If this attempt to convert the object fails, a runtime error is generated.
Backward Compatibility
The behavior of the standard equality operators (== and !=) depends on the JavaScript version. JavaScript 1.2. The standard equality operators (== and !=) do not perform a type conversion before the comparison is made. The strict equality operators (=== and !==) are unavailable. JavaScript 1.1 and earlier versions. The standard equality operators (== and !=) perform a type conversion before the comparison is made. The strict equality operators (=== and !==) are unavailable.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 (/).1/2 //returns 0.5 in JavaScript
1/2 //returns 0 in Java
% (Modulus)
The modulus operator is used as follows:var1 % var2The 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 32 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. The following table summarizes JavaScript's bitwise operators:Bitwise Logical Operators
- 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.
- 15 & 9 yields 9 (1111 & 1001 = 1001)
- 15 | 9 yields 15 (1111 | 1001 = 1111)
- 15 ^ 9 yields 6 (1111 ^ 1001 = 0110)
Bitwise Shift Operators
<< (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 are typically used with Boolean (logical) values; when they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value.| Operator | Usage |
Description
expr1 && expr2
| expr1 || expr2
| !expr (Logical NOT) Returns false if its single operand can be converted to true; otherwise, returns true. |
|---|
-
false&& anything is short-circuit evaluated to false. -
true|| anything is short-circuit evaluated to true.
Backward Compatibility
JavaScript 1.0 and 1.1. The && and || operators behave as follows:
| Operator |
Behavior
|
|
| |
|---|
Examples
The following code shows examples of the && (logical AND) operator.a1=true && true // t && t returns trueThe following code shows examples of the || (logical OR) operator.
a2=true && false // t && f returns false
a3=false && true // f && t returns false
a4=false && (3 == 4) // f && f returns false
a5="Cat" && "Dog" // t && t returns Dog
a6=false && "Cat" // f && t returns false
a7="Cat" && false // t && f returns false
o1=true || true // t || t returns trueThe following code shows examples of the ! (logical NOT) operator.
o2=false || true // f || t returns true
o3=true || false // t || f returns true
o4=false || (3 == 4) // f || f returns false
o5="Cat" || "Dog" // t || t returns Cat
o6=false || "Cat" // f || t returns Cat
o7="Cat" || false // t || f returns Cat
n1=!true // !t returns false
n2=!false // !f returns true
n3=!"Cat" // !t returns false
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".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 theif statement.Syntax
condition ? expr1 : expr2
Parameters
condition | |
expr1, expr2 |
Description
Ifcondition 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 evaluates both of its operands and returns the value of the second operand.Syntax
expr1, expr2
Parameters
expr1, expr2 |
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 afor 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=9; i <= 9; i++, j--)
document.writeln("a["+i+","+j+"]= " + a[i,j])
delete
The delete operator deletes an object, an object's property, or an element at a specified index in an array.Syntax
delete objectName
delete objectName.property
delete objectName[index]
delete property // legal only within a with statement
Parameters
objectName | |
property | |
index |
Description
The fourth form is legal only within awith statement, to delete a property from an object.
You can use the delete operator to delete variables declared implicitly but not those declared with the var statement.
If the delete operator succeeds, it sets the property or element to undefined. The delete operator returns true if the operation is possible; it returns false if the operation is not possible.
x=42Deleting array elements. When you delete an array element, the array length is not affected. For example, if you delete a[3], a[4] is still a[4] and a[3] is undefined. When the
var y= 43
myobj=new Number()
myobj.h=4 // create property h
delete x // returns true (can delete if declared implicitly)
delete y // returns false (cannot delete if declared with var)
delete Math.PI // returns false (cannot delete predefined properties)
delete myobj.h // returns true (can delete user-defined properties)
delete myobj // returns true (can delete objects)
delete operator removes an array element, that element is no longer in the array. In the following example, trees[3] is removed with delete.
trees=new Array("redwood","bay","cedar","oak","maple")If you want an array element to exist but have an undefined value, use the
delete trees[3]
if (3 in trees) {
// this does not get executed
}
undefined keyword instead of the delete operator. In the following example, trees[3] is assigned the value undefined, but the array element still exists:
trees=new Array("redwood","bay","cedar","oak","maple")
trees[3]=undefined
if (3 in trees) {
// this gets executed
}
new
The new operator creates an instance of a user-defined object type or of one of the built-in object types that has a constructor function.Syntax
objectName = new objectType (param1 [,param2] ...[,paramN])
Parameters
Description
Creating a user-defined object type requires two steps: 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 statementcar1.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 calledcar, 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) {Now you can create an object called
this.make = make
this.model = model
this.year = year
}
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) {And then instantiate two new
this.name = name
this.age = age
this.sex = sex
}
person objects as follows:
rand = new person("Rand McNally", 33, "M")Then you can rewrite the definition of
ken = new person("Ken Jones", 39, "M")
car to include an owner property that takes a person object, as follows:
function car(make, model, year, owner) {To instantiate the new objects, you then use the following:
this.make = make;
this.model = model;
this.year = year;
this.owner = owner;
}
car1 = new car("Eagle", "Talon TSi", 1993, rand);Instead of passing a literal string or integer value when creating the new objects, the above statements pass the objects
car2 = new car("Nissan", "300ZX", 1992, ken)
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
The this keyword refers to the current object. In general, in a methodthis refers to the calling object.Syntax
this[.propertyName]
Examples
Suppose a function calledvalidate validates an object's value property, given the object and the high and low values:
function validate(obj, lowval, hival) {You could call
if ((obj.value < lowval) || (obj.value > hival))
alert("Invalid Value!")
}
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
Thetypeof operator is used in either of the following ways:
1. typeof operandThe
2. typeof (operand)
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.var myFun = new Function("5+2")The
var shape="round"
var size=1
var today=new Date()
typeof operator returns the following results for these variables:
typeof myFun is objectFor the keywords
typeof shape is string
typeof size is number
typeof today is object
typeof dontExist is undefined
true and null, the typeof operator returns the following results:
typeof true is booleanFor a number or string, the
typeof null is object
typeof operator returns the following results:
typeof 62 is numberFor property values, the
typeof 'Hello world' is string
typeof operator returns the type of value the property contains:
typeof document.lastModified is stringFor methods and functions, the
typeof window.length is number
typeof Math.LN2 is number
typeof operator returns results as follows:
typeof blur is functionFor predefined objects, the
typeof eval is function
typeof parseInt is function
typeof shape.split is function
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. void (expression)The void operator specifies an expression to be evaluated without returning a value.
2. void expression
expression is a JavaScript expression to evaluate. The parentheses surrounding the expression are optional, but it is good style to use them.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>
Table of Contents | Previous | Next | Index
Last Updated: 05/28/99 12:01:14
