[Easy] Implement Array.prototype.square

March 6, 2024

☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee

Question Prompt

Imagine you're working on a project that heavily relies on manipulating arrays. You're tasked with designing a new method for the Array prototype, called square(). This method should efficiently iterate through each element in the array and return a brand new array where every element is the square of the original element. Assume the array will only contain numbers

const numbers = [1, 2, 3, 4, 5];
const mixedArray = [1, 3.5];
const emptyArray = [];

numbers.square(); // [1, 4, 9, 16, 25]
mixedArray.square(); // [1, 12.25]
emptyArray.square(); // []

Solutions

To design the square method, we need to leverage this in the Array. this is a special keyword in JavaScript that represents the current execution context. Within an object method, it refers to the object itself. In the context for Array.prototype.square(), the keyword this refers to the specific array instance on which the square() method is called. When you call numbers.square(), this inside the square() function actually points to the numbers array.

Thus, we can create an empty array squaredArray for storing squared values first. And then iterates over each element in the array on which the square() method is called. The this keyword, as explained earlier, refers to the current array instance.

Inside the loop, the current element is accessed using this[i], multiplied by itself to square it, and then added to the squaredArray using the push() method

Array.prototype.square = function () {
  const squaredArray = [];
  for (let i = 0; i < this.length; i++) {
    squaredArray.push(this[i] * this[i]);
  }
  return squaredArray;
};

Or we can write it in a more concise way by using the map() method, a higher-order function that creates a new array by applying a function to each element of the original array. The map() method applies this squaring function to each element of the array on which the square() method is called (this). It creates a new array with the squared values.

Array.prototype.square = function () {
  return this.map((element) => element * element);
};
☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee