개발 공부/자바스크립트

[엘리의 드림코딩 JS] ES6 - ES11 핵심 문법들

5묘 2022. 12. 7. 15:06

https://youtu.be/36HrZHzPeuY

1) ES6에 추가된 기능들 : Shorthand property names, Destructuring Assignment, Spread Syntax, Default Parameters, Tenary Operator, Template Literals

/*
 * Shorthand property names
 * https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Object_initializer
 */

{
  const ellie1 = {
    name: "Ellie",
    age: "18",
  };

  // 전역 변수
  const name = "Ellie";
  const age = "18";

  // 💩
  const ellie2 = {
    name: name,
    age: age,
  };

  // 😎 key와 value 변수명 같으면 이렇게 합치자
  const ellie3 = {
    name,
    age,
  };
}

/*
 * Destructuring assignment(구조 분해 할당)
 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
 */
{
  // object
  const student = {
    name: "Anna",
    level: 1,
  };

  // 💩
  {
    const name = student.name;
    const level = student.level;
    console.log(name, level);
  }
  // 😎
  {
    // 객체 내의 key 이름 똑같이 맞춰서 넣어야함
    const { name, level } = student;
    console.log(name, level);

    // 변수 이름을 바꾸고 싶다면 이렇게 하면 됨.
    const { name: studentName, level: studentLevel } = student;
    console.log(studentName, studentLevel);
  }

  // 배열에서도 사용 가능
  const animals = ["🤑", "😺"];

  // 💩
  {
    const first = animals[0];
    const second = animals[1];
    console.log(first, second);
  }

  // 😎
  {
    const [first, second] = animals;
    console.log(first, second);

    const [a, b, ...rest] = [19, 20, 21, 2, 3];
    console.log(rest);
  }
}

/**
 * Spread Syntax
 */
{
  const obj1 = { key: "key1" };
  const obj2 = { key: "key2" };
  const array = [obj1, obj2];

  // array copy
  const arrayCopy = [...array]; // deep copy
  const obj3 = { key: "key3" };
  array[0] = obj3;
  console.log(array); //{ obj3, obj2 }
  console.log(arrayCopy); //{ obj1, obj2 }

  const arrayCopy2 = [...array, { key: "key4" }];
  console.log(array, arrayCopy, arrayCopy2);

  /*  
   * 이때 각각의 array에 담긴 obj1, obj2, obj3는 오브젝트를 가리키는 참조값이다.
    그래서 105처럼 가리키는 obj1의 value가 바뀌었을 때, 각각의 배열에 있는 obj1 전체가 바뀐 것이다.
    
   * 헷갈리면 안되는 게, 86에서 arrayCopy는 새로운 주소에 새 배열을 할당하므로 원본의 배열 요소가 바뀐다 해도(obj3 => obj1) 둘은 다른 배열이므로 상관 X. 즉 arr 자체는 deepcopy 되는 것이 맞다.
  
  const arrayCopy = [...array];
  console.log(array, arrayCopy);

  const arrayCopy2 = [...array, { key: "key3" }];
  obj1.key = "newKey";
  console.log(array, arrayCopy, arrayCopy2);
  */

  // object copy
  const obj4 = { ...obj1 };
  console.log(obj4);

  // array concatenation
  const fruits1 = ["🍓", "🍌"];
  const fruits2 = ["🍐", "🍒"];
  const fruits = [...fruits1, ...fruits2];
  console.log(fruits);

  // object merge
  const dog1 = { dog: "🐕" };
  const dog2 = { dog: "🐶" }; // key가 같을 경우 뒤에가 앞에를 덮어 씌운다.
  const dog = { ...dog1, ...dog2 };
  console.log(dog); //{dog: '🐶'}
}

/**
 * Default parameters
 */
{
  // 💩
  {
    function printMessage(message) {
      console.log(message);
    }
    printMessage("hello"); // 'hello'
    printMessage(); // 'undefined'}
  }

  // ✨
  {
    function printMessage(message = "default message") {
      console.log(message);
    }
    printMessage("hello"); // 'hello'
    printMessage(); // 'default message'
  }
}

/**
 * Ternary Operator
 */
{
  const isCat = true;
  // 💩
  {
    let component;
    if (isCat) {
      component = "😺";
    } else {
      component = "🐶";
    }
    console.log(component);
  }
  // ✨
  {
    const component = isCat ? "😺" : "🐶";
    console.log(component);
  }
}

/**
 * Template Literals
 */
{
  const weather = "🌥";
  const temperature = "16℃";

  // 💩
  console.log(
    "Today weather is " + weather + " and temperature is " + temperature + "."
  );

  // ✨
  console.log(`Today weather is ${weather} and temperature is ${temperature}.`);
}

2) ES11에 추가된 기능들 : Optional Chaining, Nullish Coalescing Operator

/**
 * Optional Chaining (ES11)
 */

{
  const person1 = {
    name: "Ellie",
    job: {
      title: "S/W Engineer",
      manager: {
        name: "Bob",
      },
    },
  };
  const person2 = {
    name: "Bob",
  };

  // 💩💩💩💩
  // {
  //   function printManager(person) {
  //     console.log(person.job.manager.name);
  //   }
  //   printManager(person1); //Bob
  //   printManager(person2); // Uncaught TypeError: Cannot read properties of undefined (reading 'manager')
  // }

  // ✨
  {
    function printManager(person) {
      console.log(person.job?.manager?.name);
    }
    printManager(person1); //Bob
    printManager(person2); //undefined (오류 안남)
  }
}

/**
 * Nullish Coalescing Operator (ES11)
 */
{
  // Logical OR operator
  // false : false, '', 0, null, undefined
  {
    const name = "Ellie";
    const userName = name || "Guest";
    console.log(userName); // 'Ellie' 출력
  }

  {
    const name = null;
    const userName = name || "Guest";
    console.log(userName); // 'Guest' 출력'
  }

  // 💩high bug risk
  {
    const name = "";
    const userName = name || "Guest";
    console.log(userName); // 'Guest' 출력'

    const num = 0;
    const message = num || undefined;
    console.log(message); // undefined 출력'
  }

  // ✨Nullish coalescing(true/false가 아니라 값 유무 따짐)
  {
    const name = "";
    const userName = name ?? "Guest";
    console.log(userName); // '' 출력'

    const num = 0;
    const message = num ?? undefined;
    console.log(message); // 0 출력'
  }
}