]> git.proxmox.com Git - pve-eslint.git/blame - eslint/docs/rules/no-unneeded-ternary.md
bump version to 8.4.0-3
[pve-eslint.git] / eslint / docs / rules / no-unneeded-ternary.md
CommitLineData
eb39fafa
DC
1# disallow ternary operators when simpler alternatives exist (no-unneeded-ternary)
2
3It'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.
4Here are some examples:
5
6```js
7// Bad
8var isYes = answer === 1 ? true : false;
9
10// Good
11var isYes = answer === 1;
12
13
14// Bad
15var isNo = answer === 1 ? false : true;
16
17// Good
18var isNo = answer !== 1;
19```
20
21Another 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.
22Here is an example:
23
24```js
25// Bad
26foo(bar ? bar : 1);
27
28// Good
29foo(bar || 1);
30```
31
32## Rule Details
33
34This rule disallow ternary operators when simpler alternatives exist.
35
36Examples of **incorrect** code for this rule:
37
38```js
39/*eslint no-unneeded-ternary: "error"*/
40
41var a = x === 2 ? true : false;
42
43var a = x ? true : false;
44```
45
46Examples of **correct** code for this rule:
47
48```js
49/*eslint no-unneeded-ternary: "error"*/
50
51var a = x === 2 ? "Yes" : "No";
52
53var a = x !== false;
54
55var a = x ? "Yes" : "No";
56
57var a = x ? y : x;
58
59f(x ? x : 1); // default assignment - would be disallowed if defaultAssignment option set to false. See option details below.
60```
61
62## Options
63
64This rule has an object option:
65
66* `"defaultAssignment": true` (default) allows the conditional expression as a default assignment pattern
67* `"defaultAssignment": false` disallows the conditional expression as a default assignment pattern
68
69### defaultAssignment
70
71When 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).
72
73Examples of additional **incorrect** code for this rule with the `{ "defaultAssignment": false }` option:
74
75```js
76/*eslint no-unneeded-ternary: ["error", { "defaultAssignment": false }]*/
77
78var a = x ? x : 1;
79
80f(x ? x : 1);
81```
82
83Note that `defaultAssignment: false` still allows expressions of the form `x ? expr : x` (where the identifier is on the right hand side of the ternary).
84
85## When Not To Use It
86
87You can turn this rule off if you are not concerned with unnecessary complexity in conditional expressions.
88
89## Related Rules
90
91* [no-ternary](no-ternary.md)
92* [no-nested-ternary](no-nested-ternary.md)