1

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?

2
  • Why exactly do you prefer to initialize it with y when you can just return the template string directly like you said? Is it because you are sometimes passing in an optional template string to override the default one? Commented Feb 1, 2017 at 4:32
  • This is a sort of contrived example of what I want to do (y for example, could be the result of a function call), but it's mostly about aesthetics; I like the concept of one character returns Commented Feb 1, 2017 at 4:49

1 Answer 1

3

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' ]

Array.prototype.map()

Default parameters

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for this insight - this clarified my confusion.
Awesome, no problem @Conqueror

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.