Thursday, February 16, 2023

The spread syntax or the rest syntax in Javascript or Typescript

In JavaScript and TypeScript, the ... syntax is called the spread syntax or the rest syntax, depending on the context in which it is used. When used in an array or an object, the spread syntax can be used to create a copy of the array or object and add or remove elements. Here's an example of using the spread syntax with an array:
  
 
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5, 6];

console.log(arr2); // [1, 2, 3, 4, 5, 6]


  
In this example, we are creating a new array arr2 that is a copy of arr1 with the values 4, 5, and 6 added to the end. The spread syntax is used to "spread" the elements of arr1 into the new array, and then the additional elements are appended. Similarly, the spread syntax can be used with objects to create a new object with the properties of the original object, and add or overwrite properties. Here's an example:
  
 
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, b: 3, c: 4 };

console.log(obj2); // { a: 1, b: 3, c: 4 }



  
In this example, we are creating a new object obj2 that has all the properties of obj1, but with the value of b changed to 3 and a new property c added. The spread syntax is used to "spread" the properties of obj1 into the new object, and then the additional properties are added or overwritten. The spread syntax can also be used in function arguments to pass an array or an object as individual arguments. Here's an example:
  
 
const myFunc = (a: number, b: number, c: number) => {
  console.log(a + b + c);
};

const arr = [1, 2, 3];
myFunc(...arr); // 6

const obj = { a: 1, b: 2, c: 3 };
myFunc(...Object.values(obj)); // 6




  
In this example, we have a function myFunc that takes three arguments. We can use the spread syntax to pass the elements of an array or the values of an object as separate arguments to the function. In both cases, the function will receive the individual values 1, 2, and 3, and log the sum 6 to the console.

No comments:

Post a Comment