Open In App

Difference Between Spread Operator and Array.concat() in Typescript

The spread operator and concat() method both are used to add elements to an array. But they are different from each other in many ways. Let us discuss the difference between both of them in detail.

Spread Operator

The spread operator creates a new array by merging the elements of the passed arrays or the values. It is denoted by three dots(…). It unpacks the elements of the passed arrays and creates a new array with the elements of both the passed arrays.



Syntax:

const newArrayName = [...arr1, ...arr2];

Features:

Example: The below code example implements the spread operator in TypeScript.




const arr1: number[] = [1, 2, 3];
const arr2: string[] =
    ["TypeScript", "GeeksforGeeks", "JavaScript"];
const mergedArray: (number | string)[] =
    [...arr1, ...arr2];
console.log(mergedArray);
const newMergedArray: (number | string)[] =
    [...mergedArray, 4, 5, "GFG"];
console.log(newMergedArray);

Output:



[1, 2, 3, "TypeScript", "GeeksforGeeks", "JavaScript"]
[1, 2, 3, "TypeScript", "GeeksforGeeks", "JavaScript", 4, 5, "GFG"]

Array.concat() method

The concat method is used to create a new array with the elements of the passed arrays or the values. It adds the elements at any index of the array.

Features:

Syntax:

const newArrayName = arr1.concat(arr2);

Example: The below code example implements the concat() method in TypeScript.




const arr1: number[] = [1, 2, 3];
const arr2: string[] =
    ["TypeScript", "GeeksforGeeks", "JavaScript"];
const mergedArray: (number | string)[] =
    arr1.concat(arr2);
console.log(mergedArray);
const newMergedArray: (number | string)[] =
    mergedArray.concat(4, 5, ["GFG"]);
console.log(newMergedArray);

Output:

[1, 2, 3, "TypeScript", "GeeksforGeeks", "JavaScript"]
[1, 2, 3, "TypeScript", "GeeksforGeeks", "JavaScript", 4, 5, "GFG"]

Difference between the Spread operator and concat() method

Spread Operator

concat() method

The spread operator is implemented using the three dots syntax(…).

The concat method is implemented using the concat() syntax.

It unpacks all the elements of the passed arrays and creates a new array of the merged values of passed arrays.

It returns a new array after concatenate all the elements of the array and the values passed as the arguments to it.

It can also be used with the objects.

It is a array specific method and can be used with arrays only.

It can be used to destructure the arrays and the objects.

It can not be used to destructure either arrays or abjects.

It preserves the type of the each element in the passed arrays

It converts the elements into string and then concat the arrays to return new array.


Article Tags :