EasyByteDanceLinkedin

square()

Prompt

JavaScript arrays don't have a native .square() method. Implement one on Array.prototype that returns a new array with each element squared.

Playground

Hint 1

This is basically a custom version of .map(). Create a new array, loop through this, and push each element multiplied by itself.

Hint 2

You can also use .map() directly: return this.map(n => n * n).

Solution

Explanation

This is a simpler version of the .map() polyfill. We add a new method to Array.prototype, so every array in JavaScript can use it (just like .map(), .filter(), etc.).

Inside the method, this refers to the array the method was called on. So when you write [1, 2, 3].square(), this is [1, 2, 3]. We loop through each element, square it, and push the result into a new array. The original array is never modified.

Why Number()?

We use Number(this[i]) to explicitly convert each element to a number before squaring it. This is important because the array might contain non-numeric values. Here's how JavaScript handles different types when converted with Number():

  • Numbers stay as they are: Number(5) is 5, so 5 * 5 = 25
  • Numeric strings get converted: Number('3') is 3, so 3 * 3 = 9
  • Non-numeric strings become NaN: Number('hello') is NaN, and NaN * NaN = NaN
  • null becomes 0: Number(null) is 0, so 0 * 0 = 0
  • undefined becomes NaN: Number(undefined) is NaN, so the result is NaN

This means [1, 'hello', 3, null, 5].square() gives you [1, NaN, 9, 0, 25]. Each value is handled consistently because we always convert to a number first.

Alternative using map()

You can write the whole thing as a one-liner:

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

Both approaches do the same thing. The for loop version shows you understand the underlying mechanics. The map version shows you know when to use built-in methods. Either is fine in an interview.

Why does squaring a negative number give a positive result?

-3 * -3 = 9. A negative times a negative is always positive. This isn't something our code does, it's just how multiplication works. So [0, -3, 5].square() gives [0, 9, 25].