ESLint is telling me this error message inside my JS module: error no-unneeded-ternary Unnecessary use of conditional expression for default assignment
The error comes in the get
method on the return
statement return val ? val : defaultVal;
?
import ls from 'local-storage'; export default { get(key, defaultVal = null) { var val = ls(key); return val ? val : defaultVal; }, set(key, val) { return ls(key, val); }, remove(key) { return ls.remove(key); }, };
Any idea why do I get this error message? I have found some resource on ESLint's website regarding this error message here but it applies to boolean expressions and I can not figure out why would that apply to my code...
Use an ESLint rule If you use ESLint in your project, you can use this rule to disallow nested ternary expressions.
Ternary operators can be nested just like if-else statements. Consider the following code: int a = 1, b = 2, ans; if (a == 1) { if (b == 2) { ans = 3; } else { ans = 5; } } else { ans = 0; } printf ("%d\n", ans); Here's the code above rewritten using a nested ternary operator: int a = 1, b = 2, ans; ans = (a == 1 ? (
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
You don't need a ternary when a simple val || defaultVal
will do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With