Avoid unnecessary ternary operations that return a boolean

이 페이지는 아직 한국어로 제공되지 않으며 번역 작업 중입니다. 번역에 관한 질문이나 의견이 있으시면 언제든지 저희에게 연락해 주십시오.

Metadata

ID: javascript-best-practices/no-unnecessary-ternary

Language: JavaScript

Severity: Warning

Category: Best Practices

Description

This rule advises against the use of unnecessary ternary operations that return a boolean value. In JavaScript, the ternary operator ? : is a shorthand way of writing an if-else statement. However, if the result of the ternary operation is a boolean (such as true or false), it is often unnecessary because the condition itself already produces a boolean value.

The use of unnecessary ternary operations can lead to code that is harder to read and understand. Furthermore, it can lead to potential bugs if the ternary operation is not correctly written or understood. To adhere to this rule, you should return the condition itself rather than using a ternary operation.

Non-Compliant Code Examples

const foo = bar === 2 ? true : false;
const baz = quux === 3 ? false : true;
const notFoo = foo ? false : true;
call(foo ? foo : 1);

Compliant Code Examples

const foo = bar === 2;
const baz = quux !== 3;
const notFoo = !foo;
call(foo || 1);
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Analysis