JavaScript 2019
JavaScript 2019 (ES10): ECMAScript 2019의 주요 기능
- *ECMAScript 2019 (ES10)**은 2019년에 발표된 JavaScript 표준으로, 배열과 객체
처리에 유용한 몇 가지 기능이 추가되었습니다.
Array.prototype.flat()
,flatMap()
,Object.fromEntries()
, 그리고 문자열 트림 메서드 등의 기능이 도입되었습니다. 또한, try-catch 블록에서 옵셔널 바인딩을 지원해 코드가 더 간결해졌습니다.
이 가이드는 **ES10(ECMAScript 2019)**에서 도입된 주요 기능과 사용 예시를 설명합니다.
1. Array.prototype.flat()
flat()
메서드는 중첩된 배열을 지정된 깊이까지 평탄화하여 단일
배열로 반환하는 새로운 메서드입니다. 중첩 배열을 다룰 때 유용하며, 기본적으로 한 단계 깊이까지만 평탄화합니다.
1.1. flat()
사용 예시
const nestedArray = [1, 2, [3, 4, [5, 6]]];
const flattenedArray = nestedArray.flat();
console.log(flattenedArray); // [1, 2, 3, 4, [5, 6]]
1.2. 깊이 지정
깊이를 지정하여 더 깊은 중첩까지 평탄화할 수 있습니다.
const deepNestedArray = [1, 2, [3, 4, [5, 6]]];
const fullyFlattened = deepNestedArray.flat(2);
console.log(fullyFlattened); // [1, 2, 3, 4, 5, 6]
2. Array.prototype.flatMap()
flatMap()
메서드는 **map()
**과 **flat()
**을 결합한
기능을 제공합니다. 배열의 각 요소에 함수를 적용한 후, 결과를 평탄화하여 새로운 배열을 반환합니다.
2.1. flatMap()
사용 예시
const numbers = [1, 2, 3, 4];
const result = numbers.flatMap(x => [x, x * 2]);
console.log(result); // [1, 2, 2, 4, 3, 6, 4, 8]
2.2. map()
과 flat()
비교
기존에는 **map()
**으로 변환 후 **flat()
**을 따로 사용해야 했지만, **flatMap()
**을 사용하면 한
번에 처리할 수 있습니다.
// map()과 flat() 사용
const result = numbers.map(x => [x, x * 2]).flat();
console.log(result); // [1, 2, 2, 4, 3, 6, 4, 8]
// flatMap() 사용
const resultWithFlatMap = numbers.flatMap(x => [x, x * 2]);
console.log(resultWithFlatMap); // [1, 2, 2, 4, 3, 6, 4, 8]
3. Object.fromEntries()
- *
Object.fromEntries()
*는 키-값 쌍 배열을 객체로 변환하는 새로운 메서드입니다. 이를 통해 **맵(Map)**이나 키-값 배열을 간편하게 객체로 변환할 수 있습니다.
3.1. Object.fromEntries()
사용 예시
const entries = [['name', 'Alice'], ['age', 25]];
const person = Object.fromEntries(entries);
console.log(person); // { name: 'Alice', age: 25 }
3.2. Map
객체 변환
- *
Object.fromEntries()
*를 사용하면Map
객체를 일반 객체로 변환할 수 있습니다.
const map = new Map([['name', 'Alice'], ['age', 25]]);
const person = Object.fromEntries(map);
console.log(person); // { name: 'Alice', age: 25 }
4. String.prototype.trimStart()
와 trimEnd()
- *
trimStart()
*와trimEnd()
메서드는 문자열의 앞쪽 또는 뒤쪽의 공백을 제거합니다. 기존의trim()
메서드는 양쪽 공백을 제거하지만, **trimStart()
*와 **trimEnd()
*는 특정 방향의 공백만 제거할 수 있습니다.
4.1. trimStart()
사용 예시
const str = ' Hello world!';
console.log(str.trimStart()); // 'Hello world!'
4.2. trimEnd()
사용 예시
const str = 'Hello world! ';
console.log(str.trimEnd()); // 'Hello world!'
5. try...catch
의 옵셔널 catch
바인딩
ES10에서는 catch
블록에서 오류 객체를 생략할 수 있는 기능이 추가되었습니다. 기존에는 항상
catch (error)
형태로 오류 객체를 받아야 했지만, 이제는 오류 객체가 필요 없을 경우 생략할 수 있습니다.
5.1. 기존 catch
문법
try {
// 코드 실행
} catch (error) {
console.log('오류 발생');
}
5.2. 옵셔널 catch
바인딩
try {
// 코드 실행
} catch {
console.log('오류 발생');
}
옵셔널 catch
바인딩은 불필요한 변수 선언을 줄여 코드를 더 간결하게 만듭니다.
6. Function.prototype.toString()
개선
- *
Function.prototype.toString()
*은 함수의 정확한 소스 코드를 반환합니다. ES10 이전에는 함수의 공백이나 주석이 제거된 상태로 반환되었지만, ES10부터는 함수 정의가 있는 그대로 출력됩니다.
6.1. 개선된 toString()
예시
function sum(a, b) {
// 두 수를 더하는 함수
return a + b;
}
console.log(sum.toString());
// "function sum(a, b) {
// // 두 수를 더하는 함수
// return a + b;
// }"
7. Symbol.prototype.description
- *
Symbol.prototype.description
*은 **심볼(Symbol)**의 **설명(description)**을 반환하는 속성입니다. ES10 이전에는 심볼의 설명을 직접 접근할 수 없었지만, ES10부터는 심볼의 설명을 더 쉽게 확인할 수 있습니다.
7.1. description
사용 예시
const sym = Symbol('example');
console.log(sym.description); // 'example'
요약
- *ES10(ECMAScript 2019)**은 배열 처리, 객체 변환, 문자열 처리 등에서 유용한 기능들을 추가하여 JavaScript 개발을 더욱 간편하게 만들었습니다.
Array.prototype.flat()
: 중첩 배열을 지정된 깊이까지 평탄화.Array.prototype.flatMap()
: 배열을 변환 후 평탄화.Object.fromEntries()
: 키-값 쌍 배열 또는 **맵(Map)**을 객체로 변환.String.prototype.trimStart()
와trimEnd()
: 문자열의 앞쪽 또는 뒤쪽 공백 제거.- 옵셔널
catch
바인딩:catch
블록에서 오류 객체를 생략할 수 있어 코드가 간결해짐. Function.prototype.toString()
개선: 함수 정의를 정확하게 출력.Symbol.prototype.description
: 심볼의 설명을 더 쉽게 확인.
이러한 기능을 통해 개발자는 더 직관적이고 깔끔한 코드를 작성할 수 있습니다.