Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ESLint error no-unneeded-ternary

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...

like image 532
Primoz Rome Avatar asked Feb 29 '16 14:02

Primoz Rome


People also ask

How do I stop nested ternary?

Use an ESLint rule If you use ESLint in your project, you can use this rule to disallow nested ternary expressions.

What is nested ternary operator?

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 ? (

What is the format of conditional operator?

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.


1 Answers

You don't need a ternary when a simple val || defaultVal will do.

like image 89
Dave Newton Avatar answered Sep 21 '22 03:09

Dave Newton