Search code examples
javascriptarraysfunctionforeacharrow-functions

ternary operator inside an arrow function inside forEach


I have this little function that is supposed to remove object properties with even values.

function removeEvenValues(obj) {
  Object.keys(obj).forEach(k => ((!isNaN(obj[k])) && (obj[k] % 2 === 0)) ? delete obj[k] : k);
}

In the else {} part of the ternary operator, how do I leave it empty like in an if (true){ doSomething();} kind of construct? Or does it even make sense to use a fat arrow function in this case?


Solution

  • Yes, you shouldn't use a concise arrow function or a ternary operator here. Well, you could use && instead of the ternary, but you really shouldn't.

    You shouldn't even use forEach in ES6 - just use a proper loop:

    function removeEvenValues(obj) {
      for (const k of Object.keys(obj))
        if (!isNaN(obj[k]) && obj[k] % 2 === 0)
          delete obj[k];
    }
    

    or (as you probably don't care about inherited properties)

    function removeEvenValues(obj) {
      for (const k in obj)
        if (!isNaN(obj[k]) && obj[k] % 2 === 0)
          delete obj[k];
    }