-1

"I'm trying to use the concat() method in JavaScript to merge an object and several numbers into a new array. Here's the code I'm using:

console.log(Array.concat({}, 1, 2, 3));

When I run this code, I get the following error message:

TypeError: Array.concat is not a function

However, when I use Array.prototype.concat.call(), it works as expected:

console.log(Array.prototype.concat({}, 1, 2, 3));

Why does Array.concat() cause an error, but Array.prototype.concat.call() works?"

2
  • 3
    That's because the static method Array.concat doesn't exist; the method concat only exists on the prototype Commented Nov 30, 2022 at 7:52
  • 1
    What makes you think that Array.concat exists? It used to exist in some browsers as a non-standard feature years ago; have you encountered a tutorial that mentioned these static methods? Commented Nov 30, 2022 at 8:13

2 Answers 2

1

Not a huge expert, but you might want to review:

Array.prototype.concat()

In your terminal, web console, if you type Array.prototype, it will basically create an empty array with all of the methods for an array for you, so 'Array.prototype' is an array.

So,

Array.prototype.concat({}, 1, 2, 3)

and

[].concat({}, 1, 2, 3)

give the same result.

Given an instance arr of Array, arr.method is equivalent to Array.prototype.method.

You might read this as well: SO link

Sign up to request clarification or add additional context in comments.

Comments

1

concat() method actually ....concats TWO(or more) arrays, it merges them. The way you are calling it, through Array.prototype is equivalent to doing [].concat({}, 1, 2, 3) which means merge an empty array with the values {},1,2,3.

The proper way to use it is like

const num1 = [1, 2, 3];
const num2 = [4, 5, 6];
num1.concat(num2)

Array.concat doesn't exist as concat is a method of Array.prototype. The reason num1.concat(num2) works is because num1 is an Array with prototype object as property that contains all these array functions you can use

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.