Categories:

JavaScript Kit > JavaScript Reference > JavaScript Operators: Other

Other Operators

Last updated: May 5th, 2009

Below lists the other JavaScript Operators available.

Also See: JavaScript Operators precedence and associativity.

Other Operators

Operator Description
(,) comma Primarily used in a for loop when you wish to insert multiple expressions for the test conditions, the comma (,) operator evaluates its left and right operands, and returns the value of the right.

for (var i=0, y=0; i<5; i++, y+=2){
 document.write(i+" "+y+"<br />")
}

Output:

?: The Conditional Operator (?:) is a shorthand method for returning the result of either exp1 or exp2, depending on whether condition evaluates to true or false. If true, the value of exp1 is returned, or if false, the value of exp2 instead.

(condition)? exp1 : exp2

For example:

y=-1
x=(y<0)? 5: 10 //x contains 5

Mor example(s).

delete Deletes a variable defined not using "var", custom object property, method, or array element. It returns true if successful, false if not. For example:

var myarray=['joe', 'mary', 'jane']
var boss={name: 'george'}
worker={name: 'peter'}
var x=3
y=4

delete myarray[1] //returns true, myarray[1] now undefined
delete boss //returns false, since boss is a declared variable
delete worker //returns true, since worker is an undeclared variable
delete x //returns false, since x is a declared variable
delete y //returns true, since y is an undeclared variable

in The "in" operator takes an object or array as its right operand, and a string denoting the property you wish to search for as its left operand. Returns true if property exists in object, false if not.

var myarray=['joe', 'mary', 'jane']
var workers={worker1: 'peter', worker2: 'edward', worker3: 'john'}

"lastModified" in document //true, document.lastModified exists
"length" in myarray //true
"mary" in myarray //false, "mary" is an array value, not property (use array.indexOf() instead)
"worker1" in workers //true

Note that properties deleted using the "delete" operator above will return false when tested for using "in".

instanceof Returns a Boolean value indicating whether the left hand operand is of the object type specified in the right hand operand. Here object type refers to the name of the object you wish to test for, such as Date, String, Array etc. Use instanceof as a more clear-cut way of detecting the type of an object or variable versus typeof. For example:

var today=new Date()
alert(today instanceof Date) //alerts true, today is a Date object

var mycars=["Honda", "Toyota", "Ford"
alert(mycars instanceof Array) //alerts true, mycars is an Array object

function house(w, h){
this.area=w*h
}
var myhouse=new house(100, 200)
alert(myhouse instanceof house) //alerts true

new Creates a new instance of a custom or select built-in JavaScript objects such as Date. Only objects with a constructor function can be instantialized using the "new" operator. The "this" keyword can then be used anywhere inside the function to refer to the object or object instance.

var today=new Date() //create new instance of Date object

function triangle(base, height){
 this.area=base*height/2
}
var bigtriangle=new triangle(200, 150) //create new instance of triangle object

try/catch/finally Allows you to intercept exception (aka runtime) errors in JavaScript and handle them as you see fit. Examples of exceptions include trying to reference an undefined variable, or calling a non existent JavaScript method. It does not catch syntax errors (ie: forgetting to end a string with a quotation mark). The typical set up involves a try and catch clause to catch a possible exception, and react accordingly if caught:

try{
 somefunction()
 alert('I guess you do exist')
}
catch(e){
 alert('An error has occurred: '+e.message)
}

In the above, if "somefunction()" doesn't exist, the browser immediately skips the reminder of what's inside try() and executes the code inside catch().

There's another clause, finally, that if defined will be executed regardless of whether an error occurs in the try clause:

try{
 undefinedfunction()
 alert('I guess you do exist')
}
catch(e){
 alert('An error has occurred: '+e.message)
}
finally{
 alert('I am alerted regardless of the outcome above')
}

try should never be defined just by itself, but always followed by either catch, finally, or both. Within each clause, you can define additional try/catch/finally statements following the same aforementioned rule (nesting). Take the instance where an error has occurred within the catch clause- defining an additional try/catch statement inside it takes care of it:

var ajaxrequest=null
if (window.ActiveXObject){ //Test for support for different versions of ActiveXObject in IE
 try {
  ajaxrequest=new ActiveXObject("Msxml2.XMLHTTP")
 }
 catch (e){
  try{
   ajaxrequest=new ActiveXObject("Microsoft.XMLHTTP")
  } //end inner try
  catch (e){
   alert("I give up. Your IE doesn't support Ajax!")
  } //end inner catch

 } //end outer catch
}
else if (window.XMLHttpRequest) // if Mozilla, Safari etc
 ajaxrequest=new XMLHttpRequest()

ajaxrequest.open('GET', 'process.php', true) //do something with request

Here I'm using a nested try/catch statement to try and determine in IE which version of the ActiveX Object it supports that's needed to initialize an Ajax request. Using object detection won't work here, since the issue isn't whether the browser supports ActiveXObject here, but which version.

More info: "Handling runtime errors in JavaScript using try/catch/finally".

typeof The "typeof" operator allows you to probe the data type of its operand, such as whether a variable is string, numeric, or even undefined. Here are some of the possible return values:
Evaluates to Indicates
"number" Operand is a number. Example:
  • typeof 0 //number
"string" Operand is a string.
"boolean" Operand is a Boolean. Examples:
  • typeof false //boolean
"object" Operand is an object. Note that apart from most core and user defined objects, arrays and null itself also evaluates to "object" in typeof. Examples:
  • typeof window //object
  • typeof Math //object
  • typeof new Array() //object
  • typeof null //object
"function" Operand is a function. JavaScript core methods, custom functions, and even some core objects return "function" as their type. Examples:
  • typeof alert//function (window.alert())
  • typeof Date //function
  • typeof new Function("var x=3") //function
  • typeof document.getElementById //function
null Operand is null.
"undefined" Operand is not defined. Undefined properties or non existent variables all return "undefined" as their type. The following tests whether a variable exists, by checking if its data type is "undefined":

if (typeof x=="undefined")
alert("x doesn't exist!")


 

void Evaluates a lone operand without returning a value. Most commonly used to define JavaScript links, where the link executes a JavaScript code instead of its default action when clicked on. For example:

<a href="javascript:void(window.open('http://google.com'))">Open Google</a>

Example- Conditional Operator

The Conditional Operator is handy for quickly assigning a different value to a variable depending on the outcome of a condition. Here are a few examples:

var browser=(navigator.appName.indexOf("Microsoft")!=-1)? "IE" : "Non IE"

You can expand the number of possible values to assign to more than just two. In fact, there is no limit. Observe the below example, which has 3 possible values:

var browser=(navigator.appName.indexOf("Microsoft")!=-1)? "IE" : (navigator.appName.indexOf("Netscape")? "NS" : "Not IE nor NS"

In the 2nd example, "browser" will contain one of 3 possible values depending on the browser maker of the visitor.

You can use a conditional operator within a larger expression, by wrapping the entire conditional operator with a parenthesis:

document.write("The total for your order is "+(onsale==true? "$25" : "$30"))


Reference List

Right column

CopyRight (c) 2018 JavaScript Kit. NO PART may be reproduced without author's permission. Contact Info