Home > Software design >  Non array object concate method
Non array object concate method

Time:12-01

I'm trying to understand Array Method, when I write code in vs code and call only array.prototype.concate.call() gives me the correct result,

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

but when I try to array.concate() it gives me an error.

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

error message:

TypeError: Array.concat is not a function

CodePudding user response:

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

CodePudding user response:

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

  • Related