0

I have this simple code that works. However it feels cheesy and like I am doing something stupid. So is this how I would handle this if I wanted to be in one line?

    let lifeColors = [
        { lives: 1, color: 'lime' },
        { lives: 2, color: 'orange' },
        { lives: 3, color: 'salmon' },
    ]

    let lives = 20;

    let color = (lifeColors.find(x => x.lives === lives) || {color: 'white'}).color;
    console.log(color)

My inspiration was from this post

JS: Handle with find() property undefined

Happy Coconut
  • 973
  • 4
  • 14
  • 33
  • 1
    Maybe `let color = (lifeColors.find(({lives}) => livez === lives))?.color || 'white';` is a bit less "_cheesy_" ..? Note, that I've changed the variable name `lives` to `livez` to prevent the outer variable shadowing inside the function. – Teemu Dec 15 '20 at 20:07
  • hey thanks for the replay. However I get error "livez is not defined" – Happy Coconut Dec 15 '20 at 20:13
  • 1
    Please re-read my comment above. I said I changed the name of the __variable__ ... – Teemu Dec 15 '20 at 20:16
  • Yup I made a mistake. Thanks a lot for this. Have a nice day! – Happy Coconut Dec 15 '20 at 20:18

0 Answers0