3 ms·
Given than in JS an empty string is a falsy value you can go even shorter: items = items.map(x => x.toUpperCase() || `<empty>`)
by mattigames 4y ago
Given than in JS an empty string is a falsy value you can go even shorter:
items = items.map(x => x.toUpperCase() || `<empty>`)
- chii 4y agoThe original ternary "fixes" the cases where `x` is "wrong" (e.g., is not a string - `x.length` does not fail, but evaluates to false, and thus you still get `<empty>`). This even more terser code will fail if `x.toUpperCase()` fails with an exception (such as when x is not a string).
- mattigames 4y agoGiven the example I think it is reasonable to assume it is always an string; otherwise if there is any possibility that x is not a string you can just use optional chaining: items = items.map(x => x?.toUpperCase() || `<empty>`) See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- chii 4y agoGood point. I often forget that there's option chaining in javascript (now-a-days).