애드블럭 종료 후 보실 수 있습니다.

ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Javascript ES15(ECMAScript 2024) 문법정리
    JS 2024. 8. 14. 18:01
    728x90
    반응형

    ES13에 대한 글을 작성한 지 얼마 안 된 것 같은데 벌써 ES15가 정식 출시하였습니다.

    JavaScript의 최신 표준인 ECMAScript 2024 (ES15)에서는 개발자들이 더욱 강력한 기능들을 활용할 수 있도록 다양한 새로운 기능들이 도입되었습니다.

    아래에서는 ES15의 주요 기능들을 정리하고, 각 기능에 대해 ES15 이전과 이후의 코드를 비교해 보겠습니다.

    1. Object 및 Array 그룹화

    Object.groupBy() 및 Array.prototype.groupBy() 메서드를 사용하면 객체나 배열의 요소를 특정 조건에 따라 그룹화할 수 있습니다.

    예를 들어, 다음과 같이 과일 목록을 양에 따라 그룹화할 수 있습니다.

    (참고로 이번에 추가된 메서드는 원래 Array 프로토타입 메서드로 있었으나, 웹 호환성 이슈로 인해 정적 메서드로 이름을 변경하였습니다.)

    ES15 이전

    데이터를 그룹화하려면 반복문과 조건문을 사용해야 했습니다.

    const fruits = [
      { name: 'apple', quantity: 10 },
      { name: 'banana', quantity: 20 },
      { name: 'cherry', quantity: 10 }
    ];
    
    const groupedByQuantity = {};
    fruits.forEach(fruit => {
      const key = fruit.quantity;
      if (!groupedByQuantity[key]) {
        groupedByQuantity[key] = [];
      }
      groupedByQuantity[key].push(fruit);
    });
    console.log(groupedByQuantity);
    // 출력:
    // {
    //   '10': [{ name: 'apple', quantity: 10 }, { name: 'cherry', quantity: 10 }],
    //   '20': [{ name: 'banana', quantity: 20 }]
    // }

    ES15 이후

    Object.groupBy()를 사용하면 코드가 훨씬 간결해집니다.

    const groupedByQuantity = Object.groupBy(fruits, fruit => fruit.quantity);
    console.log(groupedByQuantity);
    // 출력:
    // {
    //   '10': [{ name: 'apple', quantity: 10 }, { name: 'cherry', quantity: 10 }],
    //   '20': [{ name: 'banana', quantity: 20 }]
    // }

    2. Temporal API

    Temporal API는 기존의 Date 객체보다 더욱 강력한 날짜 및 시간 처리를 제공합니다.

    예를 들어, 다음과 같이 Temporal.PlainDate 객체를 사용하여 날짜를 다룰 수 있습니다.

    ES15 이전

    날짜와 시간을 다루는 작업은 Date 객체를 사용해야 했으며, 이 객체는 불편한 부분이 많았습니다.

    const date = new Date('2024-06-30');
    console.log(date.getFullYear()); // 2024
    console.log(date.getMonth() + 1); // 6 (월은 0부터 시작)
    console.log(date.getDate()); // 30

    ES15 이후

    Temporal 객체를 사용하면 날짜와 시간을 더 직관적으로 처리할 수 있습니다.

    const date = Temporal.PlainDate.from('2024-06-30');
    console.log(date.year); // 2024
    console.log(date.month); // 6
    console.log(date.day); // 30

    3. Top-Level Await

    이제 모듈의 최상위 범위에서 await를 사용할 수 있습니다.

    이는 비동기 작업의 초기화 코드 작성 시 유용합니다.

    ES15 이전

    모듈 내에서 비동기 작업을 처리하려면 즉시 실행 함수(IIFE)나 별도의 함수 내에서 await를 사용해야 했습니다.

    (async () => {
        const module = await import('./someModule.js');
        console.log(module.someFunction());
    })();

    ES15 이후

    이제 모듈의 최상위 범위에서 await를 사용할 수 있어 코드가 더 간단해졌습니다.

    const module = await import('./someModule.js');
    console.log(module.someFunction());

    4. 패턴 매칭

    Pattern Matching 기능을 사용하면 데이터를 더욱 직관적이고 간결하게 처리할 수 있습니다.

    ES15 이전

    복잡한 조건문을 사용하여 객체의 구조를 검사해야 했습니다.

    const data = { type: 'success', value: 42 };
    
    let result;
    if (data.type === 'success') {
      result = `Success: ${data.value}`;
    } else if (data.type === 'error') {
      result = `Error: ${data.message}`;
    }
    console.log(result); // "Success: 42"

    ES15 이후

    패턴 매칭을 통해 더 간결하게 표현할 수 있습니다.

    const result = match(data, [
        { when: { type: 'success' }, then: ({ value }) => `Success: ${value}` },
        { when: { type: 'error' }, then: ({ message }) => `Error: ${message}` },
    ]);
    console.log(result); // "Success: 42"

    5. RegExp v 플래그 및 논리 할당 연산자

    RegExp의 v 플래그는 정규 표현식에서 더 세부적인 매칭 정보를 제공합니다.

    또한, 논리 할당 연산자(&&=, ||=, ??=)는 코드의 간결성을 높여줍니다.

    ES15 이전

    정규 표현식에서 세부적인 매칭 정보를 얻으려면 추가적인 코드가 필요했습니다. 또한 논리 할당을 위해 조건문을 사용해야 했습니다.

    const regex = /[\w\s]/g; // 알파벳, 숫자, 밑줄, 공백 문자만 매칭
    const str = 'foo bar 123!';
    const matches = str.match(regex);
    console.log(matches); // ['f', 'o', 'o', ' ', 'b', 'a', 'r', ' ', '1', '2', '3']
    
    let x = null;
    if (x === null || x === undefined) {
        x = 'fallback';
    }
    console.log(x); // 'fallback'

    ES15 이후

    v 플래그를 사용하여 더 많은 정보를 쉽게 얻을 수 있으며, 논리 할당 연산자로 코드가 간결해집니다.

    const regex = /\p{L}/v; // 모든 언어의 문자만 매칭
    const str = 'foo bar 123!';
    const matches = str.match(regex);
    console.log(matches); // ['f', 'o', 'o', 'b', 'a', 'r']
    
    let x = null;
    x ??= 'fallback';
    console.log(x); // 'fallback'

     

    반응형

    'JS' 카테고리의 다른 글

    구조분해 사용 팁 4가지  (2) 2024.09.14
    자바스크립트 비동기 프로그래밍 패턴  (0) 2024.05.28
    Javascript ES14 문법정리  (0) 2023.12.15
    Javascript ES13 문법정리  (0) 2023.12.04
    Javascript ES12 문법정리  (0) 2023.12.01

    댓글

Designed by Tistory.