36

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

Primoz Rome
  • 10,379
  • 17
  • 76
  • 108

2 Answers2

94

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

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
  • @UmakantPatil Those aren't equivalent. – Dave Newton Sep 13 '17 at 10:19
  • 1
    @UmakantPatil Once you make them actually do the same thing the differences are (a) browser-dependent, and (b) within 1-3%. It's also shorter and clearer; unless you're in a very tight game loop or similar it's a pointless micro-optimization. In any case, the original question was regarding the ESLint warning which defaults to flagging ternaries in default value assignments. ¯\(°_o)/¯ – Dave Newton Sep 13 '17 at 15:31
  • 1
    Oh right. my bad. I didn't do the assignments in one case. Thanks! – Umakant Patil Sep 27 '17 at 08:59
  • Is using a `??` over `||` a better practice? – Tanishq Vyas Jan 18 '23 at 06:05
  • @TanishqVyas :shrug: `??` wasn’t a useful option when the answer was written. I’d say `??` is likely better but I usually forget it’s there :) – Dave Newton Jan 18 '23 at 11:43
  • @DaveNewton Thanks for the reply. I wanted to know about a better practice since `??` would check for nullish values whereas `||` may also trigger when the value is falsy. So, as per the case it should boil down to choosing between nullish or falsy values right? Please correct me if I have a wrong understanding. – Tanishq Vyas Jan 19 '23 at 04:53
20
// Bad
foo(bar ? bar : 1);

// Good
foo(bar || 1);

This is how they say in Es-lint

Charith Jayasanka
  • 4,033
  • 31
  • 42