Web/JavaScript

(JavaScript) Rest Pattern

haramang 2021. 11. 1. 12:17

// Rest patterns and parameters

'use strict';

 

// 1) Destructuring

 

// Spread, because on Right side of =

const arr = [1, 2, ...[3, 4]];

console.log(arr);

 

// REST, becase on LEFT side of =

const [a, b, ...others] = [1, 2, 3, 4, 5];

console.log(a, b, others);

 

const [pizza, ,Risotto, ...otherFood] = [...restaurant.mainMenu, ...restaurant.starterMenu];

console.log(pizza, Risotto, otherFood);



// Objects

const {sat, ...weekdays} = restaurant.openingHours;

console.log(weekdays);



// 2) Functions

const add = function(...numbers) {

  let sum = 0;

 

  for (let i = 0; i < numbers.length; i++) {

    sum += numbers[i];

  }

 

  console.log(sum);

}

 

add(2, 3);

add(5, 3, 7, 2);

add(8, 2, 5, 3, 2, 1, 4);

 

// Spread values in array and destructuring values in the function.

const x = [23, 5, 7];

add(...x);

 

restaurant.orderPizza('mushrooms', 'onion', 'olives', 'spinach');

restaurant.orderPizza('mushroom');