The ‘…’ operator in TypeScript is called the spread operator. It is used to spread the contents of an array or an object into individual elements. Whatever you use JavaScript or TypeScript both supports spread operator.
The spread operator is used by developers to open arrays. Although you will hardly be able to understand just by definitions etc., but let me give you a task.
Task for you
suppose you have an array [1, 2, 3] and you have another array [4, 5, 6]. now you want to create an array which will contain both two arrays means [1, 2, 3, 4, 5, 6]. now tell me how will you do this?
if you are thinking that you will do something like [array1, array2] then you are wrong because an output of this will be [[1, 2, 3], [4, 5, 6]]. now you will think that you will use the loop and then you will push an element into the array. this will work but code will be complex and and it's not readable.
now in this case you can se the spread operator(...). which will help you with one line of code, no extra loops and no extra push functions. how? let's see.
let array1 = [1, 2, 3];
let array2 = [4, 5, 6];
// let's merge it.
let array3 = [...array1, ...array2];
console.log(array3);
// this code output will be [1, 2, 3, 4, 5, 6]
const object1 = { a: 1, b: 2 };
const object2 = { c: 3, d: 4 };
// let's merge it.
const object3 = { ...object1, ...object2 };
// this code output will be { a: 1, b: 2, c: 3, d: 4 }
0 Comments