Add a custom square method to Array.prototype so that any array can call [1, 2, 3].square() and get back [1, 4, 9] — a new array with each element multiplied by itself. The original array must stay untouched. This is a small exercise in extending a built-in prototype, using this to reach the receiver array, and adding the method without it polluting for...in.
// Adds a method to every array. No arguments.
// Returns a NEW array; the original is not modified.
interface Array<T> {
square(): number[];
}
// Usage:
[1, 2, 3].square(); // → [1, 4, 9]
[4, 5].square();
// → [16, 25]
const original = [2, 3];
original.square(); // → [4, 9]
original; // → [2, 3] (unchanged)
[-3, 1.5, 0].square();
// → [9, 2.25, 0]
Array.prototype.square, not be a standalone function, so the call site is [...].square().this. Inside the method, this is the array .square() was called on. Use a regular function (not an arrow) so this binds to that array.a.square() must not equal a, and a itself must be unchanged afterward.Array.prototype.square = ... makes the method show up in for...in over arrays. Define it so it stays hidden.