Table 5.5
Logical operators
|
Operator
|
Usage
|
Description
|
|
&&
|
expr1 && expr2
|
(Logical AND) Returns
expr1
if it can be converted to false; otherwise,
returns expr2.
Thus, when used with Boolean values, &&
returns true if both operands are true;
otherwise, returns false.
|
|
||
|
expr1 || expr2
|
(Logical OR) Returns
expr1
if it can be converted to true; otherwise,
returns expr2.
Thus, when used with Boolean values, || returns
true if either operand is true; if both are
false, returns false.
|
|
!
|
!expr
|
(Logical NOT) Returns false if its
single operand can be converted to true; otherwise,
returns true.
|
Examples of expressions that can be
converted to false are those that evaluate to null, 0, the
empty string (""), or undefined.
Even though the && and ||
operators can be used with operands that are not Boolean
values, they can still be considered Boolean operators since
their return values can always be converted to Boolean
values.
Short-Circuit Evaluation.
As logical expressions are evaluated
left to right, they are tested for possible "short-circuit"
evaluation using the following rules:
-
-
false
&& anything is short-circuit evaluated to
false.
-
true ||
anything is short-circuit evaluated to true.
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.
Backward Compatibility
JavaScript 1.0 and 1.1.
The && and || operators behave
as follows:
|
Operator
|
Behavior
|
|
&&
|
If the first operand
(expr1)
can be converted to false, the &&
operator returns false rather than the value of
expr1.
|
|
||
|
If the first operand
(expr1)
can be converted to true, the || operator returns
true rather than the value of expr1.
|
Examples
The following code shows examples of the
&& (logical AND) operator.
a1=true && true
// t && t returns
true
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
The following code shows examples of the
|| (logical OR) operator.
o1=true || true
// t || t returns
true
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
The following code shows examples of the
! (logical NOT) operator.
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".
|
Implemented in
|
JavaScript 1.0
|
|
ECMA version
|
ECMA-262
|
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
|
JavaScript 1.0
|
|
ECMA version
|
ECMA-262
|
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 evaluates both of its
operands and returns the value of the second
operand.
|
Implemented in
|
JavaScript 1.0
|
|
ECMA version
|
ECMA-262
|
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=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.
|
Implemented in
|
JavaScript 1.2, NES 3.0
|
|
ECMA version
|
ECMA-262
|
Syntax
delete objectName
delete
objectName.property
delete
objectName[index]
delete property // legal only within a with statement
Parameters
|
objectName
|
The name of an object.
|
|
property
|
The property to delete.
|
|
index
|
An integer representing the array
index to delete.
|
Description
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
objects)
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]=undefined
if (3 in trees) {
// this gets executed
}
function
The function
operator defines an anonymous function inside an
expression.
|
Implemented in
|
JavaScript 1.5
|
Syntax
{var | const} variableName =
function(parameters) {functionBody};
Description
The following examples shows how the
function
operator is used.
This example declares an unnamed
function inside an expression. It sets x to a function that
returns the square of its argument:
var x = function(y) {return y*y};
The next example declares array a as an
array of three functions:
var a = [function(y) {return y}, function
y {return y*y}, function (y) [return y*y*y}];
For this array, a[0](5) returns 5,
a[1](5) returns 25, and a[2](5) returns 125.
in
The in operator
returns true if the specified property is in the specified
object.
|
Implemented in
|
JavaScript 1.4
|
Syntax
propNameOrNumber in
objectName
Parameters
|
propNameOrNumber
|
A string or numeric expression
representing a property name or array index.
|
|
objectName
|
Name of an object.
|
Description
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
You must specify an object on the right
side of the in operator.
For example, you can specify a string created with the
String
constructor, but you cannot specify a string literal.
color1=new String("green")
"length" in color1 // returns true
color2="coral"
"length" in color2 // generates an error (color is not a
String object)
Using in with deleted or undefined
properties.
If you delete a property with the
delete
operator, the in operator
returns false for that property.
mycar =
{make:"Honda",model:"Accord",year:1998}
delete mycar.make
"make" in mycar // returns false
trees=new
Array("redwood","bay","cedar","oak","maple")
delete trees[3]
3 in trees // returns false
If you set a property to undefined but
do not delete it, the in operator
returns true for that property.
mycar =
{make:"Honda",model:"Accord",year:1998}
mycar.make=undefined
"make" in mycar // returns true
trees=new
Array("redwood","bay","cedar","oak","maple")
trees[3]=undefined
3 in trees // returns true
For additional information about using
the in operator
with deleted array elements, see delete.
instanceof
The instanceof
operator returns true if the specified object is of the
specified object type.
|
Implemented in
|
JavaScript 1.4
|
Syntax
objectName instanceof
objectType
Parameters
|
objectName
|
Name of the object to compare to
objectType.
|
|
objectType
|
Object type.
|
Description
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.
You must specify an object on the right
side of the instanceof
operator. For example, you can specify a string created with
the String
constructor, but you cannot specify a string literal.
color1=new String("green")
color1 instanceof String // returns true
color2="coral"
color2 instanceof String // returns false (color is not a
String object)
Examples
See also the examples for throw.
Example 1. 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
}
Example 2. The following code
uses instanceof to
demonstrate that String and
Date
objects are also of type Object (they
are derived from Object).
myString=new String()
myDate=new Date()
myString instanceof String // returns
true
myString instanceof Object // returns true
myString instanceof Date // returns false
myDate instanceof
Date // returns true
myDate instanceof Object // returns
true
myDate instanceof String // returns false
Example 3. The following code
creates an object type Car and an
instance of that object type, mycar. The
instanceof
operator demonstrates that the mycar object is
of type Car and of type
Object.
function Car(make, model, year) {
this.make = make
this.model = model
this.year = year
}
mycar = new Car("Honda", "Accord", 1998)
a=mycar instanceof Car // returns true
b=mycar instanceof Object // returns true
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.
|
Implemented in
|
JavaScript 1.0
|
|
ECMA version
|
ECMA-262
|
Syntax
objectName = new objectType
(param1 [,param2] ...[,paramN])
Parameters
|
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:
-
-
Define the object type by writing a
function.
-
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
The this keyword refers to the current
object. In general, in a method this refers to
the calling object.
|
Implemented in
|
JavaScript 1.0
|
|
ECMA version
|
ECMA-262
|
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
|
JavaScript 1.1
|
|
ECMA version
|
ECMA-262
|
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. 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.
|
Implemented in
|
JavaScript 1.1
|
|
ECMA version
|
ECMA-262
|
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>