Array.prototype.squareLoading saved progress…

Array.prototype.square

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.

Signature

// 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]

Examples

[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]

Notes

  • Define it on the prototype. The method must live on Array.prototype.square, not be a standalone function, so the call site is [...].square().
  • Use 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.
  • Return a new array. Build and return a fresh array; do not modify the receiver. a.square() must not equal a, and a itself must be unchanged afterward.
  • Keep it non-enumerable. A plain Array.prototype.square = ... makes the method show up in for...in over arrays. Define it so it stays hidden.
  • Numbers only. You can assume every element is a number; no need to validate types.
Loading editor…