JSTS

[JS][ES6] Arrow function, defualt parameter, rest parameter

Jaaaay 2022. 6. 5. 23:32

Arrow funtion 활용

setTimeout(function(){
  console.log("settimeout");
},1000);

// arrow function
setTimeout( ()=>{
  console.log("settimeout");
},1000);

const newArr = [1,2,3,4,5].map(function(value, index, object){
  return value * 2;
});

// arrow function
const newArr = [1,2,3,4,5].map((v)=>{
  return v * 2;
});
// 더 축약형
const newArr = [1,2,3,4,5].map((v)=>v * 2);
>> [2, 4, 6, 8, 10]

Arrow function의 this context

const myObj = {
  runTimeout(){
    setTimeout(function(){
      console.log(this===window);
      this.printData();
    },200)
  },

  printData(){
    console.log("hi codesquad!");
  }
}

myObj.runTimeout();
>> "error"

해결하려면 bind로 this를 지정해준다.

const myObj = {
  runTimeout(){
    setTimeout(function(){
      console.log(this===window);
      this.printData();
    }.bind(this),200)
  },

  printData(){
    console.log("hi codesquad!");
  }
}

myObj.runTimeout();
>> false
>>"hi codesquad!"

하지만 arrow function을 사용하면 안그래도 됨

const myObj = {
  runTimeout(){
    setTimeout(() => {
      console.log(this===window);
      this.printData();
    },200)
  },

  printData(){
    console.log("hi codesquad!");
  }
}
>> false
>>"hi codesquad!"

arrow function을 사용하면 호출 기준이 아닌 선언 기준으로 this가 결정된다.


function default parameters

function sum(value, size){
  return value * size;
}

console.log(sum(3))
>> NaN

값 하나를 입력 안해줘서 오류가 뜬다.

function sum(value, size){
  size = size || 1;
  return value * size;
}

console.log(sum(3))
>> 3

다음과 같이 size의 기본값을 지정해 줄 수 있으나 이런 케이스가 많아질 경우 코드가 길어질 수 있다.

function sum(value, size={value:1}){
  return value * size.value;
}

console.log(sum(3))

이런 식으로 함수 선언부터 기본값을 지정하면 깔끔하다.


rest parameters

function checkNum(){
  const argArray = Array.prototype.slice.call(arguments);
  console.log(toString.call(argArray));
  const result = argArray.every((v)=>typeof v === "number")
  console.log(result);
  }

const result = checkNum(10,2,3,4,5,"55");
>> false

argument를 변환하여 인자 값을 다루어줄 수 있다. argument는 진짜 배열이 아니기 때문에 진짜 배열로 바꾸어주어야한다.

function checkNum(...argArray){
  console.log(toString.call(argArray));
  const result = argArray.every((v)=>typeof v === "number")
  console.log(result);
  }

const result = checkNum(10,2,3,4,5,"55");
>> "[object Array]"
>> false

rest parameter(...)을 사용하면 편리하게 배열로 받을 수 있다.

'JSTS' 카테고리의 다른 글

[TS] 1. 타입스크립트 시작하기  (0) 2022.06.08
[JS][ES6] 객체  (0) 2022.06.05
[JS][ES6] Template 처리  (0) 2022.06.05
[JS][ES6] set, map  (0) 2022.06.05
[JS][ES6] 객체, destructuring  (0) 2022.06.05