Spread Syntax (...)

About

Spread syntax(...)๋Š” 0๊ฐœ ์ด์ƒ์˜ ๋ณ€์ˆ˜(ํ•จ์ˆ˜ ํ˜ธ์ถœ์˜ ๊ฒฝ์šฐ) ๋˜๋Š” ์š”์†Œ(๋ฐฐ์—ด์˜ ๊ฒฝ์šฐ)๋ฅผ ํ•„์š”๋กœ ํ•  ๋•Œ iterable(๋ฐฐ์—ด์ด๋‚˜ ๋ฌธ์ž์—ด ๋“ฑ)์„ ํŽผ์น  ์ˆ˜ ์žˆ๋„๋ก(ํ™•์žฅ) ํ•œ๋‹ค.

...๋ฅผ ์“ด๋‹ค๋Š” ์ ์—์„œ Rest parameter์™€ ๋˜‘๊ฐ™์ด ์ƒ๊ฒผ๋‹ค. ์–ด๋–ค ๋ฉด์—์„œ rest syntax์˜ ์™„์ „ํžˆ ๋ฐ˜๋Œ€๋ผ๊ณ  ํ•  ์ˆ˜ ์žˆ๋‹ค. Spread syntax๋Š” ๋ฐฐ์—ด(array)์„ ์š”์†Œ๋“ค(elements)๋กœ "ํ™•์žฅ"ํ•˜์ง€๋งŒ, rest syntax๋Š” ์—ฌ๋Ÿฌ ์š”์†Œ๋ฅผ "์‘์ถ•" ์‹œํ‚จ๋‹ค.

Rest syntax์— ๋Œ€ํ•œ ๋‚ด์šฉ์€ Rest Parameters (...)์ฐธ๊ณ .

Syntax

function sum(x, y, z) {
  return x + y + z
}

const numbers = [1, 2, 3]

console.log(sum(...numbers)) // 6

Spread ๋ฌธ๋ฒ•์€ ๊ฐ์ฒด ๋˜๋Š” ๋ฐฐ์—ด์˜ ๋ชจ๋“  ์š”์†Œ๊ฐ€ ์ƒˆ๋กœ์šด ๊ฐ์ฒด ๋˜๋Š” ๋ฐฐ์—ด์— ํฌํ•จ๋˜์–ด์•ผ ํ•  ๋•Œ๋‚˜, ์š”์†Œ๋“ค์ด ํ•จ์ˆ˜ ํ˜ธ์ถœ์˜ ๋งค๊ฐœ๋ณ€์ˆ˜ ๋ชฉ๋ก์— ๊ฐ๊ฐ ์ ์šฉ๋˜์–ด์•ผ ํ•  ๋•Œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

์ด๊ฒŒ ๋ฌด์Šจ ์†Œ๋ฆฌ๋ƒ๋ฉด... spread ๋ฌธ๋ฒ•์ด ์ ์šฉ๋  ์ˆ˜ ์žˆ๋Š” ๊ณณ์€ 3๊ฐ€์ง€๊ฐ€ ์žˆ๋‹ค.

  1. ํ•จ์ˆ˜ ๋งค๊ฐœ๋ณ€์ˆ˜ ๋ชฉ๋ก (myFunction(a, ...iterableObj, b))

  2. ๋ฐฐ์—ด ๋ฆฌํ„ฐ๋Ÿด ([1, ...iterableObj, '4', 'five', 6])

  3. ๊ฐ์ฒด ๋ฆฌํ„ฐ๋Ÿด ({ ...obj, key: 'value' }}

์ด ์„ธ ๊ฐœ๊ฐ€ ๊ฐ™์•„๋ณด์ด์ง€๋งŒ ์˜๋ฏธ๊ฐ€ ์กฐ๊ธˆ์”ฉ ๋‹ค๋ฅด๋‹ค.

Iterable ๊ฐ์ฒด(e.g., ๋ฐฐ์—ด)๋งŒ ๋ฐฐ์—ด๊ณผ ํ•จ์ˆ˜ ๋งค๊ฐœ๋ณ€์ˆ˜์— ๋Œ€ํ•ด spread๊ฐ€ ๊ฐ€๋Šฅํ•˜๋‹ค. Symbol.iterator() ๋ฉ”์†Œ๋“œ๋ฅผ ๊ฐ–๊ณ  ์žˆ์ง€ ์•Š์€ ์ˆœ์ˆ˜ ๊ฐ์ฒด(Plain Object)๋ฅผ ํฌํ•จํ•œ ๋งŽ์€ ๊ฐ์ฒด๋“ค์€ iterableํ•˜์ง€ ์•Š๋‹ค.

const obj = { key1: 'value1' }
const array = [...obj] // TypeError: obj is not iterable

Note: ๊ฐ์ฒด ๋ฆฌํ„ฐ๋Ÿด์—์„œ spreadํ•˜๋ฉด ๊ฐ์ฒด์˜ ํ”„๋กœํผํ‹ฐ๋ฅผ enumerate(์—ด๊ฑฐ, ๋ฒˆํ˜ธ๋ฅผ ๋งค๊น€)ํ•˜๊ฒŒ ๋œ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ์ผ๋ฐ˜์ ์ธ ๋ฐฐ์—ด์—์„œ๋Š” ๋ชจ๋“  ์ธ๋ฑ์Šค๊ฐ€ enumerableํ•œ ํ”„๋กœํผํ‹ฐ์ด๋ฏ€๋กœ, ๋ฐฐ์—ด๋„ ๊ฐ์ฒด๋กœ spread๊ฐ€ ๊ฐ€๋Šฅํ•˜๋‹ค.

const array = [1, 2, 3]
const obj = { ...array } // { 0: 1, 1: 2, 2: 3 }

Spread ๋ฌธ๋ฒ•์„ ํ•จ์ˆ˜ ํ˜ธ์ถœ์— ์ ์šฉํ•  ๋•Œ, JavaScript์˜ ์•„๊ทœ๋จผํŠธ ๊ธธ์ด(limit)๋ฅผ ๋„˜์ง€ ์•Š๋„๋ก ์ฃผ์˜ํ•ด์•ผ ํ•œ๋‹ค. MDN ๋ฌธ์„œ๋ฅผ ์ฐธ๊ณ ํ•˜์ž.

REF

MDN Web Docs - Spread syntax (...)

Last updated