0

When i pass arguments it consoles an Error(cannot read property "map" of undefined), when i pass an empty array it consoles an empty array :)

Array.prototype.square = function() {
  return [].map((number) => number^2)
}

var numbers = [1, 2, 3, 4, 5];

console.log(numbers.square())
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
I.Rayetzki
  • 33
  • 6

2 Answers2

1

Use Math.pow()

Array.prototype.square = function() {
  return this.map(function(item) {
    return Math.pow(item, 2);
  });
}
var numbers = [1, 2, 3, 4, 5];
console.log(numbers.square())
Rayon
  • 36,219
  • 4
  • 49
  • 76
1

You are applying map() on an empty array so it will always return empty array, instead use this to refer the array. Use Math .pow() to get square of the array element.

Array.prototype.square = function() {
  return this.map((number) => Math.pow(number, 2))
}
var numbers = [1, 2, 3, 4, 5];

console.log(numbers.square())

FYI : ^ (caret symbol) using for bitwise XOR in JavaScript, refer : What does the caret symbol (^) do in JavaScript?

Community
  • 1
  • 1
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188