Search code examples
javascriptarrow-functionsunexpected-token

Javascript arrow function unexpected token on if condition


Can somebody tell me please what is wrong with this arrow function. It throws me an error

unexpected token on begin of if condition

selected_devices
  .map( device => if( device.device_id === device_id ) device.source = 'included' )

Solution

  • You need {} when you have an if or other things that are not a single statement - also do NOT use map if you want forEach since map creates an unnecessary array you then throw away

    selected_devices
      .forEach(device => device.source = device.device_id === device_id  ? 'included' : device.source)
    

    or perhaps

    selected_devices
      .filter( device => device.device_id === device_id)
      .forEach(device => device.source = 'included')