JavaScript Operators: A Comprehensive Reference
Operators are symbols that perform operations on one or more values (called operands) and produce a new value. JavaScript supports different types of operators, such as arithmetic, assignment, comparison, logical, bitwise, string, conditional, and comma operators. Each operator has its own syntax, precedence, and associativity rules that determine how it is evaluated in an expression.
Arithmetic Operators
Arithmetic operators are used to perform mathematical calculations on numbers, such as addition, subtraction, multiplication, division, etc. JavaScript supports the following arithmetic operators:
+
: Addition. It adds the operands and returns the sum. For example:3 + 4
returns7
.-
: Subtraction. It subtracts the right operand from the left operand and returns the difference. For example:3 - 4
returns-1
.*
: Multiplication. It multiplies the operands and returns the product. For example:3 * 4
returns12
./
: Division. It divides the left operand by the right operand and returns the quotient. For example:12 / 4
returns3
.%
: Modulus (Remainder). It divides the left operand by the right operand and returns the remainder. For example:5 % 2
returns1
.**
: Exponentiation. It raises the left operand to the power of the right operand and returns the result. For example:2 ** 3
returns8
.++
: Increment. It adds one to the operand and returns the new value. It can be used as a prefix or a postfix operator. For example:++x
orx++
increments the value ofx
by one.--
: Decrement. It subtracts one from the operand and returns the new value. It can be used as a prefix or a postfix operator. For example:--x
orx--
decrements the value ofx
by one.
Assignment Operators
Assignment operators are used to assign a value to a variable. The basic assignment operator is =
, which assigns the value of the right operand to the left operand. For example: x = 10
assigns the value 10
to the variable x
.
There are also compound assignment operators that combine an arithmetic operator with the assignment operator. They perform the arithmetic operation on the left and right operands and assign the result to the left operand. For example: x += 5
is equivalent to x = x + 5
. JavaScript supports the following compound assignment operators:
+=
: Addition assignment. It adds the right operand to the left operand and assigns the result to the left operand. For example:x += 5
is equivalent tox = x + 5
.-=
: Subtraction assignment. It subtracts the right operand from the left operand and assigns the result to the left operand. For example:x -= 5
is equivalent tox = x - 5
.*=
: Multiplication assignment. It multiplies the left operand by the right operand and assigns the result to the left operand. For example:x *= 5
is equivalent tox = x * 5
./=
: Division assignment. It divides the left operand by the right operand and assigns the result to the left operand. For example:x /= 5
is equivalent tox = x / 5
.%=
: Modulus assignment. It divides the left operand by the right operand and assigns the remainder to the left operand. For example:x %= 5
is equivalent tox = x % 5
.**=
: Exponentiation assignment. It raises the left operand to the power of the right operand and assigns the result to the left operand. For example:x **= 2
is equivalent tox = x ** 2
.
Comparison Operators
Comparison operators are used to compare two values and return a Boolean value of true
or false
. JavaScript supports the following comparison operators:
==
: Equal to. It returnstrue
if the operands are equal in value, andfalse
otherwise. For example:3 == 3
returnstrue
, but3 == '3'
also returnstrue
because the operands are converted to the same type before comparison.===
: Strict equal to. It returnstrue
if the operands are equal in value and type, andfalse
otherwise. For example:3 === 3
returnstrue
, but3 === '3'
returnsfalse
because the operands are not of the same type.!=
: Not equal to. It returnstrue
if the operands are not equal in value, andfalse
otherwise. For example:3 != 4
returnstrue
, but3 != '3'
also returnsfalse
because the operands are converted to the same type before comparison.!==
: Strict not equal to. It returnstrue
if the operands are not equal in value or type, andfalse
otherwise. For example:3 !== 4
returnstrue
, but3 !== '3'
also returnstrue
because the operands are not of the same type.>
: Greater than. It returnstrue
if the left operand is greater than the right operand, andfalse
otherwise. For example:3 > 2
returnstrue
, but3 > 4
returnsfalse
.<
: Less than. It returnstrue
if the left operand is less than the right operand, andfalse
otherwise. For example:3 < 4
returnstrue
, but3 < 2
returnsfalse
.>=
: Greater than or equal to. It returnstrue
if the left operand is greater than or equal to the right operand, andfalse
otherwise. For example:3 >= 3
returnstrue
, but3 >= 4
returnsfalse
.<=
: Less than or equal to. It returnstrue
if the left operand is less than or equal to the right operand, andfalse
otherwise. For example:3 <= 3
returnstrue
, but3 <= 2
returnsfalse
.
Logical Operators
Logical operators are used to perform logical operations on Boolean values, such as true
and false
. JavaScript supports the following logical operators:
&&
: Logical AND. It returnstrue
if both operands aretrue
, andfalse
otherwise. For example:true && true
returnstrue
, buttrue && false
returnsfalse
.||
: Logical OR. It returnstrue
if either operand istrue
, andfalse
otherwise. For example:true || false
returnstrue
, butfalse || false
returnsfalse
.!
: Logical NOT. It returnstrue
if the operand isfalse
, andfalse
if the operand istrue
. For example:!true
returnsfalse
, but!false
returnstrue
.
## Bitwise Operators
Bitwise operators are used to perform operations on the binary representations of numbers, such as shifting, rotating, and masking bits. JavaScript supports the following bitwise operators:
&
: Bitwise AND. It performs the AND operation on each pair of corresponding bits of the operands and returns the result. For example:5 & 3
returns1
because0101 & 0011 = 0001
in binary.|
: Bitwise OR. It performs the OR operation on each pair of corresponding bits of the operands and returns the result. For example:5 | 3
returns7
because0101 | 0011 = 0111
in binary.^
: Bitwise XOR. It performs the XOR operation on each pair of corresponding bits of the operands and returns the result. For example:5 ^ 3
returns6
because0101 ^ 0011 = 0110
in binary.~
: Bitwise NOT. It performs the NOT operation on each bit of the operand and returns the result. For example:~5
returns-6
because~0101 = 1010
in binary, which is-6
in two's complement notation.<<
: Bitwise left shift. It shifts the bits of the left operand to the left by the number of positions specified by the right operand and returns the result. For example:5 << 2
returns20
because0101 << 2 = 010100
in binary, which is20
in decimal.>>
: Bitwise right shift. It shifts the bits of the left operand to the right by the number of positions specified by the right operand and returns the result. For example:5 >> 2
returns1
because0101 >> 2 = 0001
in binary, which is1
in decimal.>>>
: Bitwise unsigned right shift. It shifts the bits of the left operand to the right by the number of positions specified by the right operand and returns the result. Unlike the >> operator, it fills the leftmost bits with zeros, regardless of the sign of the operand. For example:-5 >>> 2
returns1073741822
because11111011 >>> 2 = 00111111111111111111111111111110
in binary, which is1073741822
in decimal.
String Operators
String operators are used to perform operations on strings, such as concatenation, extraction, and comparison. JavaScript supports the following string operators:
+
: Concatenation. It joins two or more strings and returns a new string. For example:"Hello" + " " + "world"
returns"Hello world"
.+=
: Concatenation assignment. It appends a string to the end of another string and assigns the result to the first string. For example:let greeting = "Hello"; greeting += " world";
assigns"Hello world"
togreeting
.[]
: Bracket notation. It accesses a character at a specific index in a string and returns it. For example:"Hello"[0]
returns"H"
..charAt()
: Character at. It accesses a character at a specific index in a string and returns it. For example:"Hello".charAt(0)
returns"H"
..slice()
: Slice. It extracts a part of a string and returns a new string. It takes two arguments: the start index and the end index (optional). For example:"Hello".slice(1, 3)
returns"el"
..substring()
: Substring. It extracts a part of a string and returns a new string. It takes two arguments: the start index and the end index (optional). Unlike.slice()
, it does not accept negative indexes. For example:"Hello".substring(1, 3)
returns"el"
..substr()
: Substring. It extracts a part of a string and returns a new string. It takes two arguments: the start index and the length (optional). For example:"Hello".substr(1, 2)
returns"el"
..indexOf()
: Index of. It searches for a substring in a string and returns the index of the first occurrence, or-1
if not found. It takes two arguments: the substring and the start index (optional). For example:"Hello".indexOf("l")
returns2
..lastIndexOf()
: Last index of. It searches for a substring in a string and returns the index of the last occurrence, or-1
if not found. It takes two arguments: the substring and the start index (optional). For example:"Hello".lastIndexOf("l")
returns3
..startsWith()
: Starts with. It checks if a string starts with a substring and returns a Boolean value. It takes two arguments: the substring and the start index (optional). For example:"Hello".startsWith("He")
returnstrue
..endsWith()
: Ends with. It checks if a string ends with a substring and returns a Boolean value. It takes two arguments: the substring and the end index (optional). For example:"Hello".endsWith("lo")
returnstrue
..includes()
: Includes. It checks if a string contains a substring and returns a Boolean value. It takes two arguments: the substring and the start index (optional). For example:"Hello".includes("ll")
returnstrue
..replace()
: Replace. It replaces a substring in a string with another substring and returns a new string. It takes two arguments: the substring to be replaced and the new substring. For example:"Hello".replace("l", "r")
returns"Herro"
..repeat()
: Repeat. It repeats a string a specified number of times and returns a new string. It takes one argument: the number of repetitions. For example:"Hello".repeat(3)
returns"HelloHelloHello"
..toLowerCase()
: To lower case. It converts a string to lower case and returns a new string. For example:"Hello".toLowerCase()
returns"hello"
..toUpperCase()
: To upper case. It converts a string to upper case and returns a new string. For example:"Hello".toUpperCase()
returns"HELLO"
..trim()
: Trim. It removes whitespace from both ends of a string and returns a new string. For example:" Hello ".trim()
returns"Hello"
.
Conditional Operator
The conditional operator (also known as the ternary operator) is the only operator in JavaScript that takes three operands. It is used to perform a conditional operation based on a Boolean value. The syntax is:
condition ? expression1 : expression2
The condition is evaluated as a Boolean value. If the condition is true
, the operator returns the value of expression1
. If the condition is false
, the operator returns the value of expression2
. For example:
let age = 18;
let status = (age >= 18) ? "adult" : "minor";
This assigns "adult"
to status
if age
is greater than or equal to 18
, and "minor"
to status
if age
is less than 18
.
The conditional operator can be nested to create more complex expressions, such as:
let score = 85;
let grade = (score >= 90) ? "A" : (score >= 80) ? "B" : (score >= 70) ? "C" : (score >= 60) ? "D" : "F";
This assigns "B"
to grade
if score
is between 80
and 89
, and so on.
Comma Operator
The comma operator (,) is used to evaluate two or more expressions and return the value of the last expression. The expressions are evaluated from left to right. The comma operator can be useful when you want to perform multiple operations in a single statement, such as:
let x = 1; let y = 2; let z = (x++, y++, x + y);
This assigns 2
to x
, 3
to y
, and 5
to z
.
Unary Operators
Unary operators are operators that take only one operand and perform an operation on it. JavaScript supports the following unary operators:
+
: Unary plus. It converts the operand to a number and returns it. For example:+"3"
returns3
.-
: Unary negation. It converts the operand to a number and negates it. For example:-"3"
returns-3
.!
: Logical NOT. It converts the operand to a Boolean value and inverts it. For example:!true
returnsfalse
.~
: Bitwise NOT. It converts the operand to a 32-bit integer and inverts each bit. For example:~5
returns-6
.typeof
: Type of. It returns a string indicating the type of the operand. For example:typeof 3
returns"number"
.delete
: Delete. It deletes a property from an object and returns a Boolean value indicating whether the deletion was successful. For example:delete person.age
returnstrue
if theage
property was deleted from theperson
object.void
: Void. It evaluates the operand and returnsundefined
. For example:void 0
returnsundefined
.
Relational Operators
Relational operators are used to test the relationship between two values, such as membership, inheritance, or instanceof. JavaScript supports the following relational operators:
in
: In. It returnstrue
if the left operand is a property name or an index of the right operand, which must be an object or an array. For example:"name" in person
returnstrue
if theperson
object has aname
property.instanceof
: Instance of. It returnstrue
if the left operand is an instance of the right operand, which must be a constructor function. For example:person instanceof Object
returnstrue
if theperson
object is an instance of theObject
constructor function.
Operator Precedence and Associativity
Operator precedence and associativity determine the order of evaluation of operators in an expression. Operators with higher precedence are evaluated before operators with lower precedence. For example, the multiplication operator (*) has higher precedence than the addition operator (+), so 3 + 4 * 5
is evaluated as 3 + (4 * 5)
, which is 23
.
If two operators have the same precedence, their associativity determines the order of evaluation. Operators can be either left-associative or right-associative. Left-associative operators are evaluated from left to right, while right-associative operators are evaluated from right to left. For example, the assignment operator (=) is right-associative, so x = y = z
is evaluated as x = (y = z)
, which assigns the value of z
to both y
and x
.
You can use parentheses to override the default order of evaluation and group the expressions as you want. For example, (3 + 4) * 5
is evaluated as 35
, because the parentheses force the addition to be evaluated before the multiplication.
The following table shows the precedence and associativity of the JavaScript operators, from highest to lowest. Operators with the same precedence are grouped together. Operators with higher precedence are evaluated before operators with lower precedence. Operators with the same precedence are evaluated according to their associativity.
Operator | Description | Associativity |
---|---|---|
() | Parentheses | n/a |
. | Member access | left-to-right |
[] | Member access | left-to-right |
new | Object creation | right-to-left |
++ | Postfix increment/decrement | n/a |
! | Prefix operators | right-to-left |
~ | Prefix operators | right-to-left |
+ | Prefix operators | right-to-left |
- | Prefix operators | right-to-left |
++ | Prefix operators | right-to-left |
-- | Prefix operators | right-to-left |
typeof | Prefix operators | right-to-left |
void | Prefix operators | right-to-left |
delete | Prefix operators | right-to-left |
** | Exponentiation | right-to-left |
* | Multiplication/division/modulus | left-to-right |
/ | Multiplication/division/modulus | left-to-right |
% | Multiplication/division/modulus | left-to-right |
+ | Addition/subtraction | left-to-right |
- | Addition/subtraction | left-to-right |
<< | Bitwise shift | left-to-right |
>> | Bitwise shift | left-to-right |
>>= | Bitwise shift | left-to-right |
< | Relational operators | left-to-right |
<= | Relational operators | left-to-right |
> | Relational operators | left-to-right |
>= | Relational operators | left-to-right |
in | Relational operators | left-to-right |
instanceof | Relational operators | left-to-right |
== | Equality operators | left-to-right |
!= | Equality operators | left-to-right |
=== | Equality operators | left-to-right |
!== | Equality operators | left-to-right |
& | Bitwise AND | left-to-right |
^ | Bitwise XOR | left-to-right |
| | Bitwise OR | left-to-right |
&& | Logical AND | left-to-right |
|| | Logical OR | left-to-right |
? : | Conditional operator | right-to-left |
= | Assignment operators | right-to-left |
+= | Assignment operators | right-to-left |
-= | Assignment operators | right-to-left |
*= | Assignment operators | right-to-left |
/= | Assignment operators | right-to-left |
%= | Assignment operators | right-to-left |
**= | Assignment operators | right-to-left |
<<= | Assignment operators | right-to-left |
>>= | Assignment operators | right-to-left |
>>= | Assignment operators | right-to-left |
&= | Assignment operators | right-to-left |
^= | Assignment operators | right-to-left |
|= | Assignment operators | right-to-left |
, | Comma operator | left-to-right |
Summary
In this article, you learned about the different operators that JavaScript supports, such as arithmetic, assignment, comparison, logical, bitwise, string, conditional, and comma operators. You also learned about the precedence and associativity rules that determine the order of evaluation of operators in an expression. Operators are essential for performing operations on values and producing new values in your JavaScript programs.