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:
operand1 operator operand2For example,
3+4
or x*y
.
A unary operator requires a single operand, either before or after the operator:
operator operandor
operand operatorFor example,
x++
or ++x
.
In addition, JavaScript has one ternary operator, the conditional operator. A ternary operator requires three operands.
Table 3.1 Assignment operators
Table 3.2 Comparison operators
1
These examples assume that var1 has been assigned the value 3 and var2 has been assigned the value 4.
|
1/2 //returns 0.5 in JavaScriptIn addition, JavaScript provides the arithmetic operators listed in the following table.
1/2 //returns 0 in Java
Table 3.3 Arithmetic Operators
Table 3.5 Bitwise shift operators
Operator | Description |
Example
|
| |
---|
Operator | Usage |
Description
expr1 && expr2
| expr1 || expr2
| !expr (Logical NOT) Returns false if its single operand can be converted to true; otherwise, returns true. |
---|
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
false
&& anything is short-circuit evaluated to false.true
|| anything is short-circuit evaluated to true."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
.
condition ? val1 : val2If
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
.
,
) 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 objectNamewhere
delete objectName.property
delete objectName[index]
delete property // legal only within a with statement
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=42
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 user-defined object)
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
}
in
operator returns true if the specified property is in the specified object. syntax is:
propNameOrNumber in objectNamewhere
propNameOrNumber
is a string or numeric expression representing a property name or array index, and objectName
is the name of an object.
The following examples show some uses of the in
operator.
// Arrays
trees=new Array("redwood","bay","cedar","oak","maple")
0 in trees // returns true
3 in trees // returns true
6 in trees // returns false
"bay" in trees // returns false (you must specify the index number,
// not the value at that index)
"length" in trees // returns true (length is an Array property)
// Predefined objects
"PI" in Math // returns true
myString=new String("coral")
"length" in myString // returns true
// Custom objects
mycar = {make:"Honda",model:"Accord",year:1998}
"make" in mycar // returns true
"model" in mycar // returns true
instanceof
operator returns true if the specified object is of the specified object type. Its syntax is:
objectName instanceof objectTypewhere
objectName
is the name of the object to compare to objectType
, and objectType
is an object type, such as Date or Array.
Use instanceof
when you need to confirm the type of an object at runtime. For example, when catching exceptions, you can branch to different exception-handling code depending on the type of exception thrown.
For example, the following code uses instanceof
to determine whether theDay
is a Date
object. Because theDay
is a Date
object, the statements in the if
statement execute.
theDay=new Date(1995, 12, 17)
if (theDay instanceof Date) {
// statements to execute
}
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 95. See
new
in the Core JavaScript Reference for more information.
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) {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>Example 2. When combined with the
<INPUT TYPE = "text" NAME = "age" SIZE = 3
onChange="validate(this, 18, 99)">
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
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.
Suppose you define the following variables:
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
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.
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 type |
Individual operators
, = += -= *= /= %= <<= >>= >>>= &= ^= |= ?: || && | ^ & == != < <= > >= in instanceof << >> >>> + - * / % ! ~ - + ++ -- typeof void delete () new . [] |
---|
Last Updated: 10/29/98 15:51:03