[Javascript] 연산자(operator)

nxnaxx·2021년 11월 9일
0

javascript

목록 보기
2/14
post-thumbnail

산술 연산자(arithmetic operator)

 산술 연산자(arithmetic operator)는 수학적 계산을 수행해 새로운 숫자 값을 만든다. 산술 연산이 불가능할 경우 NaN을 반환한다.

이항 산술 연산자(binary arithmetic operator)

 이항 산술 연산자(binary arithmetic operator)는 2개의 피연산자를 산술 연산하여 숫자 값을 만드는데, 값이 바뀌는 경우는 없고 언제나 새로운 값을 만든다.

// binary arithmetic operator
5 + 2; // 7
4 - 1; // 3
8 * 2; // 16
9 / 5; // 1.8
3 % 2; // 1

단항 산술 연산자(unary arithmetic operator)

 단항 산술 연산자(unary arithmetic operator)는 1개의 피연산자를 산술 연산하여 숫자 값을 만든다. 이항 산술 연산자와 달리 ++/-- 연산자는 피연산자의 값을 변경하는 부수 효과가 있다.

// unary arithmetic operator
var x = 2;

// 선할당 후증가(postfix increment operator)
postfIn = x++;
console.log(postfIn, x);

// 선증가 후할당(prefix increment operator)
prefIn = ++x;
console.log(prefIn, x);

// 선할당 후감소(postfix decrement operator)
postfDe = x--;
console.log(postfDe, x);

// 선감소 후할당(prefix decrement operator)
prefDe = --x;
console.log(prefDe, x);

[실행결과]
2 3
4 4
4 3
2 2


숫자 타입이 아닌 피연산자에 +/- 단항 연산자를 사용하면 피연산자를 숫자 타입으로 변환해 반환한다. 부수효과는 없다.

// unary plus
// string -> number (O)
var plusA = '5';
console.log(+plusA);

// string -> number (X)
var plusStr = 'blue';
console.log(+plusStr);

// boolean -> number
var plusB = true;
var plusC = false;
console.log(+plusB);
console.log(+plusC);

[실행결과]
5
NaN
1
0


- 단항 연산자는 피연산자의 부호를 반전한 값을 반환하기도 한다.

// unary minus
console.log(-8);

// string -> number (O)
var minusA = '5';
console.log(-minusA);

// string -> number (X)
var minusStr = 'red';
console.log(-minusStr);

// boolean -> number
var minusB = true;
var minusC = false;
console.log(-minusB);
console.log(-minusC);

[실행결과]
-8
-5
NaN
-1
-0


+ 연산자는 피연산자 중 하나 이상이 문자열인 경우 문자열 연결 연산자로 동작하며, 그 외의 경우는 산술 연산자로 동작한다.

// implicit coercion
// string connection
strConnect = '2' + 5;

console.log(strConnect);
console.log(typeof strConnect);

// boolean + number
console.log(1 + true);
console.log(1 + false);

// null + number
console.log(1 + null);

// undefined + number
console.log(1 + undefined);

[실행결과]
25
string
2
1
1
NaN

📌 true, false, null은 각각 1, 0, 0으로 타입 변환된다. 그러나 undefined는 숫자로 타입 변환되지 않는다. 이를 암묵적 타입 변환(implicit coercion) 또는 타입 강제 변환(type coercion)이라고 한다.


할당 연산자(assignment operator)

 할당 연산자(assignment operator)는 우항에 있는 피연산자의 평가 결과를 좌항에 있는 변수에 할당한다. 부수 효과가 있다.

var x;

x = 5;
console.log(x);

x += 5;
console.log(x);

x -= 5;
console.log(x);

x *= 5;
console.log(x);

x /= 5;
console.log(x);

x %= 5;
console.log(x);

var str = 'My favorite perfume is ';

str += 'Acqua di parma.';
console.log(str);

[실행결과]
5
10
5
25
5
0
My favorite perfume is Acqua di parma.

비교 연산자(comparison operator)

 비교 연산자(comparison operator)는 좌항과 우항의 피연산자를 비교한 후 결과를 boolean값으로 반환한다.

동등 비교(loose equality)와 일치 비교(strict equality) 연산자

 좌항과 우항의 피연산자가 같은 값으로 평가되는지 비교하여 boolean값을 반환한다. 동등 비교 연산자는 느슨한 비교, 일치 비교 연산자는 엄격한 비교를 한다.

동등 비교(==) 연산자는 좌항과 우항의 피연산자를 비교할 때 암묵적 타입 변환을 통해 타입을 일치시킨 후 같은 값인지 비교한다. 편리하지만 결과를 예측하기 어렵고 실수하기 쉬워 사용하지 않는 편이 좋다.

// loose equality
5 == 5; // true
5 == '5'; // true

일치 비교(===) 연산자는 좌항과 우항의 피연산자가 타입도 같고 값도 같은 경우에 한해서만 true를 반환한다.

// strict equality
5 === 5; // true
5 === '5'; // false

📌 주의해야 할 점
NaN은 자신과 일치하지 않는 유일한 값이기 때문에 숫자가 NaN인지 조사하려면 함수 isNaN을 사용해야 한다.

// NaN
NaN === NaN; // false

isNaN(NaN); // true
isNaN(10); // false
isNaN(1 + undefined); // true

