JavaScript | 조건문 안에서의 !! 이중 부정 연산자 (느낌표 연산자, ESLint)

AEHEE·2023년 11월 24일
0

JavaScript

목록 보기
10/10
post-thumbnail

지금 프로젝트에서 코딩 규칙을 기반으로한 ESLint를 적용중이다.
String 일 때 값이 있는지 없는지 true false로 체크하려면 느낌표 두개 연산자, 즉 이중 부정연산자 !!를 이용해서 값이 있는지를 명시적으로 체크를 한다.

👩🏻‍💻 !! 이중 부정 연산자

!!를 사용하는 것은 Truthy/Falsy 동작을 명시적으로 표현하기 위함이다.

// someValue가 Boolean을 제외한 나머지 타입이었을 때
const booleanValue = !!someValue;
console.log(booleanValue); // true

조건문을 사용할 경우 이중 부정 연산자를 사용할 필요가 없다.
보통 이중 부정 연산자를 조건문에서 많이 사용한다.

if (!!someValue) {
    // true 일 때
}

근데 지금 프로젝트에서 위와 같이 조건문 코드를 작성 후 저장하면 린트 수정으로 인해 !! 이중 부정 연산자가 사라지길래 문서를 찾아봤다.

In contexts such as an if statement’s test where the result of the expression will already be coerced to a Boolean, casting to a Boolean via double negation (!!) or a Boolean call is unnecessary

/*eslint no-extra-boolean-cast: "error"*/

var foo = !!!bar;

var foo = !!bar ? baz : bat;

var foo = Boolean(!!bar);

var foo = new Boolean(!!bar);

if (!!foo) {
    // ...
}

if (Boolean(foo)) {
    // ...
}

while (!!foo) {
    // ...
}

do {
    // ...
} while (Boolean(foo));

for (; !!foo; ) {
    // ...
}

조건문 안에서는 true / false로 조건이 실행 되기에 이중 부정 연산자가 필요 없다.

참고: https://eslint.org/docs/latest/rules/no-extra-boolean-cast

profile
UI개발자에서 FE개발자로 한걸음 더!

0개의 댓글

관련 채용 정보