Reputation: 4423
Observing strange behavior in my map function:
let tpl = ({x}, y = `This is ${x}`) => y;
console.log( tpl({x:5}) ); //correctly returns 'This is 5'
console.log( [{x:1}, {x:9}].map(tpl) ); //expecting array of strings, instead get [0, 1]
It is possible to 'fix' this by omitting default variable y
, and returning the template string directly from tpl. However, I would prefer to do the initialization this way and can't understand why it wouldn't still work.
Seems like a strange anomaly to me, does someone have insight on something I am missing?
Upvotes: 1
Views: 2336
Reputation: 463
Your tpl function is provided (value, index, array)
by JavaScript's map Array method. You've given y
a default value of This is ${x}
. But when you pass tpl
as the callback to map
, y
is not undefined so the default value is not used. map
is passing the index to your y
parameter.
let tpl = ({x}, y = `This is ${x}`) => y
const arr = [ {x:1}, {x:9} ];
arr.map(tpl) // [0, 1]
arr.map((value, index, array) => tpl(value)) // [ 'This is 1', 'This is 9' ]
Upvotes: 3