본문 바로가기
JS

Refactoring javascript 2

by memory-log 2020. 9. 23.

Clean coding in JavaScript 2

리팩토링 자바스크립트, 클린 코드 작성하기 2

Refactoring js example code

destructuring, spread operator, async-await, template literals, optional chaining example code

디스트럭처링, 스프레드 오퍼레이터, 어싱크 어웨이트, 템플릿리터럴, 옵셔널 체이닝 활용하기

Optional Chaining

옵셔널 체이닝

연산자 ?. 는 체인의 각 참조가 유효한지 명시적으로 검증하지 않고, 연결된 객체 체인 내에 깊숙이 위치한 속성 값을 읽을 수 있다.

만약 참조가 nullish (null 또는 undefined)이라면, 에러가 발생하는 것 대신에 표현식의 리턴 값은 undefined로 단락된다. 함수 호출에서 사용될 때, 만약 주어진 함수가 존재하지 않는다면, undefined를 리턴한다.

// bad
const bad = user && user.address && user.adress.street

// good
const good = user?.adress?.street
const adventurer = {
  name: "Alice",
  cat: {
    name: "Dinah",
  },
}

const dogName = adventurer.dog?.name
console.log(dogName)
// expected output: undefined

Destructuring

디스트럭처링 (구조분해할당)

배열이나 객체의 속성을 해체하여 그 값을 개별 변수에 담을 수 있게 하는 JavaScript 표현식

// bad
const city = adress.city
const pinCode = adress.pinCode
const street = adress.street

// good
const { city, pinCode, street } = adress

Arrow Function

화살표 함수

function 표현에 비해 구문이 짧고 자신의 this, arguments, super 또는 new.target을 바인딩 하지 않는다.

화살표 함수는 항상 익명이다. 이 함수 표현은 메소드 함수가 아닌 곳에 가장 적합하며 생성자로서 사용할 수 없다.

// bad
function add(a, b) {
  return a + b
}

// good
const add = (a, b) => a + b

Arrow function & this

function Person() {
  let that = this
  that.age = 0

  setInterval(function growUp() {
    // 콜백은  `that` 변수를 참조하고 이것은 값이 기대한 객체이다.
    that.age++
  }, 1000)
}

화살표 함수는 자신의 this가 없다. 대신 화살표 함수를 둘러싸는 렉시컬 범위(lexical scope)의 this가 사용된다.

화살표 함수는 일반 변수 조회 규칙을 따른다. 때문에 현재 범위에서 존재하지 않는 this를 찾을 때, 화살표 함수는 바로 바깥 범위에서 this를 찾는것으로 검색을 끝내게 된다.

function Person() {
  this.age = 0

  setInterval(() => {
    this.age++ // |this|는 Person 객체를 참조
  }, 1000)
}

let p = new Person()

setInterval에 전달 된 함수 내부의 this는 setInterval을 포함한 function의 this와 동일한 값을 갖는다.

Template literals

템플릿 리터럴

내장된 표현식을 허용하는 문자열 리터럴. 여러 줄로 이뤄진 문자열과 문자 보간기능을 사용할 수 있다.

이중 따옴표 나 작은 따옴표 대신 백틱(``) (grave accent) 을 이용한다.

${expression} 로 표기하여 표현식을 넣을 수 있다.

// bad
const bad = "hi " + firstName + " " + lastName

// good
const good = `hi ${firstName} ${lastName}`

Spread Operator

const person = { firstName: "Wow", lastName: "LOL" }
const job = { jobTitle: "Developer", location: "Hawaii" }

// bad
const employee = {
  firstName: person.firstName,
  lastName: person.lastName,
  jobTitle: person.jobTitle,
  location: person.location,
}

// good
const employee = { ...person, ...job }

'JS' 카테고리의 다른 글

비동기 Asynchronous 이해하기  (0) 2020.09.23
JS Module  (0) 2020.09.23
Refactoring javascript 1  (0) 2020.09.23
Detect Dark mode in CSS & Javascript  (0) 2020.09.23
Javascript 삼각함수 sin, cos, tan  (0) 2020.09.22

댓글