Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending Array.prototype returning undefined

I'm trying to extend Array.prototype to include a square function. I have this:

Array.prototype.square = function(){
  return this.forEach(function(el){
    return (el * el)
  });
}

When I call this function on an array, say arr = [2, 2, 2] it returns undefined. If I add a console.log in there I can see that the callback function for the forEach function executes properly -- it logs 4 three times. Why is this function returning undefined instead of a new array of [4, 4, 4]?

like image 228
Chris Clouten Avatar asked Feb 05 '26 23:02

Chris Clouten


2 Answers

The forEach method does not return a value. You need to use map:

Array.prototype.square = function(){
  return this.map(function(el){
    return (el * el)
  });
}

console.log([2, 2, 2].square()); // [4, 4, 4]
like image 113
p.s.w.g Avatar answered Feb 07 '26 15:02

p.s.w.g


As p.s.w.g. said, .map is the appropriate function, but in a comment you asked about using forEach. To get this to work, you'd have to create a temporary array:

Array.prototype.square = function(){
  var tmp = [];

  this.forEach(function(el){
    tmp.push(el * el)
  });

  return tmp;
}

console.log([2, 2, 2].square()); // [4, 4, 4]

.map() is better, though.

like image 21
Ben Jacobs Avatar answered Feb 07 '26 15:02

Ben Jacobs