자바스크립트 최신 문법 정리

Lucid·2021년 4월 4일
1

내일은 첫 출근이다.. 첫 출근이다.. 무섭다...
무서움을 달래기 위해 조금씩 알고있던 문법들을 한번에 정리해보고자 한다.

shorthand property name

const firstName = "lee";
const age = 19;

const me = {
  firstName,
  age,
};

// const me2 = {
//   firstName: firstName,
//   age: age,
// };

console.log(me);
  • key와 value가 동일하다면 축약해서 사용 가능

Destructuring assignment

const student = {
  firstName: "lee",
  age: 20,
};

const { firstName, age } = student;

console.log(student.firstName);
console.log(firstName);
  • object 안에 있는 요소들을 동일하게 괄호 안에 사용해서 쓸수 있다.
const student = {
  firstName: "lee",
  age: 20,
};

const { firstName: studentFirstName, age: studentAge } = student;

console.log(student.firstName);
console.log(studentFirstName, studentAge);
  • 변수명을 다르게 사용하고 싶다면 :을 사용해서 변수명을 지정해준다.
  • 배열의 경우에도 동일하게 적용 가능하다.

Spread Syntax

const arr = [1, 2, 3, 4];
const arrCopy = [...arr,5];
  • 배열을 복사할때 ... (spread operation)을 통해 유용하게 복사 가능
  • Object도 복사 가능
  • key가 동일한 object를 ...로 병합한다면 마지막에 온 아이템으로 덮어씌워진다.

Default Parameter

const multiply = (a = 1, b = 2) => {
  console.log(`a * b = ${a * b}`);
};

multiply(10, 10); // a * b = 100
multiply(); // a * b = 2
  • 함수 호출 시 인자가 없을 경우를 대비하여 default parameter를 줄 수 있다.

Ternary Operator

const isEmptyString = true;

const message = isEmptyString ? "Message is null" : "Message is string";

console.log(message);
  • 삼항 연산자 사용하기
  • 너무 중첩해서 사용하지 말자

Template Literals

const name = "elsa";

console.log("hi, my name is " + name);
console.log(`hi, my name is ${name}`);
  • 위처럼 사용하면 지저분하고 복잡하니 아래 처럼 사용하자!

Optional Chaining

const student1 = {
  name: "Elsa",
  class: {
    title: "Math",
    teacher: "steve",
  },
};

const student2 = {
  name: "Anna",
};

console.log(student1.class.title); // Math
console.log(student2.class?.title); // undefined
  • student2의 class값이 undefined이거나 null이 아니라면 title 출력
  • 이렇게 ?를 붙이지 않으면 error!를 뿜어주게 됨

Nullish Coalescing Operator

falsy : false, '', 0, null, undefined

const num = null;

console.log(num ?? "hi");
  • falsy한 값이라면 "hi"출력, 아니라면 num 출력!

마치며

ES6 문법은 여태까지 쓰고 있었고, 무엇인지 알고 있었다면 es11은 쓰고는 있었지만 이름을 모르고 있던 것들도 있었다.
더 깔끔한 코드를 작성할 수 있을 것 같다 ☺️


참고 : 드림코딩 by 엘리

profile
Find The Best Solution 😎

0개의 댓글