Here is a list of javascript operator and how to use it!
You should mark this and use it when you need to know what is this operator!
In order to naviguate, you can make a cmd + f
or ctrl + f
and put the operator that you need and put :
after this.
Example: ...:
if I'm looking for what is ...
operator
π¨ Popularity is defined by my OWN usage.
Ambidextrous operator
+
: addition | unary plus
Popularity: β β β β β
If you use +
operator BEFORE operand, it will be used as unary plus operator
.
The unary plus operator precedes its operand and evaluates to its operand but attempts to convert it into a number, if it isn't already.
const x = 1
const y = -1
console.log(+x)
// expected output: 1
console.log(+y)
// expected output: -1
console.log(+'')
// expected output: 0
console.log(+true)
// expected output: 1
console.log(+false)
// expected output: 0
console.log(+'hello')
// expected output: NaN
π Note: If you try to use it with a string that is not a number, it will return NaN (not a number)
If you use +
operator in other context will be used as addition operator
.
It Produces the sum of numeric operands
except for string
π Note: It will convert boolean to number, object to number
console.log(2 + 4) // 6
console.log(2 + true) // 3
When you use it with string it will make a string concatenation
const name = 'code oz'
console.log('hello ' + 'my name is ' + name)
π Note: you should use template litterals string instead of concatenation
-
: subtraction | unary negation
Popularity: β β β β β
If you use -
operator BEFORE operand, it will be used as unary negation operator
.
The unary negation operator precedes its operand and negates it.
π Note: It will convert boolean to number, object to number & string to number
const a = 5
console.log(-a) // -5
console.log(-'1') // -1
π Note: If you try to use it with a string that is not a number, it will return NaN (not a number)
If you use -
operator in other context will be used as subtraction operator
.
It subtracts the two operands, producing their difference.
console.log(5 - 3)
// expected output: 2
console.log(3.5 - 5)
// expected output: -1.5
console.log(5 - 'hello')
// expected output: NaN
console.log(5 - true)
// expected output: 4
...
: spread | rest
Popularity: β β β β β
If you use ...
operator as function argument during execution, it will turns array into a list of arguments. In this context it's called Spread operator
.
let arr = [3, 5, 1]
Math.max(...arr) // 5 (spread turns array into a list of arguments)
You can use ...
operator in another way that is the opposite of turning array into a list
, it's when you convert some item into an array
!
It allows us to have an unlimited number of parameter for this function! since it will convert the arguments (list of item) into an array that is the argument!
// rest parameter is handle as array in the function
const add = (...rest) => {
return rest.reduce((total, current) => total + current)
}
// Nice your function can handle different number of parameters !
add(1, 2, 3)
add(1, 2, 3, 4, 5)
You can also use it for extracting
values from array
or object
// We extract the first Item of the array into the variable and the others variable in an array named others
const [ firstItem, ...others ] = [ 1, 2, 3, 4 ]
firstItem // 1
others // [ 2, 3, 4 ]
const toto = { a: 1, b: 2, c: 3 }
const { a, ...others } = toto
a // 1, we extract the a key from toto object
others // { b: 2, c: 3 }, we extract other key in the object thanks to rest operator
π Note: When you are doing const toto = { ...anotherObject }
it's equal to const toto = Object.assign({}, anotherObject)
Summarize:
Spread operator:
Transform arrays into list of arguments.
Rest operator:
Transform list of arguments into an array.
Logical operator
Thing to know: All value in Javascript are falsy or truthy value, it means that you can make Boolean(any value), and you will get boolean value. In Javascript all value are truthy value except 0, null, undefined, NaN, empty string
&&
: logical AND
Popularity: β β β β β
Use to check if all value (in general value are condition) are truthy.
It will return the first value falsy, otherwise it will return the final value.
const isTrue = true
const isFalse = false
const value = isFalse && isTrue // will return false
const valueBis = isTrue && isFalse // will return false
const toto = 5 && 3 && 1 // will return 1 since all value before are true (5 & 3)
const tutu = 5 && 0 && 2 // will return 0 since it's the first falsy value
if (firstCondition && secondCondition) { console.log('hello') } // console log will be shown only if both condition are true!
&&=
: logical AND assignement
Popularity: β ββββ
Value is assigned only if value passed is truthy.
let toto = 0
let tutu = 2
toto &&= 5 // toto value will be NOT changed since toto is falsy (0)
tutu &&= 3 // tutu value will be replaced by 3 since tutu is trusly (2)
// toto &&= 5 It's a shortcut of π
let toto = 0
toto = toto && 5
||
: logical OR
Popularity: β β β β β
Use to check if one value (in general value are condition) are truthy among a set of value.
It will return the first value truthy, otherwise it will return the final value.
const isTrue = true
const isFalse = false
const value = isFalse || isTrue // will return true
const valueBis = isTrue || isFalse // will return true
const toto = 5 || 3 || 1 // will return 5 since it's the first truthy value
const tutu = 0 || 2 || 5 // will return 2 since it's the first truthy value
if (firstCondition || secondCondition) { console.log('hello') } // console log will be shown if one condition matches!
||=
: logical OR assignement
Popularity: β ββββ
Value is assigned only if value passed is falsy.
let toto = 0
let tutu = 2
toto ||= 5 // toto value will be replaced by 5 since toto is falsy (0)
tutu ||= 3 // tutu value will NOT changed since tutu is not a falsy value (2)
// toto ||= 5 It's a shortcut of π
let toto = 0
toto = toto || 5
??
: logical Nullish Coalescing
Popularity: β β β ββ
Returns its its right-hand side operand when its left-hand side operand is null
or undefined
(nullish value).
const toto = 0 ?? 55 // 0 since 0 is not equal to nullish value.
const tutu = null ?? 'hello' // 'hello' since the right-hand side is equal to `null`
const tata = undefined ?? 55 // '55 since the right-hand side is equal to `undefined`
const titi = null ?? undefined // undefined since the right-hand side is equal to `null`
β οΈ Be careful: ??
operator is different of ||
, so when you need to assign a value depending on other value, you should pick the correct operator!
const toto = 0 || 55 // 55 since 0 is a falsy value
const titi = 0 ?? 55 // 0 since 0 is different of nullish value
const tutu = undefined || 55 // 55 since undefined is a falsy value
const tata = undefined ?? 55 // 55 since undefined is equal to nullish value
??=
: logical Nullish assignement
Popularity: β ββββ
Value is assigned only if value passed is equal to null
or undefined
(nullish).
let toto = null
toto ??= 55 // toto is equal to 55 since it's a nullish value (null)
let tutu = 90
tutu ??= 23 // toto is equal to 90 since it's not a nullish value (90)
// toto ??= 5 It's a shortcut of π
let toto = null
toto = toto ?? 5 // Equal to 5 since toto is equal to null
!
: logical NOT
Popularity: β β β β β
Swap a true value
into false value
and false value
into true value
.
It also convert any value to boolean value. So all truthy
value become falsy
value and vice versa.
π‘ Tips: I use double logical operator a lot in order to convert any value to boolean! It's equal to use Boolean(any value)
console.log(!true) // false
console.log(!true) // true
console.log(!0) // false
console.log(!1) // true
console.log(!{}) // false
console.log(![]) // false
console.log(!undefined) // true
// My tips π
console.log(!!{}) // true, equal to Boolean({})
console.log(!![]) // true, equal to Boolean([])
if (!!value) { ... } // I use a lot in order to check if a value is defined or undefined! (Be careful, if the value is equal to `0` it will be false!)
Special operator
?.
: Optional chaining
Popularity: β β β β β
It allows to accesses a property on an object without having to check if each reference in the chain is valid.
It's not really clear? Ok let's have a look π
const toto = { a: { b: 5 } }
toto.a // { b: 5 }
toto.a.b // 5
toto.a.b.c // undefined
toto.a.b.c.d // Uncaught TypeError: Cannot read properties of undefined
In fact in you try to access to a property on an undefined property, Javascript engine will trigger an error!
So to be safe we need to make something like π
const toto = { a: { b: 5 } }
if (toto.a && toto.a.b && toto.a.b.c && toto.a.b.c.d) {
console.log(toto.a.b.c.d) // It's safe to use it since we check before if the property exist!
}
But it's not really convenient to make this, isn't?
So opional chaining
is here to save us! π¦ΈββοΈ
You can try to access to a property without check if all property exist before as show above! You just need to use this operator on property, if the property doesn't exist, it will return undefined
.
const toto = { a: { b: 5 } }
toto?.a?.b // 5
toto?.a?.b?.c?.d // undefined
?
: Ternary
Popularity: β β β β β
Is the only operator in Javascript that requires two pseudo operand (?
and :
). It evaluate a condition depending on whether that condition is falsy
or truthy
! It's equivalent to if (...) & else (...)
.
console.log(true ? 55 : 10) // 55
console.log(0 ? 13 : 34) // 34
const toto = 2 > 1
console.log(toto ? 'ok' : 'not ok')
// It's a shortcut of π
if (toto) {
console.log('ok')
} else {
console.log('not ok')
}
Comparator operator
==
: Equality
Popularity: β ββββ
It checks whether its two operands are equal, returning a Boolean result. Unlike the === (strict equality operator)
, it attempts to convert (make an implicit coercion) and compare operands that are of different types.
π Note: The mechanic of implicit coercion is not easy to understand but you can check it in details at this post https://dev.to/codeozz/implicit-coercion-in-javascript-neh
Here an exemple of how the implicit corecion is done! π
// 1) Not the same type so implicit coercion will be made
'24' == 24
// 2) Convert string into number so
Number('24') == 24
// 3) We got an number so we can check value
24 == 24 // true !
In general you should use === (strict equality)
and avoid this operator!
===
: Strict Equality
Popularity: β β β β β
It checks whether its two operands are equal, returning a Boolean result. Unlike the == (equality operator)
, the strict equality operator always considers operands of different types to be different.
console.log(1 === 1)
// expected output: true
console.log('hello' === 'hello')
// expected output: true
console.log('1' === 1)
// expected output: false
console.log(0 === false)
// expected output: false
You should always use this operator instead of == (equality operator)
!
!=
: Inequality
Popularity: β ββββ
It checks whether its two operands are not equal, returning a Boolean result. Unlike the !== (strict inequality operator)
, it attempts to convert and compare operands that are of different types.
console.log(1 != 1)
// expected output: false
console.log('hello' != 'hello')
// expected output: false
console.log('1' != 1)
// expected output: false
console.log(0 != false)
// expected output: false
In general you should use !== (strict inequality)
and avoid this operator!
!==
: Strict Inequality
Popularity: β β β β β
It checks whether its two operands are not equal, returning a Boolean result. Unlike the (!= inequality operator)
, the strict inequality operator always considers operands of different types to be different.
console.log(1 !== 1)
// expected output: false
console.log('hello' !== 'hello')
// expected output: false
console.log('1' !== 1)
// expected output: true
console.log(0 !== false)
// expected output: true
You should always use this operator instead of != (inequality)
!
>
: Greater than
Popularity: β β β β β
It returns true if the left operand is greater than the right operand, and false otherwise.
console.log(5 > 3)
// expected output: true
console.log(3 > 3)
// expected output: false
console.log('ab' > 'aa')
// expected output: true
>=
: Greater than or Equal To
Popularity: β β β β β
It returns true if the left operand is greater than or equal to the right operand, and false otherwise.
console.log(5 >= 3)
// expected output: true
console.log(3 >= 3)
// expected output: true
console.log('ab' >= 'aa')
// expected output: true
<
: Less than
Popularity: β β β β β
It returns true if the left operand is less than the right operand, and false otherwise.
console.log(5 < 3)
// expected output: false
console.log(3 < 3)
// expected output: false
console.log('aa' < 'ab')
// expected output: true
<=
: Less than or Equal To
Popularity: β β β β β
It returns true if the left operand is less than or equal to the right operand, and false otherwise.
console.log(5 <= 3)
// expected output: false
console.log(3 <= 3)
// expected output: true
// Compare bigint to number (note: bigint is not supported in all browsers)
console.log(3n <= 5)
// expected output: true
console.log('aa' <= 'ab')
// expected output: true
Arithmetic operator
+=
: Addition Assignment
Popularity: β β β ββ
Adds
the value of the right operand to a variable and assigns the result to the variable
.
let a = 5
let b = 3
b += a // b will be equal to 8, since we are adding 5 to b variable!
-=
: Subtraction Assignment
Popularity: β β β ββ
Subtracts
the value of the right operand to a variable and assigns the result to the variable
.
let a = 5
let b = 3
b -= a // b will be equal to 2, since we are subtracting 5 to b variable!
*
: Multiplication
Popularity: β β β ββ
Its produces the product of the operands.
let a = 5
let b = 3
let c = a * b // 15
*=
: Multiplication Assignment
Popularity: β β β ββ
Multiple
the value of the right operand to a variable and assigns the result to the variable
.
let a = 5
let b = 3
b *= a // 15
/
: Division
Popularity: β β β ββ
Its produces the quotient of its operands
where the left operand is the dividend and the right operand is the divisor.
let a = 10
let b = 2
let c = a / b // 2
console.log(1 / 0) // Infinity
/=
: Division Assignment
Popularity: β β β ββ
Divide
the value of the right operand to a variable and assigns the result to the variable
.
let a = 10
let b = 2
b /= a // 2
**
: Exponentiation
Popularity: β β β ββ
Its returns the result of raising the first operand to the power of the second operand. It is equivalent to Math.pow
, except it also accepts BigInts as operands.
let a = 10
let b = 2
let c = a ** b // 100, it equals to 10^2 or Math.pow(10, 2)
**=
: Exponentiation Assignment
Popularity: β β β ββ
It raises the value of a variable
to the power of the right operand.
let a = 10
let b = 2
b **= a // 1024, it equals to 2^10 or Math.pow(2, 10)
a **= b // 100, it equals to 10^2 or Math.pow(10, 2)
%
: Remainder (modulo)
Popularity: β ββββ
Its returns the remainder left over when one operand is divided by a second operand. It always takes the sign of the dividend.
let a = 10
let b = 3
let c = a % b // 1
More information about modulo in mathematic -> https://simple.wikipedia.org/wiki/Modulo_operation
%=
: Remainder Assignment
Popularity: β ββββ
It divides a variable by the value of the right operand
and assigns the remainder to the variable
.
let a = 10
let b = 3
a %= b // 1 it's equal to a % b
More information about modulo in mathematic -> https://simple.wikipedia.org/wiki/Modulo_operation
++
: Increment
Popularity: β β β ββ
It increments (adds one to) its operand and returns a value.
You can use it in two ways:
- As
pre increment
: It increment the value before the operation
let toto = 55
console.log(toto) // 55
console.log(++toto) // 56
console.log(toto) // 56
- As
post increment
: It increment the value after the operation
let toto = 55
console.log(toto) // 55
console.log(toto++) // 55
console.log(toto) // 56
--
: Decrement
Popularity: β β β ββ
It decrement (subtracts one to) its operand and returns a value.
You can use it in two ways:
- As
pre decrement
: It decrement the value before the operation
let toto = 55
console.log(toto) // 55
console.log(--toto) // 54
console.log(toto) // 54
- As
post decrement
: It decrement the value after the operation
let toto = 55
console.log(toto) // 55
console.log(toto--) // 55
console.log(toto) // 54
Bits operator
&
: Bitwise AND
Popularity: β ββββ
Returns a 1 in each bit position for which the corresponding bits of both operands are 1s.
β οΈ Be careful: Don't be confused between &
and &&
operator! The &&
is the logical operator AND
const a = 5 // 00000000000000000000000000000101
const b = 3 // 00000000000000000000000000000011
console.log(a & b) // 00000000000000000000000000000001
π‘ Tips: If you need to check if a number is even, you can use numberVar & 1
, if the result is equal to 0
, your number is even!
&=
: Bitwise AND assignment
Popularity: β ββββ
It uses the binary representation of both operands, does a bitwise AND operation on them and assigns the result to the variable.
let a = 5 // 00000000000000000000000000000101
a &= 3 // 00000000000000000000000000000011
console.log(a) // 00000000000000000000000000000001
~
: Bitwise NOT
Popularity: β ββββ
It inverts the bits of its operand. Like other bitwise operators, it converts the operand to a 32-bit signed integer
const a = 5 // 00000000000000000000000000000101
const b = -3 // 11111111111111111111111111111101
console.log(~a) // 11111111111111111111111111111010
// expected output: -6
console.log(~b) // 00000000000000000000000000000010
// expected output: 2
|
: Bitwise OR
Popularity: β ββββ
It returns a 1 in each bit position for which the corresponding bits of either or both operands are 1s.
const a = 5 // 00000000000000000000000000000101
const b = 3 // 00000000000000000000000000000011
console.log(a | b) // 00000000000000000000000000000111
// expected output: 7
|=
: Bitwise OR assignment
Popularity: β ββββ
It uses the binary representation of both operands, does a bitwise OR operation on them and assigns the result to the variable.
let a = 5 // 00000000000000000000000000000101
a |= 3 // 00000000000000000000000000000011
console.log(a) // 00000000000000000000000000000111
// expected output: 7
^
: Bitwise XOR
Popularity: β ββββ
It returns a 1 in each bit position for which the corresponding bits of either but not both operands are 1s.
const a = 5 // 00000000000000000000000000000101
const b = 3 // 00000000000000000000000000000011
console.log(a ^ b) // 00000000000000000000000000000110
^=
: Bitwise XOR assignment
Popularity: β ββββ
It uses the binary representation of both operands, does a bitwise XOR operation on them and assigns the result to the variable.
let a = 5 // 00000000000000000000000000000101
a ^= 3 // 00000000000000000000000000000011
console.log(a) // 00000000000000000000000000000110
// expected output: 6
<<
: Left shift
Popularity: β ββββ
Shifts the first operand the specified number of bits to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right.
const a = 5 // 00000000000000000000000000000101
const b = 2 // 00000000000000000000000000000010
console.log(a << b) // 00000000000000000000000000010100
// expected output: 20
<<=
: Left shift assignment
Popularity: β ββββ
Moves the specified amount of bits to the left and assigns the result to the variable.
let a = 5 // 00000000000000000000000000000101
a <<= 2 // 00000000000000000000000000010100
console.log(a)
// expected output: 20
>>
: Right shift
Popularity: β ββββ
Shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Copies of the leftmost bit are shifted in from the left.
Since the new leftmost bit has the same value as the previous leftmost bit, the sign bit (the leftmost bit) does not change. Hence the name "sign-propagating".
const a = 5 // 00000000000000000000000000000101
const b = 2 // 00000000000000000000000000000010
const c = -5 // -00000000000000000000000000000101
console.log(a >> b) // 00000000000000000000000000000001
// expected output: 1
console.log(c >> b) // -00000000000000000000000000000010
// expected output: -2
>>=
: Right shift assignment
Popularity: β ββββ
Moves the specified amount of bits to the right and assigns the result to the variable.
let a = 5 // 00000000000000000000000000000101
a >>= 2 // 00000000000000000000000000000001
console.log(a)
// expected output: 1
let b = -5 // -00000000000000000000000000000101
b >>= 2 // -00000000000000000000000000000010
console.log(b)
// expected output: -2
>>>
: Unsigned Right shift
Popularity: β ββββ
Shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded.
Zero bits are shifted in from the left.
The sign bit becomes 0, so the result is always non-negative. Unlike the other bitwise operators, zero-fill right shift returns an unsigned 32-bit integer.
const a = 5 // 00000000000000000000000000000101
const b = 2 // 00000000000000000000000000000010
const c = -5 // -00000000000000000000000000000101
console.log(a >>> b) // 00000000000000000000000000000001
// expected output: 1
console.log(c >>> b) // 00111111111111111111111111111110
// expected output: 1073741822
>>>=
: Unsigned Right shift assignment
Popularity: β ββββ
Moves the specified amount of bits to the right and assigns the result to the variable.
let a = 5 // 00000000000000000000000000000101
a >>>= 2 // 00000000000000000000000000000001
console.log(a)
// expected output: 1
let b = -5 // -00000000000000000000000000000101
b >>>= 2 // 00111111111111111111111111111110
console.log(b)
// expected output: 1073741822
I hope you like this reading!
π You can get my new book Underrated skills in javascript, make the difference
for FREE if you follow me on Twitter and send message to me π and SAVE 19$ π΅π΅
Or get it HERE
π«π·π₯ For french developper you can check my YoutubeChannel
π MY NEWSLETTER
βοΈ You can SUPPORT MY WORKS π
πββοΈ You can follow me on π
π Twitter : https://twitter.com/code__oz
π¨βπ» Github: https://github.com/Code-Oz
And you can mark π this article!
Top comments (15)
A couple of thoughts, one technical and one subjective:
the
...
on the left-hand-side of an assignment statement is also a "rest" operator. "spread" is for expressions (or rhs in statements). When you are putting a bunch of stuff into something, it's a "spread". When you are pulling a bundle of stuff out of something, and giving that bundle a new name, it's a "rest". In functions you are pulling the bundle out of the arguments arrayconst f = (x, y, z, ...extraDimensions /*rest of the args*/) => {};
const [x, y, z, ...extraDimensions /*rest of the array*/] = dimensions;
const { x, y, z, ...extraDimensions /*rest of the object*/} = dimensions;
I personally feel you should be using
??
at least as often as you are using?.
, if not more often. Again, this is the subjective opinion. If you are often using?.
that means you are often gettingundefined
. If you are passingundefined
around, it means that you are often forcing other people (or other parts of the codebase) to do null checking. If you are handling those missing holes in your data with??
, then you have fewer reasons to use?.
farther down the line... Null checking is Sir Tony Hoare's "Billion-Dollar Mistake" and is generally better handled on the outskirts of a system, near the I/O, rather than in the middle of all of the logic... the opinion might be subjective, but it's got a pretty sound backing, by even the inventor of Null (or the person who introduced the concept to programming languages), let alone language researchers.thanks for replied! I changed a few things for
...
operatorFun article, thanks for it! MDN has some great resources on this topic as well developer.mozilla.org/docs/Web/Jav... developer.mozilla.org/docs/Web/Jav... developer.mozilla.org/docs/Web/Jav...
Nice sharing! didn't read at all but it seems to be nice!
Thanks Yarip
Perfect work..
thank you a lot
Perfect work
thanks a lot!
Article of the month. Nice.
thank you a lot mate
Small correction in the code snippet for logical Nullish Coalescing.,
It was mentioned right-handed instead of left-handed.,
thanks it's fixed :D
Very nice feedbacks luke!