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?
Update: A comment I added below clarifies my question better.
typeof Stringreturns? "If I decide to implement an object in Javascript sayMyString[...]":MyStringis a function too! But it showsundefinedbecause you are not returning anything form it.MyString?Stringis a construtor function which returns a string object when it is called withnew, it returns a string primitive value when it's called withoutnew. You can do something similar with your function if you wanted to. But in general this would not make sense for custom constructors, so you would rather use.mapwitharr.map(function(v) { return new MyString(v); });.