spread and rest operator code example

Example 1: spread and rest javascript

var myName = ["Marina" , "Magdy" , "Shafiq"];var newArr = [...myName ,"FrontEnd" , 24];console.log(newArr) ; // ["Marina" , "Magdy" , "Shafiq" , "FrontEnd" , 24 ] ;

Example 2: spread operator in javascript

// spread operators can be used for arrays or objects

// cloning to prevent mutation.
let numList = [1,2,3];
let numListClone = [...numList]; // [1, 2, 3]

// spread operator for destructuring.
let animal = {
  name: 'dog',
  color: 'brown',
  age: 7
};
let { age, ...otherProperties } = animal; 

// spread operator as rest operator
function sum(x, y, ...rest) {}

// spread operator for merging arrays or objects
let numLists = [...numList1, ...numList2];
let animalWithBreed = {
  ...animal,
  breed: '',
}

Example 3: spread and rest javascript

var myName = ["Marina" , "Magdy" , "Shafiq"] ;const [firstName , ...familyName] = myName ;console.log(firstName); // Marina ;console.log(familyName); // [ "Magdy" , "Shafiq"] ;

Example 4: how to assign an rest operator in javascript

function multiply(multiplier, ...theArgs) {
  return theArgs.map(element => {
    return multiplier * element
  })
}

let arr = multiply(2, 1, 2, 3)
console.log(arr)  // [2, 4, 6]

Example 5: spread and rest operator javascript

function myData(...args){console.log(args) ; // ["Marina",24,"Front-End Developer"]}myData("Marina",24,"Front-End Developer") ;