JS) default parameter, rest parameter, spread operator

kangdari·2020년 3월 31일
0

default parameter

파라미터 기본 값 설정
false한 인자 값이 넘어와도 default parameter를 설정해두면 기본 값 설정이 편하다.

const f = (x=4, y=5, z=6) => {
   console.log(x, y, z);
}

f(0, undefined, null) // 0 5 6
f(0, '', null) // 
f() // 4 5 6
f(0) // 0 5 6
f(0, 1) // 0 1 6
f(0, 1, 2) // 0 1 2

할당되지 않은(undefined) f 값에 대해서만 default parameter가 적용됨.

const f = (a=1, b=2, c=3, d=4, e=5, f=6) =>{
    console.log(a, b, c, d, e, f)
}

f(8, 0, '', false, null) // 8 0 '' false null 6

이렇게도 사용 가능

const f = (a=1, b=a+1, c=3) => {
    console.log(a, b, c)
}

f(1, undefined, 3); // 1 2 3

함수도 default parameter로 설정이 가능하다.

const getDefault = () =>{
    console.error('getDefault called')
    return 10
}

const sum = (x, y = getDefault()) => {
    console.log(x + y)
}

sum(1,2) // 3
sum(1) // error: getDefault called 11

주의사항

기본 값으로 설정하고자하는 변수일 경우 인자의 변수 명과 달라야한다.
TDZ(Temporal Dead Zone)의 영향을 받는다.

let a = a ???

let a = 10
const f = (a=a) => {
    console.log(a)
}

f(1) // 1
f() // ReferenceError: Cannot access 'a' before initialization

rest parameter

  • rest parameter는 배열의 형태로 남은 파라미터 값들을 반환해준다.
  • 반드시 마지막에 위치해야한다.
const f = ( a, ...rest) => {
    console.log(a) // 1
    console.log(rest) // [ 2, 3, 4, 5, null, undefined ]
}

f(1, 2, 3, 4, 5, null, undefined)

spread operator(전개 연산자)

  • 배열 합치기
const birds = ['eagle', 'pigeon']
const mammals = ['elephant', 'dog']
const animal = birds.concat('whale').concat(mammals);
console.log(animal) // [ 'eagle', 'pigeon', 'whale', 'elephant', 'dog' ]

// spread operator ...
const animal2 = [...birds, 'whale', ...mammals]
console.log(animal2) // [ 'eagle', 'pigeon', 'whale', 'elephant', 'dog' ]
  • 배열의 각 요소 값들을 펼치는 효과
const arr = [1, 2, 3, 4, 5]
console.log(...arr) // 1, 2, 3, 4, 5
  • 앞뒤로 다른 값들을 함께 사용할 수 있음
const values = [2, 3, 4, 5, 6, 7]
const sum = (...args) => args.reduce((a, c) => a + c)
console.log(sum(1, ...values, 8, 9)) // 45
  • iterable한 데이터는 모두 사용 가능 ( 반복가능한 데이터)
const str = "Hello"
const splitArr = str.split('')
const restArr = [...str]
console.log(splitArr, restArr) 
// [ 'H', 'e', 'l', 'l', 'o' ] 
// [ 'H', 'e', 'l', 'l', 'o' ]
  • 새로운 배열을 반환한다.

  • 얕은 복사(Shallow copy)만을 수행한다.

const originArr = [{
    first: 'hello',
    seconde: 'hi'
}]

let copiedArr = [...originArr]
console.log(copiedArr) // [ { first: 'hello', seconde: 'hi' } ]

copiedArr[0].first = 'HELLO';
console.log(originArr[0].first) // HELLO
console.log(copiedArr[0].first) // HELLO

0개의 댓글