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