let Map = Array.prototype.map
let strResult = Map.call("Muhammad asif", (x) => {
return x.charCodeAt(0);
})
console.log(strResult)
What is the relation between call and map and how is its process? why charCodeAt(0) used here?
- What is the relation between
callandmap?
map is a function. call also a function.map is a part of Array object, and call is a part of Function object.map on an array. For example: [1, 2, 3].map(),call on a function. For example: myFunction.call()
- How is its process?
Array.prototype.map is a function that you put on a variable called Map. You can't just use it like a normal function, because it is designer to be used with an array. You can use it like this:
const myArray = [1, 2, 3]
myArray.Map = Map // put your `Map` variable into a real array
myArray.Map(number => console.log(number))
OR
Map.call("your array or iterable things goes here", (itemInArray) => {console.log(itemInArray)});
/* first parameter of `call` will be used as `this`. `this` in `Array.prototype.map` means an array. CMIIW */
Which is the same as:
const myString = "your array or iterable things goes here"
for(let index = 0; index < myString.length; index++){
const itemInArray = myString[index]
console.log(itemInArray)
}
- Why
charCodeAt(0)used here?
I don't know. That is your code, and the one who should answer this question is yourself. charCodeAt is not a required function for map or call to works. FYI, charCodeAt is also a function that returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index. So,
"abc".charCodeAt(0) // will show UTF-16 representation of the 0th character of "abc"
"abc".charCodeAt(1) // will show UTF-16 representation of the 1st character of "abc"
"abc".charCodeAt(2) // will show UTF-16 representation of the 2nd character of "abc"
Here you can find some explanation https://forum.freecodecamp.org/t/explain-array-prototype-map-call/165936/7
With this approach, you can use map function on string as it was an array.
charCodeAt is the function called on each element of the given string. It returns the Unicode representation (a number) of passed character. You can pass any other string-accepting function istead of it.
For example:
let Map = Array.prototype.map
let strResult = Map.call("Muhammad asif", (x) => {
return x + x
});
console.log(strResult)
will result with ["MM", "uu", "hh", "aa", "mm", "mm", "aa", "dd", " ", "aa", "ss", "ii", "ff"]