## Chapter 3 Expressions and Operators

This chapter describes JavaScript expressions and operators, including assignment, comparison, arithmetic, bitwise, logical, string, and special operators.

This chapter contains the following sections:

## Expressions

An expression is any valid set of literals, variables, operators, and expressions that evaluates to a single value; the value can be a number, a string, or a logical value.

Conceptually, there are two types of expressions: those that assign a value to a variable, and those that simply have a value. For example, the expression `x = 7` is an expression that assigns x the value seven. This expression itself evaluates to seven. Such expressions use assignment operators. On the other hand, the expression `3 + 4` simply evaluates to seven; it does not perform an assignment. The operators used in such expressions are referred to simply as operators.

JavaScript has the following types of expressions:

## Operators

JavaScript has the following types of operators. This section describes the operators and contains information about operator precedence.

JavaScript has both binary and unary operators. A binary operator requires two operands, one before the operator and one after the operator:

`operand1 operator operand2`
For example, `3+4` or `x*y`.

A unary operator requires a single operand, either before or after the operator:

`operator operand`
or

`operand operator`
For example, `x++` or `++x`.

In addition, JavaScript has one ternary operator, the conditional operator. A ternary operator requires three operands.

### Assignment Operators

An assignment operator assigns a value to its left operand based on the value of its right operand. 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 the following table.

Table 3.1 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. The operands can be numerical or string values. Strings are compared based on standard lexicographical ordering, using Unicode values. The following table describes the comparison operators.

### 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 most other programming languages, except the / operator returns a floating-point division in JavaScript, not a truncated division as it does in languages such as C or Java. For example:

`1/2 //returns 0.5 in JavaScript1/2 //returns 0 in Java`
In addition, JavaScript provides the arithmetic operators listed in the following table.

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

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

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.

The shift operators are listed in the following table.

### 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. The logical operators are described in the following table.

Examples of expressions that can be converted to false are those that evaluate to null, 0, the empty string (""), or undefined.

The following code shows examples of the && (logical AND) operator.

`a1=true && true       // t && t returns truea2=true && false      // t && f returns falsea3=false && true      // f && t returns falsea4=false && (3 == 4)  // f && f returns falsea5="Cat" && "Dog"     // t && t returns Doga6=false && "Cat"     // f && t returns falsea7="Cat" && false     // t && f returns false`
The following code shows examples of the || (logical OR) operator.

`o1=true || true       // t || t returns trueo2=false || true      // f || t returns trueo3=true || false      // t || f returns trueo4=false || (3 == 4)  // f || f returns falseo5="Cat" || "Dog"     // t || t returns Cato6=false || "Cat"     // f || t returns Cato7="Cat" || false     // t || f returns Cat`
The following code shows examples of the ! (logical NOT) operator.

`n1=!true              // !t returns falsen2=!false             // !f returns truen3=!"Cat"             // !t returns false`

#### 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"`.

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

JavaScript provides the following special operators:

#### conditional operator

The conditional operator is the only JavaScript operator that takes three operands. The operator can have one of two values based on a condition. The syntax is:

`condition ? val1 : val2`
If `condition` is true, the operator has the value of `val1`. Otherwise it has the value of `val2`. You can use the conditional operator anywhere you would use a standard operator.

For example,

`status = (age >= 18) ? "adult" : "minor"`
This statement assigns the value "adult" to the variable `status` if `age` is eighteen or more. Otherwise, it assigns the value "minor" to `status`.

#### 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 time through the 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. Its syntax is:

`delete objectNamedelete objectName.propertydelete objectName[index]delete property // legal only within a with statement`
where `objectName` is the name of an object, `property` is an existing property, and `index` is an integer representing the location of an element in an array.

The fourth form is legal only within a `with` 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=42var y= 43myobj=new Number()myobj.h=4      // create property hdelete 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 user-defined object)`
##### Deleting 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 `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")delete trees[3]if (3 in trees) {   // this does not get executed}`
If you want an array element to exist but have an undefined value, use the `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]=undefinedif (3 in trees) {   // this gets executed}`

#### 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 `Array`, `Boolean`, `Date`, `Function`, `Image`, `Number`, `Object`, `Option`, `RegExp`, or `String`. On the server, you can also use it with `DbPool`, `Lock`, `File`, or `SendMail`. Use `new` as follows:

`objectName = new objectType ( param1 [,param2] ...[,paramN] )`
You can also create objects using object initializers, as described in "Using Object Initializers" on page 101.

See `new` in the Client-Side JavaScript Reference for more information.

#### this

Use the `this` keyword to refer to the current object. In general, `this` refers to the calling object in a method. Use `this` as follows:

`this[.propertyName]`
Example 1. 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)">`
Example 2. When combined with the `form` property, `this` can refer to the current object's parent form. In the following example, the form `myForm` contains a `Text` object and a button. When the user clicks the button, the value of the `Text` object is set to the form's name. The button's `onClick` event handler uses `this.form` to refer to the parent form, `myForm`.

`<FORM NAME="myForm">Form name:<INPUT TYPE="text" NAME="text1" VALUE="Beluga"><P><INPUT NAME="button1" TYPE="button" VALUE="Show Form Name"   onClick="this.form.text1.value=this.form.name"></FORM>`

#### typeof

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

`1. typeof operand2. 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.

Suppose you define the following variables:

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

`typeof myFun is objecttypeof shape is stringtypeof size is numbertypeof today is objecttypeof dontExist is undefined`
For the keywords `true` and `null`, the `typeof` operator returns the following results:

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

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

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

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

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

#### void

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

`1. void (expression)2. 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.

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

### Operator Precedence

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

The following table describes the precedence of operators, from lowest to highest.

Table 3.7 Operator precedence
Operator type Individual operators

comma

`,`

assignment

`= += -= *= /= %= <<= >>= >>>= &= ^= |=`

conditional

`?:`

logical-or

`||`

logical-and

`&&`

bitwise-or

`|`

bitwise-xor

`^`

bitwise-and

`&`

equality

`== !=`

relational

`< <= > >=`

bitwise shift

`<< >> >>>`

`+ -`

multiply/divide

`* / %`

negation/increment

`! ~ - + ++ -- typeof void delete`

call

`()`

create instance

`new`

member

`. []`