The list processing routine map
on an array object is very convenient at times. Here's one of the handy ways to use it:
var numarr = [1,2,3,4];
console.log(numarr.map(String))
>>> ["1", "2", "3", "4"]
I took this for granted thus far. Today I was however puzzled by it. What the map
function is returning above is an array of strings. We typically pass a function to map
as argument. In above case we pass String
object. String
is implemented inside the Javascript implementation, so I don't know what kind of specialities it has. The above code works as if a new
instance of String
is created for each item in array.
If it's not clear, consider this. If I decide to implement an object in Javascript say MyString
and pass it to map
, I won't get the above behavior.
function MyString(x) { this.val = x; }
MyString.prototype.toString = function () { return String(this.val); };
var ms = new MyString(4)
console.log(String(ms));
>>> "4"
var arr = [1,2,3];
arr.map(MyString)
>>> [undefined, undefined, undefined]
Does anyone know why then arr.map(String) works the way it does?
typeof String
returns? "If I decide to implement an object in Javascript sayMyString
[...]":MyString
is a function too! But it showsundefined
because you are not returning anything form it. – Felix Kling 25 mins ago