[JavaScript] 기본연산자 ( +, -, *, /, **, % )와 연산자 우선순위

JavaScript 연산자

JavaScript에서 많이 사용되는 기본적인 연산자들에 대해 알아보려고 한다.

+

의경우 숫자+숫자 연산시 숫자 결과값을 반환한다. 

반면에 숫자+문자열(숫자)인경우 두 숫자를 계산하지 못하고 결과값으로 문자열을 반환한다.

ex)
5 + 5 = 10
5 + '5' = 55



숫자형이 아닌 피연산자에 +를 붙여주면 숫자형으로 변화한다.

ex1)
+true => 1
+'' => 0
+'가나다' => NaN 

ex2)
let stringNum1 = '2';
let stringNum2 = '3';

stringNum1+stringNum2 = '23';
(+stringNum1)+(+stringNum2) = 5;  또는 +stringNum1 + +stringNum2 = 5; 처럼 연산자와의 간격을 줘도 계산이 가능해진다.

이렇게 말고도 Number(...)를 사용해도 문자열타입의 숫자를 숫자로 형변환이 가능하다.
Number(stringNum1)+Number(stringNum2) = 5;





-, *, /, **, %


-      마이너스 연산자

*      곱하기 연산자

/      나누기 연산자

**    거듭제곱 연산자

%    나머지 연산자


아래 예제는 + 연산자와 같이 몇가지 알아두면 좋을만한 위 연산자들의 특성

ex)
5 - 5 = 0
5 - '5' = 0

5 * 5 = 25
5 * '5' = 25

4 % 3 = 1
4 % '3' = 1

3 * '가' = NaN
3 * 'apple' = NaN
3+'3'+3+'3' - 1 = 3332



연산자 우선순위

하나의 표현식에 둘 이상의 연산자가 있는 경우, 실행 순서는 연산자의 우선순위에 의해 결정된다. 

하지만 이러한 연산자 우선순위를 무력화 시킬 수 있는 방법이 있다. 

(...)를 사용하면 자바스크립트에서 정의한 연산자 우선순위를 무력화 시킬 수 있다.

Precedence

Operator type

Associativity

Individual operators

21

Grouping

n/a

( … )

20

Member Access

left-to-right

… . …


Computed Member Access

left-to-right

… [ … ]


new (with argument list)

n/a

new … ( … )


Function Call

left-to-right

… ( … )


Optional chaining

left-to-right

?.

19

new (without argument list)

right-to-left

new …

18

Postfix Increment

n/a

… ++


Postfix Decrement


… --

17

Logical NOT (!)

right-to-left

! …


Bitwise NOT (~)


~ …


Unary plus (+)


+ …


Unary negation (-)


- …


Prefix Increment


++ …


Prefix Decrement


-- …


typeof


typeof …


void


void …


delete


delete …


await


await …

16

Exponentiation (**)

right-to-left

… ** …

15

Multiplication (*)

left-to-right

… * …


Division (/)


… / …


Remainder (%)


… % …

14

Addition (+)

left-to-right

… + …


Subtraction (-)


… - …

13

Bitwise Left Shift (<<)

left-to-right

… << …


Bitwise Right Shift (>>)


… >> …


Bitwise Unsigned Right Shift (>>>)


… >>> …

12

Less Than (<)

left-to-right

… < …


Less Than Or Equal (<=)


… <= …


Greater Than (>)


… > …


Greater Than Or Equal (>=)


… >= …


in


… in …


instanceof


… instanceof …

11

Equality (==)

left-to-right

… == …


Inequality (!=)


… != …


Strict Equality (===)


… === …


Strict Inequality (!==)


… !== …

10

Bitwise AND (&)

left-to-right

… & …

9

Bitwise XOR (^)

left-to-right

… ^ …

8

Bitwise OR (|)

left-to-right

… | …

7

Logical AND (&&)

left-to-right

… && …

6

Logical OR (||)

left-to-right

… || …

5

Nullish coalescing operator (??)

left-to-right

… ?? …

4

Conditional (ternary) operator

right-to-left

… ? … : …

3

Assignment

right-to-left

… = …




… += …




… -= …




… **= …




… *= …




… /= …




… %= …




… <<= …




… >>= …




… >>>= …




… &= …




… ^= …




… |= …




… &&= …




… ||= …




… ??= …

2

yield

right-to-left

yield …


yield*


yield* …

1

Comma / Sequence

left-to-right

… , …







댓글