Web/JavaScript

[JavaScript] Operators

llHoYall 2022. 6. 21. 22:39

The operators of JS are not much different from other languages.

Assignment Operators

  • Assignment: =
  • Addition assignment: +=
  • Subtraction assignment: -=
  • Exponentiation assignment: **=
  • Multiplication assignment: *=
  • Division assignment: /=
  • Remainder assignment: %=
  • Left shift assignment: <<=
  • Right shift assignment: >>=
  • Unsigned right shift assignment: >>>=
  • Bitwise AND assignment: &=
  • Bitwise XOR assignment: ^=
  • Bitwise OR assignment: |=
  • Logical AND assignment: &&=
  • Logical OR assignment: ||=
  • Logical nullish assignment: ??=
    • If the left-hand operand is null or undefined, it is assigned the right-hand operand.

Simply, it performs the operation first and assigns the results.

Let's take some examples.

let op_var1 = 3;
op_var1 += 7;
console.log(`${op_var1}`); // 10
op_var1 *= 2;
console.log(`${op_var1}`); // 20
op_var1 /= 5;
console.log(`${op_var1}`); // 4

let op_var2;
op_var2 ??= 5;
console.log(`${op_var2}`); // 5

Comparison Operators

These operators return a boolean value.

  • Equal: ==
  • Not equal: !=
  • Strict equal: ===
  • Strict not equal: !==
  • Greater than: >
  • Greater than or equal: >=
  • Less than: <
  • Less than or equal: <=

Here are some examples.

console.log(`${3 == '3'}`); // true
console.log(`${3 != 4}`); // true
console.log(`${3 === '3'}`); // false
console.log(`${5 > 7}`); // false
console.log(`${5 <= 7}`); // true

Arithmetic Operators

  • Remainder: %
  • Increment: ++
  • Decrement: --
  • Unary negation: -
  • Unary plus: +
  • Exponentiation operator: **

Here are some examples.

console.log(`${7 % 3}`); // 1
console.log(`${2 ** 3}`); // 8

let preInc_var = 3;
preInc_var = ++preInc_var + 1;
console.log(`${preInc_var}`); // 5

let postInc_var = 3;
postInc_var = postInc_var++ + 1;
console.log(`${postInc_var}`); // 4

let preDec_var = 3;
preDec_var = --preDec_var + 1;
console.log(`${preDec_var}`); // 3

let postDec_var = 3;
postDec_var = postDec_var-- + 1;
console.log(`${postDec_var}`); // 4

Bitwise Operators

  • Bitwise AND: &
  • Bitwise OR: |
  • Bitwise XOR: ^
  • Bitwise NOT: ~
  • Left shift: <<
  • Sign-propagation right shift: >>
  • Zero-fill right shift: >>>

Actually, I'm a firmware engineer, so it is familiar to me. Some people don't feel like this but don't be disappointed.

If you are a web developer, you wouldn't use these operators not so much. It might not be used at all.

Just see some examples.

console.log(`${9 & 1}`);
// 1 (b0001) <- (b1001 & b0001)
console.log(`${1 | 4}`);
// 5 (b0101) <- (b0001 | b0100)
console.log(`${3 << 1}`);
// 6 (b0110) <- (b0011 << 1)
console.log(`${7 >> 2}`);
// 1 (b0001) <- (b0111 >> 2)

Logical Operators

  • Logical AND: &&
    • if all operands are true, the result is true. If one or more operators are false, the result is false.
  • Logical OR: ||
    • if all operands are false, the result is false. If one or more operators are true, the result is true.
  • Logical NOT: !
    • if the operand is true, the result is false. Otherwise, the result is true.

Operands can be expressions.

These characteristics can be used to create a short-circuit evaluation.

In the case of the logical AND operator, if the first operand is false the result is false without evaluating the remaining operand. The same goes for the logical OR operator.

 

There is a nullish coalescing operator.

If the first operand is nullish (i.e. null or undefined), the second operand is returned.

