JavaScript Operators
Overview
In computer programming, an operator is (usually) a symbol or a word that represents some action to be performed on one or more operands. You should attempt to become familiar with the range of JavaScript operators that are available, and how they work, before writing any serious code. Consider the following statement:
y = x * 7;
In this statement, we have three operands - the variables x and y, and the numeric literal 7. We also have two operators - the assignment operator (=) and the multiplication operator (*). The multiplication operator multiplies the value of x by 7, and the assignment operator assigns the result of that multiplication operation to the variable y.
As with other programming languages, it is JavaScript's operators that allow it to manipulate primitive and complex data types in order to achieve the functionality required of a script or program. Those operators can be broadly categorised into the following groups:
- Arithmetic operators - used to perform arithmetic operations on numeric operands. Examples include addition, subtraction, multiplication and division.
- Relational operators - sometimes called comparison operators. Used to test the relationship between two operands. Examples include the equality, less than and greater than operators. Typically used to compare numeric values or strings.
- Logical operators - these are the logical AND, logical OR and logical NOT operators that return a Boolean (true or false) value, depending on whether the operands to which they are applied evaluate to true or false.
- Bitwise operators - these operators, as their name suggests, are used to compare or manipulate the operands to which they are applied on a bit-by-bit basis.
- Assignment operators - an assignment operator assigns a value to the operand on its left based on the value of the operand on its right. The basic assignment operator simply assigns the value of the right-hand operand to the left-hand operand. Other assignment operators are compound operators that combine the assignment operator with another (binary) operator. The operation signified by the binary operator is applied to both operands, and the result is assigned to the left-hand operand.
- The ternary operator - also known as the conditional operator. The value assigned to an operand by the ternary operator will depend on whether some condition is true or false.
- String operators - there are two string operators in JavaScript (+ and +=), both of which are used to concatenate (join together) two strings. These operators are also both arithmetic operators; JavaScript will determine which role they will undertake based on the context in which they are used.
- Other operators – there are a number of other operators that do not fit neatly into any of the above categories, but which are nevertheless very useful on occasion. These include the typeof operator, the comma operator, the delete operator, the in operator, and the instanceof operator.
The following sections will list the JavaScript operands currently available in each of the categories listed above, and give a brief example of their use. Don't attempt to memorise the functionality of all of the operators listed here, but do have a quick scan through them so that you have an idea of what is available. You can always revisit this page if you are looking for an operator to do a specific job.
Arithmetic operators
Arithmetic operators are symbols that represent various arithmetical operations, such as addition, subtraction, multiplication and division. An arithmetic operator takes either one or two numeric values as its arguments depending on whether it is a unary or a binary operator, and returns a single numeric value. The operands can be either literal values or variables.
Note that some unary operators can be used as either prefix operators (operators that appear immediately before their operand) or as postfix operators (operators that appear immediately after their operand). The value returned by a prefix operator is the value of its operand after the operation is applied to it, whereas the value returned by a postfix operator is the value of the operand before the operation is applied to it.
The following table lists JavaScript's arithmetic operators, and provides examples of their use.
Operator | Description |
---|---|
+ | Addition operator - a binary operator that adds the values of two numeric operands together. For example:
x = 7; |
- | Subtraction operator - a binary operator that subtracts the value of the right-hand operand from that of the left-hand operator. For example:
x = 8; |
* | Multiplication operator - a binary operator that multiplies the values of two numeric operands together. For example:
x = 3; |
/ | Division operator - a binary operator that divides the value of the left-hand operand by that of the right-hand operator. For example:
x = 24; |
% | Modulo operator - a binary operator that divides the value of the left-hand operand by that of the right-hand operator and returns the remainder. For example:
x = 17; |
++ | Increment operator - a unary operator that increases the value of its operand by one. Note that if used as a prefix operator, ++ returns the value of its operand after incrementing it; if used as a postfix operator, ++ returns the value of its operand before incrementing it. For example:
x = 5; |
-- | Decrement operator - a unary operator that decreases the value of its operand by one. Note that if used as a prefix operator, -- returns the value of its operand after decrementing it; if used as a postfix operator, -- returns the value of its operand before decrementing it. For example:
x = 9; |
** | Exponentiation operator - a relatively new binary operator (introduced with ECMAScript 2016) that returns the result of raising the value of the left-hand operand to the power of the value of the right-hand operand. For example:
x = 2 ** 3; // the value of x is 8 |
+ | Unary plus operator - the unary plus operator has the same symbol as the binary plus operator, but is applied to a single operand. If applied to a number it has no effect, but when applied to a non-numeric operand, it attempts to convert it to a number. For example:
let x = "5", y = "10", z = "Cat"; In the final document.write() statement, the unary plus operator has again been applied to both operands. This time, however, the second operand is z, a string value that will not convert to a number. Instead, the unary plus returns the value NaN (Not a Number) which, when added to a numeric value, will also produce the result NaN. |
Assignment operators
The assignment operator is a binary operator that assign a value to the operand on its left based on the value of the operand to its right (note that the right-hand operand may be an expression in its own right). The basic assignment operator simply assigns the value of the right-hand operand to the left-hand operand, but JavaScript also has a number of compound assignment operators that combine the assignment operator with another (binary) operator.
The operation signified by the binary operator is applied to both operands, and the result is then assigned to the left-hand operand. The compound assignment operators offer a shorthand way of writing program statements. For example, the following statements are equivalent; both of them increment the value of the variable x by 4:
x += 4;
x = x + 4;
The table below lists JavaScript's assignment operators, and provides examples of their use.
Operator | Description |
---|---|
= | Basic assignment operator - assigns the value of the right-hand operand to the left hand operand. For example:
x = 10; // the value of x is 10 |
+= | Addition assignment operator - adds together the values of the left- and right-hand operands, and then assigns the result to the left-hand operand. For example:
x += 10; // equivalent to: x = x + 10; |
-= | Subtraction assignment operator - subtracts the value of the right-hand operand from the value of the left-hand operand, and then assigns the result to the left-hand operand. For example:
x -= 5; // equivalent to: x = x - 5; |
*= | Multiplication assignment operator – multiplies the values of the left-and right-hand operands together, and then assigns the result to the left-hand operand. For example:
x *= 6; // equivalent to: x = x * 6; |
/= | Division assignment operator - divides the value of the left-hand operand by the value of right-hand operand, and then assigns the result to the left-hand operand. For example:
x /= 3; // equivalent to: x = x / 3; |
%= | Modulo assignment operator - divides the value of the left-hand operand by the value of right-hand operand, and then assigns the remainder to the left-hand operand. For example:
x %= 7; // equivalent to: x = x % 7; |
**= | Exponentiation assignment operator - raises the value of the left-hand operand to the power of the value of the right-hand operand, and then assigns the result to the left-hand operand. For example:
x **= 2; // equivalent to: x = x ** 2; |
<<= | Left shift assignment operator - left-shifts the bits in the left-hand operator by the number of places signified by the right-hand operand, and assigns the result to the left-hand operand. For example:
x <<= 2; // equivalent to: x = x << 2; |
>>= | Right shift assignment operator - right-shifts the bits in the left-hand operator by the number of places signified by the right-hand operand, and assigns the result to the left-hand operand. For example:
x >>= 4; // equivalent to: x = x >> 4; |
>>>= | Unsigned right shift assignment operator - right-shifts the bits in the left-hand operator by the number of places signified by the right-hand operand, and assigns the result to the left-hand operand (bits shifted right from the most significant position are replaced with zeros). For example:
x >>>= 3; // equivalent to: x = x >>> 3; |
&= | Bitwise AND assignment operator - performs a bitwise AND of the operands and assigns the result to the left-hand operand. For example:
x &= y; // equivalent to: x = x & y; |
^= | Bitwise XOR assignment operator – performs a bitwise Exclusive OR of the operands and assigns the result to the left-hand operand. For example:
x ^= y; // equivalent to: x = x ^ y; |
|= | Bitwise OR assignment operator - performs a bitwise OR of the operands and assigns the result to the left-hand operand. For example:
x |= y; // equivalent to: x = x | y; |
Relational operators
Relational operators, also known as comparison operators, are binary operators that compare two operands and return a Boolean value (true or false) based on the result of the comparison. The operands can be numbers, strings, Boolean values or objects.
If the operands are of different types, JavaScript will normally try to convert one or both of them to an appropriate type to enable comparison (this usually involves converting a string value to a numeric value), except in the case of the strict equality and inequality operators (=== and !==) which compare the types of each operand as well as their values, and don't attempt to convert the operands to compatible types.
The table below lists JavaScript's relational operators, and provides examples of their use.
Operator | Description |
---|---|
== | Equality operator - compares the equality of two operands, without considering type; returns true if they are equal. For example:
let x = 5, y = 10, z = "5"; |
=== | Equality operator (strict) – compares the equality of two operands, including checking to see if they are of the same type; returns true if they are equal. For example:
let x = 3, y = 7, z = "3"; |
!= | Inequality operator – compares the equality of two operands, without considering type; returns true if they are not equal. For example:
let x = 5, y = 10, z = "5"; |
!== | Inequality operator (strict) – compares the equality of two operands, including checking to see if they are of the same type; returns true if they are not equal, or if they are of different types. For example:
let x = 4, y = 7, z = "4"; |
> | Greater than operator - compares the values of the operands, and returns true if the value of the left-hand operand is greater than the value of the right-hand operand. For example:
let x = 3, y = 5, z = "3"; |
< | Less than operator - compares the values of the operands, and returns true if the value of the left-hand operand is less than the value of the right-hand operand. For example:
let x = 6, y = 8, z = "6"; |
>= | Greater than or equal to operator - compares the values of the operands, and returns true if the value of the left-hand operand is greater than or equal to the value of the right-hand operand. For example:
let x = 7, y = 9, z = "7"; |
<= | Less than or equal to operator - compares the values of the operands, and returns true if the value of the left-hand operand is less than or equal to the value of the right-hand operand. For example:
let x = 2, y = 5, z = "2"; |
Logical operators
Logical operators, sometimes called Boolean operators, return a Boolean value (true or false) when used with Boolean values. However, they are frequently used with non-Boolean expressions that evaluate to either true or false, in which case the return value may be something other than a Boolean value.
Note that JavaScript treats several values as false in addition to the Boolean value false: the number zero (0); the value null; the empty string (""); and the special numeric values NaN (Not a Number) and undefined. All other values are treated as being true, including both negative and positive numbers, non-empty strings, and objects.
Note that values that are not Boolean values (true or false) in their own right, but that are nevertheless evaluated as being either true or false, are commonly referred to as "truthy" values (if they evaluate to true) and "falsey" values if they evaluate to false (seriously - we're not joking).
There are three logical operators: the binary logical AND operator (&&), the binary logical OR operator (||), and the unary logical NOT operator (!). The return value of the two binary operators (&& and ||) is equal to that of the last operand that is actually evaluated. Consequently, the && operator is sometimes known as the guard operator, and the || operator is sometimes known as the default operator. The NOT operator (!) essentially just negates whatever Boolean value its operand evaluates to.
The table below lists JavaScript's logical operators, and provides examples of their use.
Operator | Description |
---|---|
&& | Logical AND operator - compares two operands. If the first operand evaluates to false, the value of that operand will be returned and the value of the second operand is not evaluated. Otherwise the value of the second operand will be returned. For example:
let x = 3, y = 6; |
|| | Logical OR operator - compares two operands. If the first operand evaluates to true, the value of that operand is returned and the value of the second operand is not evaluated. Otherwise the value of the second operand will be returned. For example:
let x = 7, y = 5; |
! | Logical NOT operator - returns false if its operand evaluates to true. Otherwise, it returns true. For example:
let x = 2, y = 3; |
Bitwise operators
Bitwise operators, as the name suggests, are used to manipulate the bits of a number, regardless of the base to which that number is expressed; they work in exactly the same way on decimal, hexadecimal, octal, or binary numbers. JavaScript bitwise operators work on 32-bit integers, so any numeric values involved in a bitwise operation are first converted to 32-bit integers (for floating-point numbers this means that the mantissa is discarded), and then converted back to their original format once the operation is complete.
For numbers with more than 32 bits, only the 32 least significant bits (i.e. the right-most 32 bits) are taken into account - the rest are ignored. This effectively means that the application of bitwise operations is limited to signed 32-bit integer values in the range -2,147,483,648 (-2^{31}) to 2,147,483,647 (2^{31} - 1). The table below lists JavaScript's bitwise operators, and provides examples of their use. Note that, for the sake of clarity, the examples use 8-bit rather than 32-bit values to demonstrate the effect of applying a bitwise operator.
Operator | Description |
---|---|
& | Bitwise AND operator - compares each bit in the right-hand operand with the corresponding bit in the left-hand operand. If both bits are one, a one is returned in the corresponding position in the result. Otherwise a zero will be returned in that position. A bitwise AND is sometimes used to "mask" certain bits of a number, leaving only the bits we are interested in. For example:
200 & 240 // returns 192 |
| | Bitwise OR operator - compares each bit in the right-hand operand with the corresponding bit in the left-hand operand. If both bits are zero, a zero is returned in the corresponding position in the result. Otherwise, a one will be returned in that position. the bitwise OR can be used to make sure that certain bits in a sequence are turned on. For example:
200 | 15 // returns 207 |
~ | Bitwise NOT operator - a unary bitwise operator that inverts the bits of its operand, essentially returning the one's complement of the original number. For example:
~200 // returns -201 |
^ | Bitwise Exclusive OR operator - compares each bit in the right-hand operand with the corresponding bit in the left-hand operand. If both bits are the same (i.e. both ones or both zeros), a zero is returned in the corresponding position in the result. Otherwise, a one will be returned in that position. For example:
200 ^ 240 // returns 56 |
<< | Bitwise left-shift operator - left-shifts the bits in the left-hand operator by the number of places signified by the right-hand operand. For example:
30 << 3 // returns 240 |
>> | Bitwise right-shift operator - right-shifts the bits in the left-hand operator by the number of places signified by the right-hand operand. For example:
-123 >> 3 // returns -25 |
>>> | Bitwise zero-fill right-shift operator - right-shifts the bits in the left-hand operator by the number of places signified by the right-hand operand. For example:
123 >>> 3 // returns 15 Right-shifting a positive operand with the zero-fill right-shift operator is the same as dividing the operand by 2^{n}, where n is the number of places by which the number is shifted (any significant bits lost in the process represent a fractional component of the result, which is effectively rounded down to the nearest integer value). Using the zero-fill right-shift operator to right-shift negative integer values produces very different results. For example, right shifting the 32-bit version of -123 by three places using the zero-fill right-shift operator produces a result of 536,870,896, as follows:
// 1111 1111 1111 1111 1111 1111 1000 0101 |
The ternary operator
The ternary operator (sometimes called the conditional operator) assigns a value to a variable depending on whether some condition is true or false. The ternary operator is unique in that it is represented by two distinct symbols (? and :) and has three operands. The first operand is the conditional expression to be evaluated, and is followed by the interrogation point (?), more commonly known as a question mark.
The second and third operands follow the interrogation point and are separated by a colon (:). They represent two alternative values, only one of which will be returned, depending on whether the left-hand operand evaluates to true or false. If the left-hand operand evaluates to true, then the value of the operand to the left of the colon will be returned. Otherwise, the value of the operand to the right of the colon is returned.
The syntax of the ternary operator is as follows:
<condition> ? <value1> : <value2>;
The ternary operator is essentially a shorthand way of writing an if-else statement (we will be looking at if-else and other program flow control structures on a separate page). Consider the following code:
let x = 10, y = 5, z = 0;
if (x < y) {
z = x;
}
else {
z = y;
}
We can write the same code much more concisely using the ternary operator:
let x = 10, y = 5, z = 0;
z = (x < y) ? x : y;
Clearly, the ternary operator can reduce the amount of code you have to write, but its use inevitable involves a trade-off between highly compact code that will download quickly and readable code that is easy to maintain. You will often encounter the ternary operator in JavaScript libraries, where minimal file size is desirable in order to reduce download times. In most cases, you should try to write code that is easy to read and maintain.
String operators
The JavaScript string operators are used to concatenate (join together) two strings. The basic string concatenation operator also doubles up as the arithmetic addition operator; the role assigned to it by JavaScript in a particular case will be determined by the context in which it is used. This can lead to some interesting situations, but let's start with an example for which the operands are all unambiguously string values. Consider the following code:
let firstName = "John", lastName = "Smith";
let greeting = "Good morning, " + firstName + " " + lastName + "!";
document.write(greeting); // outputs "Good morning, John Smith!"
As you can see from the code, the concatenation operator is used here to build the string "Good morning, John Smith!" from five separate string elements and assign it to the variable greeting. There is also a string concatenation assignment operator that, like its basic counterpart, doubles up as an arithmetic operator - namely the addition assignment operator. Once again, JavaScript will determine which role is being invoked based on the context in which it is used. Consider this example:
let customerName = "John Smith";
let invoiceTo = "Customer name: ";
invoiceTo += customerName;
document.write(invoiceTo); // outputs "Customer name: John Smith"
We said above that JavaScript will determine whether the operation performed is string concatenation or arithmetic addition based on the context. What happens, for example, when we have two operands, one of which is a string and the other a number? Consider this code:
let x = "10", y = 5;
let sum = x + y;
document.write(sum); // outputs "105"
Clearly, adding a number and a string together will result in the number being converted to a string, after which the two strings will be concatenated. Things are not always quite so straightforward, however. Look at this code:
let x = "10", y = 5, z = 2;
let sum = x + y + z;
document.write(sum); // outputs "1052"
This result is probably what you would expect to see. But now consider this code:
let x = "10", y = 5, z = 2;
let sum = y + z + x;
document.write(sum); // outputs "710"
In this case, even though one of the operands in the expression to the right of the assignment operator is a string, JavaScript has determined that the first plus sign takes on the role of the arithmetic addition operator rather than that of the string concatenation operator. This is due to rules of precedence which state that multiple operations involving the same operator are carried out in strict order, from left to right.
Because the first two operands in this case are both numbers, they are treated as such and added together. Note that, if the first operation results in a string, adding several numbers to that result will also result in a string:
let x = "10";
let sum = x + 1 + 2 + 3 + 4 + 5;
document.write(sum); // outputs "1012345"
The typeof operator
The typeof operator is a unary operator that returns a string indicating the type of the operand to which it is applied. The operand itself appears after the typeof operator, and can be of any type. It can also be an expression. The typeof operator is useful on occasion, such as when you wish to validate function parameters, or check that a variable has been defined. The code below demonstrates how the typeof operator is used, and the values returned for various types of operand.
let x = 5, myStr = "Hello!", myBool = true, y;
const PI = 3.14159265359;
let myFunction = new Function('3 * 4');
let myObject = {firstName: "John", lastName: "Smith"}
let myArray = ['Cat', 'Dog', 'Rabbit'];
let myDate = new Date();
document.write("x is of type: " + typeof x + "<br>"); // outputs "number"
document.write("y is of type: " + typeof y + "<br>"); // outputs "undefined"
document.write("myStr is of type: " + typeof myStr + "<br>"); // outputs "string"
document.write("myBool is of type: " + typeof myBool + "<br>"); // outputs "boolean"
document.write("(x == y) is of type: " + typeof (x == y) + "<br>"); // outputs "boolean"
document.write("PI is of type: " + typeof PI + "<br>"); // outputs "number"
document.write("myFunction is of type: " + typeof myFunction + "<br>"); // outputs "function"
document.write("myObject is of type: " + typeof myObject + "<br>"); // outputs "object"
document.write("myArray is of type: " + typeof myArray + "<br>"); // outputs "object"
document.write("myDate is of type: " + typeof myDate + "<br>"); // outputs "object"
document.write("nonExistentVar is of type: " + typeof nonExistentVar + "<br>"); // outputs "undefined"
document.write("NaN is of type: " + typeof NaN + "<br>"); // outputs "number"
document.write("Infinity is of type: " + typeof Infinity + "<br>"); // outputs "number"
document.write("null is of type: " + typeof null + "<br>"); // outputs "object"
document.write("undefined is of type: " + typeof undefined + "<br>"); // outputs "undefined"
document.write("Date is of type: " + typeof Date + "<br>"); // outputs "function"
document.write("Function is of type: " + typeof Function + "<br>"); // outputs "function"
document.write("Math is of type: " + typeof Math + "<br>"); // outputs "object"
document.write("Boolean is of type: " + typeof Boolean + "<br>"); // outputs "function"
document.write("String is of type: " + typeof String + "<br>"); // outputs "function"
Note that the data type returned for user-defined dates and arrays is object. Note also that the data types returned for Date, Function, Boolean and String is function, whereas the data type returned for Math is object. This is due to the fact that Math is a namespace that acts as a container for a number of math functions; it is not a constructor, and does not create other objects. All of the others (Date, Function, Boolean and String) are constructor functions that are used explicitly to create objects of the type they represent.
The typeof operator is useful because it is an easy way to check the type of a variable in your code. This is important because JavaScript is a is a dynamically typed language. This means that you aren't required to assign types to variables when you create them. Because a variable is not restricted in this way, its type can change during the runtime of a program.
The comma operator
The comma operator (,) allows multiple expressions to be evaluated as a single statement. Each expression is evaluated in turn, from left to right, but only the value of the last expressions is returned. You can use the comma operator in situations where you want to include multiple expressions in a location that requires a single expression. Commonly used to supply multiple arguments in a for loop. For example:
let digits = [1,2,3,4,5,6,7,8,9,0];
let chars = "A","B","C","D","E","F","G","H","I","J"];
for (let i = 0, j = 0; i < digits.length; i++, j++) {
document.write(digits[i] + " = " + chars[j] + "<br>");
}
/*
Outputs:
1=A
2=B
3=C
4=D
5=E
6=F
7=G
8=H
9=I
0=J
*/
In the above example, use of the comma operator allows the variables i and j to be updated during each iteration of the for loop. The comma operator can be used to write very compact code, but it can also make your code somewhat obscure and thus less easy to read and maintain. We would suggest that, unless you have to use it for some reason (other than for loops), its use should be avoided.
The delete operator
The delete operator is used to delete a specific property of an object or an individual array element. The syntax of the delete operator is as follows:
delete objectName.property;
delete objectName[index];
The following example demonstrates the effect of deleting an object property:
let Person = {
firstName:"John",
lastName:"Smith"
};
document.write(Person.firstName + " " + Person.lastName + "<br>"); // outputs "John Smith"
delete Person.firstName;
document.write(Person.firstName + " " + Person.lastName + "<br>"); // outputs "undefined Smith"
let myArray = ['Cat', 'Dog', 'Rabbit'];
for (let i = 0; i < myArray.length; i++) {
document.write(myArray[i] + " ");
} // outputs "Cat Dog Rabbit"
document.write("<br>");
delete myArray[1];
for (let i = 0; i < myArray.length; i++) {
document.write(myArray[i] + " ");
} // outputs "Cat undefined Rabbit"
If the delete operator is applied to an object property, both the value of the property and the property itself are deleted from the object. Attempts to access a deleted object property will return a value of undefined. If the delete operator is applied to an array element, the array element is deleted but the length of the array is not affected and the array is not re-indexed (an attempt to address the array element returns a value of undefined).
Note that there is a subtle difference between deleting an array element using the delete operator and assigning a value of undefined to that array element. In both cases, an attempt to address the array element in question will return a value of undefined, but if the array element has been deleted, then to all intents and purposes it no longer exists:
let myArray = ['Cat', undefined, 'Rabbit'];
document.write((1 in myArray) + "<br>"); // outputs true
delete myArray[1];
document.write((1 in myArray) + "<br>"); // outputs false
If a delete operation is successful, it will return a value of true, otherwise it will return a value of false; any attempt to delete a variable declared with let or var will fail, and will return a value of false. Deleting an implicitly declared variable, on the other hand, will succeed. Note that you should never attempt to use the delete operator to delete a property of one of JavaScript's pre-defined objects, as this may have unforeseen consequences.
The in operator
The in operator can be used to check whether or not an array element exists, or whether an object has a specified property. The in operator returns true if the array element or property exists and false otherwise. For example:
let Person = {
firstName:"John",
lastName:"Smith"
};
document.write(("firstName" in Person) + "<br>"); // outputs true
document.write(("age" in Person) + "<br>"); // outputs false
let myArray = ['Cat', 'Dog', 'Rabbit'];
document.write((1 in myArray) + "<br>"); // outputs true
document.write((3 in myArray) + "<br>"); // outputs false
Note that when checking for the presence of an object property, you should use the name of the property in quotes; when checking for an array element, use the index number. Note also that the in operator works equally well on JavaScript's pre-defined objects, as the following code shows:
document.write(("PI" in Math) + "<br>"); // outputs true
document.write(("NaN" in Number) + "<br>"); // outputs true
document.write(("length" in String) + "<br>"); // outputs true
document.write(("hugeNumber" in Math) + "<br>"); // outputs false
The instanceof operator
The instanceof operator enables you to check whether or not an object is an instance of a user-defined object, or of one of the pre-defined object types that has a constructor function. The instanceof operator returns true if the object is an instance of the specified type; otherwise it returns false. The syntax is as follows:
objectName instanceof objectType
where objectName is the name of the object whose type we want to check, and objectType is the name of an object's constructor function, such as Array or Date. The following code demonstrates how the instanceof operator is used:
let Person = {
firstName:"John",
lastName:"Smith"
};
let myArray = ['Cat', 'Dog', 'Rabbit'];
var birthday = new Date(1955, 2, 25);
let x = new Number;
document.write((Person instanceof Object) + "<br>"); // outputs true
document.write((Person instanceof Array) + "<br>"); // outputs false
document.write((Person instanceof Number) + "<br>"); // outputs false
document.write((Person instanceof String) + "<br>"); // outputs false
document.write((Person instanceof Boolean) + "<br>"); // outputs false
document.write((myArray instanceof Object) + "<br>"); // outputs true
document.write((myArray instanceof Array) + "<br>"); // outputs true
document.write((birthday instanceof Date) + "<br>"); // outputs true
document.write((birthday instanceof Object) + "<br>"); // outputs true
document.write((x instanceof Number) + "<br>"); // outputs true
Operator precedence
If an expression has more than one operator, the order in which the operations within the expression are executed will depend on the precedence (i.e. the level of priority) of the individual operators. You are probably aware of the rules of precedence applied to arithmetic operators, which are summarised by the mnemonic BODMAS (Brackets, Order, Division, Multiplication, Addition, Subtraction).
In JavaScript, every operator has a precedence number that determines its level of precedence. Operations involving an operator with a high precedence number will be executed before operations that involve an operator with a lower precedence number. If two operands have the same precedence number, the order of execution is strictly left-to-right.
The table below lists the JavaScript operators we have discussed in this page (along with some that we haven't discussed yet) along with their precedence number, operator type, and associativity. The associativity of an operator determines the order in which operations with the same precedence are evaluated. Left-associativity proceeds from left to right, while right-associativity proceeds in the opposite direction, from right to left. Consider the following statement:
x = a + b + c;
The assignment operator (+) has right-associativity. That means that its right-hand operand (the expression a + b + c) is evaluated first, and the result is then assigned to the left-hand operand (x). The expression a + b + c has two addition operators that, since they are identical, have equal precedence. The addition operator has left-associativity, so the addition operations will be evaluated from left to right:
x = (a + b) + c;
If a number of operations of equal precedence are chained together, each additional operation in the direction of the associativity is made with the result of the previously evaluated operation as its left- or right-hand operand, depending on the direction of the associativity. For example, the following statements do the same thing, but we have used the grouping operator in the second statement to emphasize the left-associativity of the addition operations:
x = a + b + c + d + e;
x = (((a + b) + c) + d) + e;
We can do something similar with chained assignment operations. Suppose we had several variables to which we want to assign the same value. Both of the statements below achieve this, but we have again used the grouping operator in the second statement to emphasize the right-associativity of the assignment operations:
a = b = c = d = 32;
a = (b = (c = (d = 32)));
You will see that parentheses - the grouping operator - has a higher precedence than any other operator. In other words, expressions inside parentheses are always evaluated before anything else. This can be quite useful if you want to override the standard operator precedence for some reason. For example, consider the following example:
let x = 3, y = 5, z = 7;
document.write(x + y * z); // outputs 38
document.write((x + y) * z); // outputs 56
The first document.write() statement outputs 38 because the multiplication operator has a higher precedence number (15) than the addition operator (14). The expression y * z is evaluated first, and the result is added to the value of x. In the second document.write() statement, we use the grouping operator ( ... ) to force JavaScript to evaluate x + y first. The result of that addition is then multiplied by the value of z.
Precedence | Operator Type | Associativity | Operators |
---|---|---|---|
21 | Grouping | n/a | ( ... ) |
20 | Member Access | left-to-right | ... . ... |
20 | Computed Member Access | left-to-right | ... [ ... ] |
20 | new (with argument list) | n/a | new ... ( ... ) |
20 | Function Call | left-to-right | ... ( ... ) |
20 | Optional Chaining | left-to-right | ?. |
19 | new (without argument list) | right-to-left | new ... |
18 | Postfix Increment | n/a | ... ++ |
18 | Postfix Decrement | n/a | ... -- |
17 | Logical NOT | right-to-left | ! ... |
17 | Bitwise NOT | right-to-left | ~ ... |
17 | Unary Plus | right-to-left | + ... |
17 | Unary Negation | right-to-left | - ... |
17 | Prefix Increment | right-to-left | ++ ... |
17 | Prefix Decrement | right-to-left | -- ... |
17 | typeof | right-to-left | typeof ... |
17 | void | right-to-left | void ... |
17 | delete | right-to-left | delete ... |
17 | await | right-to-left | await ... |
16 | Exponentiation | right-to-left | ... ** ... |
15 | Multiplication | left-to-right | ... * ... |
15 | Division | left-to-right | ... / ... |
15 | Remainder (Modulo) | left-to-right | ... % ... |
14 | Addition | left-to-right | ... + ... |
14 | Subtraction | left-to-right | ... - ... |
13 | Bitwise Left Shift | left-to-right | ... << ... |
13 | Bitwise Right Shift | left-to-right | ... >> ... |
13 | Bitwise Unsigned Right Shift | left-to-right | ... >>> ... |
12 | Less Than | left-to-right | ... < ... |
12 | Less Than Or Equal | left-to-right | ... <= ... |
12 | Greater Than | left-to-right | ... > ... |
12 | Greater Than Or Equal | left-to-right | ... >= ... |
12 | in | left-to-right | ... in ... |
12 | instanceof | left-to-right | ... instanceof ... |
11 | Equality | left-to-right | ... == ... |
11 | Inequality | left-to-right | ... != ... |
11 | Strict Equality | left-to-right | ... === ... |
11 | Strict Inequality | left-to-right | ... !== ... |
10 | Bitwise AND | left-to-right | ... & ... |
9 | Bitwise XOR | left-to-right | ... ^ ... |
8 | Bitwise OR | left-to-right | ... | ... |
7 | Nullish coalescing operator | left-to-right | ... ?? ... |
6 | Logical AND | left-to-right | ... && ... |
5 | Logical OR | left-to-right | ... || ... |
4 | Conditional | left-to-right | ... ? ... : ... |
3 | Assignment | left-to-right | ... = ... |
3 | Assignment | left-to-right | ... += ... |
3 | Assignment | left-to-right | ... -= ... |
3 | Assignment | left-to-right | ... ** ... |
3 | Assignment | left-to-right | ... * ... |
3 | Assignment | left-to-right | ... /= ... |
3 | Assignment | left-to-right | ... %= ... |
3 | Assignment | left-to-right | ... <<= ... |
3 | Assignment | left-to-right | ... >>= ... |
3 | Assignment | left-to-right | ... >>>= ... |
3 | Assignment | left-to-right | ... &= ... |
3 | Assignment | left-to-right | ... ^= ... |
3 | Assignment | left-to-right | ... |= ... |
2 | yield | right-to-left | yield ... |
2 | yield* | right-to-left | yield* ... |
1 | Comma / Sequence | left-to-right | ... , ... |