[Javascript] Rest parameter and spread syntax

Suyeon·2020년 9월 3일
0

Javascript

목록 보기
14/31

When we see "..." in the code, it is either rest parameters or the spread syntax.

Rest Parameter

  • It gathers the rest of the list of arguments into an array.
  • It is used to create functions that accept any number of arguments.
  • It must be at the end.
function sumAll(...args) { 
  let sum = 0;

  for (let arg of args) sum += arg;

  return sum;
}

alert( sumAll(1) ); // 1
alert( sumAll(1, 2) ); // 3
alert( sumAll(1, 2, 3) ); // 6

Spread Syntax

  • It expands an array into a list.
  • It occurs in a function call or alike.
  • It is used to pass an array to functions that normally require a list of many arguments.
// (1) Expands array into a list of  arguments
alert( Math.max(3, 5, 1) ); // 5

// Not working
let arr = [3, 5, 1];
alert( Math.max(arr) ); // NaN

// Working!
let arr = [3, 5, 1];
alert( Math.max(...arr) ); // 5 (spread turns array into a list of arguments)

// (2) Merge arrays
let arr = [3, 5, 1];
let arr2 = [8, 9, 15];
let merged = [0, ...arr, 2, ...arr2];

// (3) Copy
let arr = [1, 2, 3];
let arrCopy = [...arr]; 

The spread syntax internally uses iterators to gather elements, the same way as for..of does.

let str = "Hello";

alert( [...str] ); // H,e,l,l,o
alert( Array.from(str) ); // H,e,l,l,o (more universal)
profile
Hello World.

0개의 댓글