논리 연산자 중 '!'연산자에 대해서는 다들 잘 알고 있을 것이다. not의 의미를 가지는 이 연산자는 결과값에 대한 반대값을 반환한다. 그렇다면 그 not의 not이면 어떻게 될까? 결과는 변화없이 똑같이 반환 될 것이다. 그렇다면 어째서 '!!'를 사용하는 것인지 이번 글에서 설명하고자 한다.
영어로는 double exclamation라고 불리는 이 연산자는 한국에서는 느낌표 두 개 연산자라고 불린다. 이 연산자는 데이터를 boolean으로 명시적인 형변환을 하기 위해서 사용된다.
이 연산자를 유용하게 사용할 수 있는 경우를 예시를 들어 설명해 보도록 하겠다. 우리가 자바스크립트 로직을 구현할 때, 전해받은 데이터에 대한 null체크를 진행하려고 한다. 근데 전해받은 데이터가 비어있을 때 그값이 null인지 undefined인지 또는 그 데이터가 "", "null", "undefined"인지 확신이 없을 때 이 느낌표 두 개 연산자를 사용하면 boolean타입으로 변환해서 null체크를 진행할 수 있다.
예제를 보면서 확인해 보자.
var test1; //undefined
console.log("test1 : " + test1);
console.log("!test1 : " + !test1);
console.log("!test1 : " + !!test1);
console.log("");
var test2 = true; //boolean
console.log("test2 : " + test2);
console.log("!test2 : " + !test2);
console.log("!test2 : " + !!test2);
console.log("");
var test3 = null; //null
console.log("test3 : " + test3);
console.log("!test3 : " + !test3);
console.log("!test3 : " + !!test3);
console.log("");
var test4 = "" ; //""
console.log("test4 : " + test4);
console.log("!test4 : " + !test4);
console.log("!test4 : " + !!test4);
결과값은 다음과 같다.
test1 : undefined
!test1 : true
!test1 : false
test2 : true
!test2 : false
!test2 : true
test3 : null
!test3 : true
!test3 : false
test4 :
!test4 : true
!test4 : false
이렇게 빈 값을 체크할 때에 고려해야할 데이터 타입들을 모두 false로 넘겨 받을 수가 있다.
https://ifuwanna.tistory.com/278#:~:text=%EC%98%88%EC%83%81%EB%8C%80%EB%A1%9C%20%EC%A1%B0%EA%B1%B4%EB%AC%B8%EC%97%90%EC%84%9C%EB%8A%94%20%EA%B8%B0%EC%A1%B4,Conversion)%ED%95%98%EA%B8%B0%20%EC%9C%84%ED%95%B4%20%EC%82%AC%EC%9A%A9%ED%95%A9%EB%8B%88%EB%8B%A4.
https://penguingoon.tistory.com/178