You MUST store this Javascript Operator Index
Tags: javascript, webdev, beginners, codenewbie
Published: 2021-11-18 18:04:09

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.

```javascript
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_

```javasript
console.log(2 + 4) // 6
console.log(2 + true) // 3
```

When you use it with string it will make a `string concatenation`


```javascript
const name = 'code oz'
console.log('hello ' + 'my name is ' + name)
```

_📝 Note: you should use [template litterals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) 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_

```javascript
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.

```javascript
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`.

```javascript
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!

```javascript
// 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`

```javascript
// 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 ]
```

```javascript
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. 

```javascript
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.

```javascript
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.

```javascript
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.

```javascript
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).

```javascript
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!_

```javascript
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).

```javascript
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)_

```javascript
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 👇

```javascript
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 👇

```javascript
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`.

```javascript
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 (...) `.

```javascript
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! 👇

```javascript
// 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.

```javascript
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.

```javascript
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.

```javascript
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.

```javascript
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.

```javascript
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.

```javascript
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.

```javascript
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`.

```javascript
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`.

```javascript
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.

```javascript
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`.

```javascript
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.

```javascript
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`.

```javascript
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.

```javascript
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.

```javascript
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.

```javascript
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`.

```javascript
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

```javascript
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

```javascript
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

```javascript
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

```javascript
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_

```javacript
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.

```javacript
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

```javacript
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.

```javacript
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.

```javacript
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.

```javacript
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.

```javacript
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.

```javascript
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.

```javascript
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".

```javascript
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.

```javascript
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.

```javascript
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.

```javascript
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](https://twitter.com/code__oz) and send message to me 😁 and **SAVE 19$** 💵💵

Or get it [HERE](https://codeoz.gumroad.com/l/RXLYp) 

🇫🇷🥖 For french developper you can check my [YoutubeChannel](https://www.youtube.com/channel/UCC675U1ZUPFASsK9-FjawtA)

🎁 [MY NEWSLETTER](https://www.getrevue.co/profile/code__oz)

☕️ You can [SUPPORT MY WORKS](https://www.buymeacoffee.com/CodeoZ) 🙏

🏃‍♂️ You can follow me on 👇

🕊 Twitter : [https://twitter.com/code__oz](https://twitter.com/code__oz)

👨‍💻 Github: https://github.com/Code-Oz

And you can mark 🔖 this article!