자바스크립트 연산자의 대부분은 다른 언어와 유사하다. 몇 가지 주의해야 할 연산자들에 대해서 간단히 살펴보자.
+ 연산자
- 더하기 연산
- 문자열 연결 연산
- 두 연산자가 모두 숫자일 경우에만 더하기 연산이 수행되고, 나머지는 문자열 연결 연산이 수행된다.
let add1 = 1 + 2;
let add2 = "my " + "string";
let add3 = 1 + "string";
let add4 = "string" + 2;
console.log(add1); // 3
console.log(add2); // my string
console.log(add3); // 1string
console.log(add4); // string2
typeof 연산자
- 피연산자의 타입을 문자열 형태로 리턴한다.
// 숫자 타입
let intNum = 10;
let floatNum = 0.1;
// 문자열 타입
let singleChar = "a";
// 불린 타입
let boolVar = true;
// undefined 타입
let emptyVar;
// null 타입
let nullVar = null;
console.log(
typeof intNum, // number
typeof floatNum, // number
typeof singleChar, // string
typeof boolVar, // boolean
typeof emptyVar, // undefined
typeof nullVar // object
);
==(동등) 연산자와 ===(일치) 연산자
- == : 자료형 비교(x), 값만 비교(o)
- === : 자료형 비교(o) + 값 비교(o)
!! 연산자
- 피연산자를 불린값으로 변환한다.
- 객체는 값이 비어있는 빈 객체라도 true로 변환된다.
console.log(!!0); // false
console.log(!!1); // true
console.log(!!'string'); // true
console.log(!!''); // false
console.log(!!true); // true
console.log(!!false); // false
console.log(!!null); // false
console.log(!!undefined); // false
console.log(!!{}); // true
console.log(!![1,2,3]); // true
null 병합 연산자
- 왼쪽 값이 null 혹은 undefined인 경우 오른쪽 값을 반환한다.
'??'와 '||'의 차이
왼쪽 값이 null 혹은 undefined의 경우 OR 연산자와 똑같이 동작한다.
console.log(null || 100) // 100
console.log(null ?? 100) // 100
console.log(undefined || 200) // 200
console.log(undefined ?? 200) // 200
하지만 null과 undefined를 제외한 false로 평가되는 모든 값의 경우 OR 연산자는 오른쪽 값을 반환하지만
null 병합 연산자의 경우 왼쪽 값을 반환하게 된다.
console.log(0 || 100)
console.log(0 ?? 100)
console.log(false || 200)
console.log(false ?? 200)
console.log("" || 200)
console.log("" ?? 200) // 빈 문자열이라 출력 결과가 없음
100
0
200
false
200
따라서 null 과 undefined만 체크하고 싶은 경우 null 병합 연산자를 사용하면 되고
false로 평가되는 모든 값을 체크하고 싶은 경우 OR 연산자를 사용하면 된다.