console.log(`${null ?? 3}`); // 3
console.log(`${7 ?? 3}`); // 7

String Operators

  • Concatenation: +
    • If one of the operands is a string, all operands would be converted with a string and concatenated.
console.log(`${'Hello' + ' JavaScript'}`);
// Hello JavaScript

Conditional (Ternary) Operator

condition ? value1 : value2

If the condition is true, it returns value1. Otherwise, it returns value2.

console.log(`${true ? 3 : 6}`); // 3
console.log(`${false ? 3 : 6}`); // 6

Comma / Sequence Operator

This operator simply evaluates from the left operand in order and returns the evaluation result of the last operand.

This operator is sometimes used inside a for loop, to allow multiple variables to be updated each time through the loop.

const x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
const a = [x, x, x, x, x];

for (let i = 0, j = 9; i < j; ++i, --j) {
  console.log(`a[${i}][${j}] = ${a[i][j]}`);
}
// a[0][9] = 9
// a[1][8] = 8
// a[2][7] = 7
// a[3][6] = 6
// a[4][5] = 5

Unary Operators

delete

This operator deletes an object's property. If the delete operator succeeds, it removes the property from the object. Trying to access it afterward will yield undefined. The delete operator returns true if the operation is possible; it returns false if the operation is not possible.

let rect = { width: 3, height: 5 };
delete rect.width;
console.log(`${rect.width}`);
// undefined

typeof

This operator returns a string indicating the type of the unevaluated operand. An operand can be the string, variable, keyword, or object for which the type is to be returned. The parentheses are optional.

The possible results are 'boolean', 'function', 'number', 'object', 'string', 'symbol', and 'undefined'.

const test_var = 'This is a test string.';
console.log(`${typeof test_var}`);
// string

void

This operator specifies an expression to be evaluated without returning a value. The parentheses surrounding the expression are optional, but using them is a good style.

console.log(`${void([] == {})}`);
// undefined

Relational Operators

in

This operator returns true if the specified property is in the specified object.

const car = { tire: 4, handle: 1 };
console.log(`${'tire' in car}`);
// true
console.log(`${'wing' in car}`);
// false

instanceof

This operator returns true if the specified object is of the specified object type.

const arr_var = [1, 2, 3];
console.log(`${arr_var instanceof Array}`); // true
console.log(`${arr_var instanceof Date}`); // false

Other Operators

grouping operator: ( )

This operator controls the precedence of evaluation in expressions.

console.log(`${7 * (2 + 3)}`);
// 35 <- 7 * (5)

new

This operator is used when creating an instance of object types.

const today = new Date()
console.log(`${today}`);

Operator Precedence

If you remember this table, it may be helpful to you. But that is not recommended. Just understand this table.

Good code is a code that is able to predict results without having to refer to this table.

Please make the code clear using the grouping operator.

Precedence Operator Type Individual Operators Associativity
19 Grouping ( )  
18 Member access .
Computed member access [ ]
with argument list new  
Function call ( )
Optional chaining ?.
17 without argument list new
16 Postfix increment / decrement ++  --  
16 Logical / Bitwise NOT !  ~
Unary plus / negation +  -
Prefix increment / decrement ++  --
  typeof void delete await
14 Exponentiation **
13 Multiplcation / Division / Remainder *  /  %
12 Addition / Subtraction +  -
11 Bitwise shift <<  >>  >>>
10 Comparison <  <=  >  >=
  in  instanceof
9 Comparison ==  !=  ===  !==
8 Bitwise AND &
7 Bitwise XOR ^
6 Bitwise OR |
5 Logical AND &&
4 Logical OR ||
3 Conditional (ternary) operator ? :
2 Assignment =  +=  -=  **=  *=  /=  %=
<<=  >>=  >>>=
&=  ^=  |=  &&=  ||=
??=
  yield  yield*
1 Comma / Sequence ,

Please refer to the below link.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#Table