JavaScript operators
In JavaScript, operators are special symbols or keywords that perform operations on values and variables. Here’s a rundown of the main types:
1. Arithmetic Operators
+
(Addition): Adds two values.5 + 3
results in8
.-
(Subtraction): Subtracts one value from another.5 - 3
results in2
.*
(Multiplication): Multiplies two values.5 * 3
results in15
./
(Division): Divides one value by another.6 / 3
results in2
.%
(Modulus): Returns the remainder of a division operation.5 % 3
results in2
.**
(Exponentiation): Raises a number to the power of another number.2 ** 3
results in8
.
2. Assignment Operators
=
: Assigns a value to a variable.let x = 5
assigns5
tox
.+=
: Adds and assigns.x += 3
is equivalent tox = x + 3
.-=
: Subtracts and assigns.x -= 3
is equivalent tox = x - 3
.*=
: Multiplies and assigns.x *= 3
is equivalent tox = x * 3
./=
: Divides and assigns.x /= 3
is equivalent tox = x / 3
.%=
: Applies modulus and assigns.x %= 3
is equivalent tox = x % 3
.
3. Comparison Operators
==
: Equality. Checks if two values are equal, after type conversion.5 == '5'
istrue
.===
: Strict equality. Checks if two values are equal, without type conversion.5 === '5'
isfalse
.!=
: Inequality. Checks if two values are not equal, after type conversion.5 != '5'
isfalse
.!==
: Strict inequality. Checks if two values are not equal, without type conversion.5 !== '5'
istrue
.>
: Greater than.5 > 3
istrue
.<
: Less than.5 < 3
isfalse
.>=
: Greater than or equal to.5 >= 5
istrue
.<=
: Less than or equal to.5 <= 5
istrue
.
4. Logical Operators
&&
(Logical AND): Returnstrue
if both operands aretrue
.true && false
isfalse
.||
(Logical OR): Returnstrue
if at least one operand istrue
.true || false
istrue
.!
(Logical NOT): Returnstrue
if the operand isfalse
.!true
isfalse
.
5. Unary Operators
+
(Unary plus): Converts a value to a number.+ '5'
results in5
.-
(Unary minus): Negates a value.-5
results in-5
.++
(Increment): Increases a variable’s value by 1.x++
or++x
.--
(Decrement): Decreases a variable’s value by 1.x--
or--x
.!
(Logical NOT): Inverts the boolean value.!true
results infalse
.
6. Conditional (Ternary) Operator
? :
: Evaluates a condition and returns one of two values.condition ? expr1 : expr2
. Ifcondition
is true,expr1
is returned; otherwise,expr2
is returned.
7. Type Operators
typeof
: Returns the type of a variable.typeof 5
results in"number"
.instanceof
: Checks if an object is an instance of a specific class.[] instanceof Array
istrue
.
8. Bitwise Operators
&
(AND): Performs a bitwise AND.5 & 3
results in1
.|
(OR): Performs a bitwise OR.5 | 3
results in7
.^
(XOR): Performs a bitwise XOR.5 ^ 3
results in6
.~
(NOT): Inverts all the bits of a number.~5
results in-6
.<<
(Left shift): Shifts bits to the left.5 << 1
results in10
.>>
(Right shift): Shifts bits to the right.5 >> 1
results in2
.>>>
(Unsigned right shift): Shifts bits to the right, filling with zeros.5 >>> 1
results in2
.