Skip to content
Advertisement

Why can I use comma at the end of the line in the following callback function inside the map function?

In javascript, I thought we aren’t allowed to end the line with comma if we were inside a closure. Why is the following code snippet an exception?

And why does it not work if I put a comma after k.c = 'asd'?

let kk = [
{ a: 'asd', b: 'ddd' }, 
{ a: 'hhh', b: 'dsd' }
];

kk = kk.map(k => {
  k.a = 'new',
    k.b = 'new1',
    k.c = 'asd'
  return k
})

console.log(kk)

Advertisement

Answer

The following is an expression, with two uses of the comma operator:

k.a = 'new', k.b = 'new1', k.c = 'asd'

(the trailing semi-colon is optional in JavaScript).

This, however, is a statement:

return k

You can’t combine an expression and a statement with the comma operator.

NB: this code should use .forEach rather than .map. You should only use the latter when you’re returning new objects, rather than mutating in place.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement