Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
November 18, 2021 06:04 pm GMT

You MUST store this Javascript Operator Index

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 = 1const y = -1console.log(+x)// expected output: 1console.log(+y)// expected output: -1console.log(+'')// expected output: 0console.log(+true)// expected output: 1console.log(+false)// expected output: 0console.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) // 6console.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 = 5console.log(-a) // -5console.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: 2console.log(3.5 - 5)// expected output: -1.5console.log(5 - 'hello')// expected output: NaNconsole.log(5 - true)// expected output: 4

...: spread | rest

If you use ... operator in function parameters, it will be used as rest operator

It allows us to have an unlimited number of parameter for this function!

// rest parameter is handle as array in the functionconst 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)

If you use ... operator in other context, it will be used as spread operator

  • If you use it as arguments in function: It will allows an iterable such as an array expression in function parameters.
const fruits = ['Apple','Orange','Banana']const getFruits = (f1, f2, f3) => {    console.log(Fruits: ${f1}, ${f2} and ${f3})}getFruits(...fruits) // Fruits: Apple, Orange and Banana
  • 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 othersconst [ firstItem, ...others ] = [ 1, 2, 3, 4 ]firstItem // 1others // [ 2, 3, 4 ]
const toto = { a: 1, b: 2, c: 3 }const { a, ...others } = totoa // 1, we extract the a key from toto objectothers // { 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)

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 = trueconst isFalse = falseconst value = isFalse && isTrue // will return false const valueBis = isTrue && isFalse // will return falseconst 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 valueif (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 = 0let tutu = 2toto &&= 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 = trueconst isFalse = falseconst value = isFalse || isTrue // will return true const valueBis = isTrue || isFalse // will return trueconst toto = 5 || 3 || 1 // will return 5 since it's the first truthy valueconst tutu = 0 || 2 || 5 // will return 2 since it's the first truthy valueif (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 = 0let tutu = 2toto ||= 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 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 valueconst titi = 0 ?? 55 // 0 since 0 is different of nullish valueconst tutu = undefined || 55 // 55 since undefined is a falsy valueconst 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 = nulltoto ??= 55 // toto is equal to 55 since it's a nullish value (null)let tutu = 90tutu ??= 23 // toto is equal to 90 since it's not a nullish value (90)// toto ??= 5 It's a shortcut of let toto = nulltoto = 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) // falseconsole.log(!true) // trueconsole.log(!0) // falseconsole.log(!1) // trueconsole.log(!{}) // falseconsole.log(![]) // falseconsole.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 // 5toto.a.b.c // undefinedtoto.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 // 5toto?.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) // 55console.log(0 ? 13 : 34) // 34const toto = 2 > 1console.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 value24 == 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: trueconsole.log('hello' === 'hello')// expected output: trueconsole.log('1' ===  1)// expected output: falseconsole.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: falseconsole.log('hello' != 'hello')// expected output: falseconsole.log('1' !=  1)// expected output: falseconsole.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: falseconsole.log('hello' !== 'hello')// expected output: falseconsole.log('1' !==  1)// expected output: trueconsole.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: trueconsole.log(3 > 3)// expected output: falseconsole.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: trueconsole.log(3 >= 3)// expected output: trueconsole.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: falseconsole.log(3 < 3)// expected output: falseconsole.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: falseconsole.log(3 <= 3)// expected output: true// Compare bigint to number (note: bigint is not supported in all browsers)console.log(3n <= 5)// expected output: trueconsole.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 = 5let b = 3b += 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 = 5let b = 3b -= 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 = 5let b = 3let 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 = 5let b = 3b *= 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 = 10let b = 2let c = a / b // 2console.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 = 10let b = 2b /= 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 = 10let b = 2let 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 = 10let b = 2b **= 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 = 10let b = 3let 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 = 10let b = 3a %= 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 = 55console.log(toto) // 55console.log(++toto) // 56console.log(toto) // 56
  • As post increment: It increment the value after the operation
let toto = 55console.log(toto) // 55console.log(toto++) // 55console.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 = 55console.log(toto) // 55console.log(--toto) // 54console.log(toto) // 54
  • As post decrement: It decrement the value after the operation
let toto = 55console.log(toto) // 55console.log(toto--) // 55console.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        // 00000000000000000000000000000101const b = 3        // 00000000000000000000000000000011console.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      // 00000000000000000000000000000101a &= 3         // 00000000000000000000000000000011console.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     // 00000000000000000000000000000101const b = -3    // 11111111111111111111111111111101console.log(~a) // 11111111111111111111111111111010// expected output: -6console.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        // 00000000000000000000000000000101const b = 3        // 00000000000000000000000000000011console.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      // 00000000000000000000000000000101a |= 3         // 00000000000000000000000000000011console.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        // 00000000000000000000000000000101const b = 3        // 00000000000000000000000000000011console.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      // 00000000000000000000000000000101a ^= 3         // 00000000000000000000000000000011console.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         // 00000000000000000000000000000101const b = 2         // 00000000000000000000000000000010console.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 // 00000000000000000000000000000101a <<= 2   // 00000000000000000000000000010100console.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          //  00000000000000000000000000000101const b = 2          //  00000000000000000000000000000010const c = -5         // -00000000000000000000000000000101console.log(a >> b)  //  00000000000000000000000000000001// expected output: 1console.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      //  00000000000000000000000000000101a >>= 2        //  00000000000000000000000000000001console.log(a)// expected output: 1let b = -5     // -00000000000000000000000000000101b >>= 2        // -00000000000000000000000000000010console.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          //  00000000000000000000000000000101const b = 2          //  00000000000000000000000000000010const c = -5         // -00000000000000000000000000000101console.log(a >>> b) //  00000000000000000000000000000001// expected output: 1console.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 //  00000000000000000000000000000101a >>>= 2  //  00000000000000000000000000000001console.log(a)// expected output: 1let b = -5 // -00000000000000000000000000000101b >>>= 2   //  00111111111111111111111111111110console.log(b)// expected output: 1073741822

Original Link: https://dev.to/codeoz/you-must-store-this-javascript-operator-index-2bec

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To