Implement map on a Prototype - newArray is not defined but I thought it was

Implement map on a Prototype - newArray is not defined but I thought it was
0

#1

I was glad to grasp use of this for this challenge.

However, I get ‘‘newArray is not defined’’ when executing the below code

This problem is resolved if one cuts and pastes newArray from outside where it is defined in the function as below and define it as a global variable like s.

Small technicality as I ‘‘think’’ I got the main learning of this challenge but want to ensure consistency.

Your code so far


// the global Array
var s = [23, 65, 98, 5];


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;
});

console.log(newArray);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.167 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/functional-programming/implement-map-on-a-prototype/


#2

My current theory is that newArray is defined in the function and is hence a local variable. As a local variable, it is not recognized by the callback function, the callbackF(this[i]) part… Is any of that correct?


#3

You can’t access a local variable outside of the scope.

newArray is defined inside the function and it can only be accessed inside of it.

Refer to the previous challenge for more information Basic JavaScript: Local Scope and Functions.


#4

It actually works - the problem was console.log(newArray);

the function itself does return something

Should have been console.log(new_s);


#5

Your code works I know. Congratulations.

I was commenting on that line:

console.log(newArray);

Which tries to console.log a variable outside of its scope.


#6

Yeah thank you - I was confused as I assumed I thought this meant there was something wrong with the function but the issue was trying to log a local var


#7

No problem.

Good Luck & Happy Coding!