syntactic sugar in Javascript (Class와 Async Await)

자바스크립트에서는 syntactic sugar라는 개념이 있는데, 이는 코드 작성을 더 간결하고 쉽게 만들어주는 문법적 편의 기능을 의미한다.

이를 잘 활용하면 쉽고 잘 읽히는 코드를 작성할 수 있다.

Class

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  sayHello() {
    console.log(`Hello, I'm ${this.name}.`);
  }
}

프로토타입 생성자 함수

function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype.sayHello = function() {
  console.log(`Hello, I'm ${this.name}.`);
};

 

Async/Await

async function getData() {
  const response = await fetch('https://~')
  const jsonData = await response.json()
  const result = jsonData.result.id
  console.log(result)
}

는 사실....

async function getData() {
  await fetch('https://~').then((response) => {
    response.json().then((jsonData) => {
      const result = jsonData.result.id
      console.log(result)
    })
  })
}

 

이외에도 구조분해할당, Spread 문법, 객체 리터럴 단축 표기, 탬플릿 리터럴, 화살표 함수 등이 sugar syntax로, 쉽게 자바스크립트 문법을 작성하도록 도와준다.