양의 0과 음의 0을 비교하면 true를 반환한다.

// zero
0 === -0; // true
0 == -0; // true

📝 Object.is 메서드를 사용하면 예측 가능한 정확한 비교 결과를 반환한다.

// object.is method
Object.is(-0, +0); // false
Object.is(NaN, NaN); // true

부동등 비교 연산자(!=)와 불일치 비교 연산자(!==)는 각각 동등 비교(==), 일치 비교(===) 연산자의 반대 개념이다.

5 != 8; // true
5 != 5; // false
5 != '5'; // false

5 !== 8; // true
5 !== 5; // false
5 !== '5'; // true
// inequality
5 > 2; // true
5 > 5; // false
5 >= 5; // true
5 <= 5; // true

대소 관계 비교 연산자

 대소 관계 비교 연산자는 피연산자의 크기를 비교하여 boolean 값을 반환한다.

// inequality
5 > 2; // true
5 > 5; // false
5 >= 5; // true
5 <= 5; // true

삼항 조건 연산자(ternary operator)

 삼항 조건 연산자(ternary operator)는 조건식의 평가 결과에 따라 반환할 값을 결정한다. 물음표(?) 앞의 조건식은 boolean 타입의 값으로 평가될 표현식이며 true로 평가되면 두 번째 피연산자를 반환하고 false로 평가되면 세 번째 피연산자를 반환한다.

var x = 5;
var result = x % 2 ? '홀수' : '짝수';

console.log(result);

[실행결과]
홀수

삼항 조건 연산자 표현식은 값으로 평가할 수 있는 표현식인 문이다.


논리 연산자(logical operator)

 논리 연산자(logical operator)는 우항과 좌항의 피연산자를 논리 연산한다.

// OR operator
true || true; // true
true || false; // true
false || false; // false

// AND operator
true && true; // true
true && false; // false
false && false; // false

// NOT operator
!true; // false
!false; // true

논리 부정(!) 연산자는 언제나 boolean값을 반환하는데, 피연산자가 boolean값이 아닐 경우 boolean 타입으로 암묵적 타입 변환된다.

// implicit coercion
!0; // true
!'carrot'; // false

논리합(||) 또는 논리곱(&&) 연산자 표현식의 평가 결과는 boolean 값이 아닐 수도 있다. 언제나 2개의 피연산자 중 어느 한쪽으로 평가된다. (단축평가)

// short-circuit evaluation
'Dog' && 'Cat'; // Cat

쉼표 연산자(comma operator)와 그룹 연산자(group operator)

 쉼표(,) 연산자(comma operator)는 왼쪽 피연산자부터 차례로 평가하고 마지막 평가가 끝나면 마지막 피연산자의 평가 결과를 반환한다.

// comma operator
var x, y, z;

x = 1, y = 2, z = 3; // 3

 그룹 연산자(group operator)는 소괄호('()')로 피연산자를 감싸고 그것을 가장 먼저 평가한다. 그룹 연산자를 사용하면 연산자의 우선순위를 조절할 수 있다.

// group operator
console.log(10 * 3 + 5);
console.log(10 * (3 + 5));

[실행결과]
35
80

typeof 연산자

 typeof 연산자는 피연산자의 data 타입을 7가지 문자열 "string", "number", "boolean", "undefined", "symbol", "object", "function" 중 하나로 반환한다. "null"을 반환하는 경우는 없으며, 함수의 경우 "function"을 반환한다. typeof 연산자가 반환하는 문자열은 7가지 data 타입과 정확히 일치하지는 않는다.

// typeof operator
typeof '' // string
typeof 1 // number
typeof NaN // number
typeof true // boolean
typeof undefined // undefined
typeof Symbol() // symbol
typeof null // object
typeof [] // object
typeof {} // object
typeof new Date() // object
typeof /test/gi // object
typeof function () {} // function

📌 typeof 연산자로 null 값을 연산하면 "object"를 반환하므로 값이 null 타입인지 확인할 때는 일치 연산자(===)를 사용한다.

// typeof null
var sample = null;

typeof sample === null; // false
sample === null; // true

지수 연산자(exponent operator)

 지수 연산자(exponent operator)는 좌항의 피연산자를 밑으로, 우항의 피연산자를 지수로 거듭 제곱하여 숫자 값을 반환한다.

// exponent operator
2 ** 2; // 4
2 ** 2.5; // 5.65685424949238
2 ** 0; // 1
2 ** -4; // 0.0625

지수 연산자가 도입되기 전에는 Math.pow 메서드를 사용했다.

// Math.pow method
Math.pow(2, 2); // 4
Math.pow(2, 2.5); // 5.65685424949238

다음과 같은 경우 Math.pow 메서드보다 지수 연산자가 가독성이 좋다.

2 ** 2 ** 2; // 16
Math.pow(Math.pow(2, 2), 2); // 16

음수를 거듭 제곱의 밑으로 사용하려면 괄호로 묶어야 한다.

(-3) ** 2; // 9

지수 연산자는 할당 연산자와 함께 사용할 수 있고 이항 연산자 중에서 우선순위가 가장 높다.

var num = 7;
num **= 2;
console.log(num);

console.log(2 * 5 ** 3);

[실행결과]
49
250

0개의 댓글