]> git.proxmox.com Git - pve-eslint.git/blame - eslint/docs/src/rules/no-unneeded-ternary.md
import 8.41.0 source
[pve-eslint.git] / eslint / docs / src / rules / no-unneeded-ternary.md
CommitLineData
8f9d1d4d
DC
1---
2title: no-unneeded-ternary
8f9d1d4d
DC
3rule_type: suggestion
4related_rules:
5- no-ternary
6- no-nested-ternary
7---
8
9
eb39fafa
DC
10
11It's a common mistake in JavaScript to use a conditional expression to select between two Boolean values instead of using ! to convert the test to a Boolean.
12Here are some examples:
13
14```js
15// Bad
16var isYes = answer === 1 ? true : false;
17
18// Good
19var isYes = answer === 1;
20
eb39fafa
DC
21// Bad
22var isNo = answer === 1 ? false : true;
23
24// Good
25var isNo = answer !== 1;
26```
27
28Another common mistake is using a single variable as both the conditional test and the consequent. In such cases, the logical `OR` can be used to provide the same functionality.
29Here is an example:
30
31```js
32// Bad
33foo(bar ? bar : 1);
34
35// Good
36foo(bar || 1);
37```
38
39## Rule Details
40
41This rule disallow ternary operators when simpler alternatives exist.
42
43Examples of **incorrect** code for this rule:
44
8f9d1d4d
DC
45::: incorrect
46
eb39fafa
DC
47```js
48/*eslint no-unneeded-ternary: "error"*/
49
50var a = x === 2 ? true : false;
51
52var a = x ? true : false;
53```
54
8f9d1d4d
DC
55:::
56
eb39fafa
DC
57Examples of **correct** code for this rule:
58
8f9d1d4d
DC
59::: correct
60
eb39fafa
DC
61```js
62/*eslint no-unneeded-ternary: "error"*/
63
64var a = x === 2 ? "Yes" : "No";
65
66var a = x !== false;
67
68var a = x ? "Yes" : "No";
69
70var a = x ? y : x;
71
72f(x ? x : 1); // default assignment - would be disallowed if defaultAssignment option set to false. See option details below.
73```
74
8f9d1d4d
DC
75:::
76
eb39fafa
DC
77## Options
78
79This rule has an object option:
80
81* `"defaultAssignment": true` (default) allows the conditional expression as a default assignment pattern
82* `"defaultAssignment": false` disallows the conditional expression as a default assignment pattern
83
84### defaultAssignment
85
86When set to `true`, which it is by default, The defaultAssignment option allows expressions of the form `x ? x : expr` (where `x` is any identifier and `expr` is any expression).
87
88Examples of additional **incorrect** code for this rule with the `{ "defaultAssignment": false }` option:
89
8f9d1d4d
DC
90::: incorrect
91
eb39fafa
DC
92```js
93/*eslint no-unneeded-ternary: ["error", { "defaultAssignment": false }]*/
94
95var a = x ? x : 1;
96
97f(x ? x : 1);
98```
99
8f9d1d4d
DC
100:::
101
eb39fafa
DC
102Note that `defaultAssignment: false` still allows expressions of the form `x ? expr : x` (where the identifier is on the right hand side of the ternary).
103
104## When Not To Use It
105
106You can turn this rule off if you are not concerned with unnecessary complexity in conditional expressions.