EasyAmazonByteDanceApple

Polyfill: concat()

Prompt

Imagine the JavaScript array method .concat() does not exist. Implement a myConcat method on Array.prototype that works like the native .concat().

Playground

Hint 1

Start by copying the original array's elements into a new array (don't modify the original). Then loop through each argument and add its contents to the new array.

Hint 2

Each argument can be either an array or a single value. Use Array.isArray() to check. If it's an array, add its elements individually. If it's a single value, just push it.

Solution

Explanation

concat merges arrays and values into a new array. It never modifies the original. You can pass it any number of arguments, and each one can be either an array or a single value.

The interesting behavior is how it handles arrays vs non-arrays. If you pass an array, concat unpacks its elements and adds them individually. If you pass a regular value (number, string, object), it adds it as-is. But it only goes one level deep. Nested arrays inside an argument stay nested.

[1].concat([2, 3]); // [1, 2, 3] - array is unpacked
[1].concat(2); // [1, 2] - value added as-is
[1].concat([2, [3, 4]]); // [1, 2, [3, 4]] - only one level deep

Our solution starts by copying the original array with [...this] so we don't modify it. Then for each argument, we check if it's an array with Array.isArray(). If it is, we loop through its elements and push each one. If it's not, we push the value directly.

We use for...of here (not a regular for loop) because we don't need to pass the index to anyone. There's no callback involved, we're just adding elements to an array.

When do you use concat?

  • Combining datasets: merging results from multiple API calls into one array
  • Adding elements immutably: when you want to append items without modifying the original (common in React state updates)
  • Building arrays from mixed sources: combining arrays and individual values in one step

concat vs spread

In modern JavaScript, the spread operator often replaces concat: [...arr1, ...arr2] does the same thing as arr1.concat(arr2). But concat is still useful when some arguments might be arrays and others might be single values, since it handles both automatically.