1

I'm reading on the map/reduce documentation and this particular string example doesn't make sense to me.

var toCode = function(char) {
   return char.charCodeAt(0);    
}

First, the thing that works. Why does it work? string is not an array.

var text = "Hello World";
var map = Array.prototype.map;
console.log(map.call(text, toCode));

Now, the thing that doesn't work. Isn't this exactly the same as above?

console.log(text.map(toCode));

I use www.codeacademy.com console to test and this is the error message:

 TypeError: undefined is not a function (evaluating '"hello world".map(toCode)')

Thank you.

1 Answer 1

3

Your second code won't work because strings don't have a map method, but you can borrow it from Array, because array methods are meant to work on array-like objects, that is an object with numeric keys, such as strings:

The map function is intentionally generic; it does not require that its this value be an Array object. Therefore it can be transferred to other kinds of objects for use as a method. Whether the map function can be applied successfully to a host object is implementation-dependent.

http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.19

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

1 Comment

That's what I thought originally, but then the first case working made me think that in Javascript, a string is an array of characters, then the second case must also work. Thanks for clearing.

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.