Implement a Map prototype with for loop

@camperextraordinaire
Sir I want to ask,

Array.prototype.myMap = function(callback){
  var newArray = [];
  // Add your code below this line
  newArray = Object(this);
  for(let i = 0; i < newArray.length; i++){
    newArray[i] = callback(newArray[i]);
  }
  // Add your code above this line
  return newArray;

};

in line newarray = Object(this); didn’t it point to the global window array object and not on this object? please explain it to me why is it working?

Read this:

Passing “this” to Object essentially creates an Array object

Ps. I would not add this line of code since the newArray is already an array object by definition.

1 Like

ok sir I understand that this in this context points to the original array and if we use it, it’s gonna change the original array.
But if we write like this as pointed out by @msmith1114 solution
Array.prototype.myMap = function(callback){
var newArray = [];
// Add your code below this line
for(var i = 0;i < this.length;i++)
{
newArray.push(callback(this[i]));
}
// Add your code above this line
return newArray;

};

var new_s = s.myMap(function(item){
return item * 2;
});
Didn’t the callback function is a method in newArray.push(callback(this[i])) that uses the this object and shouldn’t we have to modify how we execute the callback function to preserve the this object context? Or else the this object will either point to the global window object , if callback was passed to a global function ?

thank you sir I have been told by someone that I have to use some(I don’t know about them) call and apply functions to that callback function of javascript and my code is incorrect for the same reason.