2

I know the basic of call and array.prototype.map.call() function takes two arguments, the first one is the object context to be used as this is inside the called function and second is the argument list. But in MDN I found an example where array.prototype.map is used via a call method and a string is passed as the first argument.

I want to know how the passed string gets manipulated inside map function. No this keyword inside map function. How does the map know that it is called on a string?

var map = Array.prototype.map;
var a = map.call('Hello World', function(x) { return x.charCodeAt(0); });
3
  • 1
    "No this keyword inside map function." - I think you're confusing the .map() function itself with the function that you pass as an argument to .map(). Commented Jul 8, 2016 at 5:27
  • If you go through the polyfill of Array#map, you will get to know that it deals with while loop considering length of the this and in your case, this is a String which is having length property... Commented Jul 8, 2016 at 5:28
  • Why do you think the map function didn't use its this argument? Commented Jul 8, 2016 at 7:30

1 Answer 1

6

The string gets represented in the following format internally:

String {0: "h", 1: "e", 2: "l", 3: "l", 4: "o", 5: " ", 6: "w", 7: "o", 8: "r", 9: "l", 10: "d", length: 11, [[PrimitiveValue]]: "hello world"}

So when this gets passed to map this is actually treated as an array since it has indices as keys and a length property. Array.prototype.map iterates over it to return the array, invoked on the string you passed in with the Function.prototype.call method.

Try new String('hello world') in the console.

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

Comments

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.