More on JavaScript Operators

Read this article to learn more about using operators in JavaScript. We will not use all of them in this introductory course. However, this is a condensed reference that contains tables of all operator categories. JavaScript categorizes operators by the task (such as arithmetic, comparison, or assignment). Operators execute in a particular order. This is called operator precedence and tells JavaScript which part to evaluate first, second, third, and so on. This is an important concept. 

For example, consider how a program calculates a price using arithmetic operators:

Multiplication first the result is: $18 = 4 + 2 * 7 ( 2 * 7 = 14 + 4)
Calculate left to right the result is: $42 = 4 + 2 * 7 (4+ 2 = 6 * 7)

Relational operators

A relational operator compares its operands and returns a Boolean value based on whether the comparison is true.


in

The in operator returns true if the specified property is in the specified object. The syntax is:

propNameOrNumber in objectName

where propNameOrNumber is a string, numeric, or symbol 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
var trees = ['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)

// built-in objects
'PI' in Math;          // returns true
var myString = new String('coral');
'length' in myString;  // returns true

// Custom objects
var mycar = { make: 'Honda', model: 'Accord', year: 1998 };
'make' in mycar;  // returns true
'model' in mycar; // returns true


instanceof

The instanceof operator returns true if the specified object is of the specified object type. The syntax is:

objectName instanceof objectType

where 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 ifstatement execute.

var theDay = new Date(1995, 12, 17);
if (theDay instanceof Date) {
  // statements to execute
}