Topic Description

Imagine you are working on a project that heavily relies on array operations. Your task is to design a new method for the array prototype called square(). This method should efficiently iterate over each element in the array and return a brand new array where each element is the square of the original element. Assume the array only contains 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(); // []

Answer

Array.prototype.square = function(){
	return this.map(item => item * item)
}