I will be grateful if anyone looks at how I understand Solution 1 (with forEach) and say whether such an understanding is correct, especially in understanding what the keyword this is doing there.
My description:
This is a prototype of a method called myMap. The method calls a certain function named “callback” (it could be any other name), which:
creates a newArray;
using the key word this, it sets the property, as usual in a constructor, and in this case the property is the function (forEach method);
it iterates through [some] array using the forEach method;
on each element of [some] array it executes the function named “callback”;
the result of the every function execution step is pushed into the created newArray;
the method returns newArray.
When we call the myMap() method on the source array s, it performs all these actions, plus the callback(a) performs item*2, in this example, and returns the general result.
Thank you, now I think that I understand better. So, is this editing of my p.2 (below) correct?
the keyword this is here, because it refers to the array, which the forEach() method should be called on. In our case, this is [23, 65, 98, 5] in s.myMap(function(item){return item*2});
var s = [23, 65, 98, 5];
Array.prototype.myMap = function(callback) {
var newArray = [];
let i = 0;
// Only change code below this line
while(i < this.length){
newArray.push(callback(this[i]));
i++
}
// Only change code above this line
return newArray;
};
var new_s = s.myMap(function(item) {
return item * 2;
});
console.log(new_s);