31

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
  • 9,694
  • 16
  • 71
  • 98

2 Answers2

84

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

Dave Newton
  • 156,572
  • 25
  • 250
  • 300
  • @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
  • Oh right. my bad. I didn't do the assignments in one case. Thanks! – Umakant Patil Sep 27 '17 at 08:59
17
// Bad
foo(bar ? bar : 1);

// Good
foo(bar || 1);

This is how they say in Es-lint

Charith Jayasanka
  • 2,745
  • 20
  • 35