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); });
Paul Floyd
  • 5,530
  • 5
  • 29
  • 43
AL-zami
  • 8,902
  • 15
  • 71
  • 130
  • 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()`. – nnnnnn Jul 08 '16 at 05: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... – Rayon Jul 08 '16 at 05:28
  • Why do you think the `map` function didn't use its `this` argument? – Bergi Jul 08 '16 at 07:30

1 Answers1

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.

JaKXz
  • 1,665
  • 1
  • 14
  • 34
Piyush.kapoor
  • 6,715
  • 1
  • 21
  • 21