JS

Javascript ES14 문법정리

Kir93 2023. 12. 15. 14:00
728x90
반응형

계속 작성하다 보니 어느덧 가장 최신인 ECMAScript 2023까지 왔습니다.

이렇게 정리를 해보니 점점 발전하고 있는 JS에 대해 새삼 느끼는 시간이었습니다.

 

1. findLast와 findLastIndex

배열 작업 시 특정 요소를 찾는 것은 자주 발생하는 작업입니다. find 메서드는 이러한 프로세스를 단순화하기 위해 도입되었지만, 첫 번째 일치하는 요소만 반환합니다.

그러나 때로는 배열의 끝에서부터 마지막 일치하는 요소를 찾아야 하는 상황이 있습니다. 이럴 때 findLast와 findLastIndex가 유용하게 사용됩니다.

// 이전 방법
const users = [
  {id: 1, name: 'user1', age: 19},
  {id: 2, name: 'user2', age: 14},
  {id: 3, name: 'user3', age: 22},
  {id: 4, name: 'user4', age: 13},
];

let lastUser;
for (let i = users.length - 1; i >= 0; i--) {
  if (users[i].age > 18) {
    lastUser = users[i];
    break;
  }
}
console.log(lastUser); // {id: 3, name: 'user3', age: 22}

// findLast() 사용
const lastUser = users.findLast(user => user.age > 18);
console.log(lastUser); // {id: 3, name: 'user3', age: 22}

마찬가지로 findLastIndex 메서드는 조건을 만족하는 마지막 요소의 인덱스를 찾아야 할 때 유용할 수 있습니다.

하루 종일 기록된 일련의 온도가 있고 온도가 30도를 초과한 마지막 인스턴스를 찾고 싶다고 가정해 보겠습니다.

// 이전 버전
const temperatures = [25, 28, 30, 32, 33, 31, 29];
let lastIndex = -1;
for (let i = temperatures.length - 1; i >= 0; i--) {
if (temperatures[i] > 30) {
lastIndex = i;
break;
}
}
console.log("Last index with temperature > 30:", lastIndex); => Last index with temperature > 30 (New): 5

// using findLastIndex()
const lastIndexNew = temperatures.findLastIndex(temp => temp > 30);
console.log("Last index with temperature > 30 (New):", lastIndexNew); => Last index with temperature > 30 (New): 5

2. Change Array by copy

ECMAScript 2023에서는 Array.prototype 및 TypedArray.prototype에 변경 사항을 유지한 채 배열을 수정할 수 있는 향상된 배열 메서드가 도입되었습니다.

2.1. toReversed

const months = ['January', 'February', 'March', 'April', 'May'];

// 이전 방법
const reversedMonths = months.reverse();
console.log(months); // ['May', 'April', 'March', 'February', 'January']; // 원래 배열이 변경됨
console.log(reversedMonths); // ['May', 'April', 'March', 'February', 'January'];

// toReversed() 사용
const reversedMonths = months.toReversed();
console.log(months); // ['January', 'February', 'March', 'April', 'May']; // 원래 배열은 변경되지 않음
console.log(reversedMonths); // ['May', 'April', 'March', 'February', 'January'];

2.2. toSorted

const prime = [13, 7, 17, 2];

// 이전 방법
const sortPrime = prime.sort();
console.log(prime); // [2, 7, 13, 17]; // 원래 배열이 변경됨
console.log(sortPrime); // [2, 7, 13, 17];

// toSorted() 사용
const sortPrime = prime.toSorted();
console.log(prime); // [13, 7, 17, 2]; // 원래 배열은 변경되지 않음
console.log(sortPrime); // [2, 7, 13, 17];

2.3. toSpliced

const numbers = [1, 2, 3, 4, 5, 6];

// 이전 방법
const spliceNumbers = numbers.splice(4, 1);
console.log(numbers); // [1, 2, 3, 4, 6]; // 원래 배열이 변경됨
console.log(spliceNumbers); // [1, 2, 3, 4, 6];

// toSpliced() 사용
const sortPrime = prime.toSorted(4, 1);
console.log(prime); // [1, 2, 3, 4, 5, 6]; // 원래 배열은 변경되지 않음
console.log(sortPrime); // [1, 2, 3, 4, 6];

2.4. with

const usernames = ['user1', 'user2', 'user3'];

// 이전 방법
usernames[1] = 'newUser';
console.log(usernames); // ['user1', 'newUser', 'user3']

// with() 사용
const updatedUsernames = usernames.with(1, 'newUser');
console.log(usernames); // ['user1', 'user2', 'user3'] // 원래 배열은 변경되지 않음
console.log(updatedUsernames); // ['user1', 'newUser', 'user3']

3. Hashbang Grammar

ECMAScript 2023에서 도입된 해시뱅(#!) 문법은 소스 코드에서 쉬뱅 표기법을 사용할 수 있게 합니다.

이 기능은 스크립트와 모듈을 구분하는 데 도움이 되며 빌드 도구와의 호환성을 향상하며 다른 언어와의 일관성을 제공합니다.

#!/usr/bin/env node

console.log('Hello from Hashbang Grammar!');

 

4. Symbols as WeakMap Keys

JavaScript에서 객체를 키로 사용하는 것은 때때로 원치 않는 부작용을 일으킬 수 있습니다. 객체는 참조 타입이므로 키로 사용하면 메모리 누수나 예상치 못한 동작이 발생할 수 있습니다. 이러한 문제를 해결하기 위해 불변하고 고유한 Symbol을 사용하여 키를 만들어 충돌을 방지할 수 있습니다.

// 이전 방법
const privateData = new Map();
const obj = {};

privateData.set(obj, 'This is private data');
console.log(privateData.get(obj)); // Output: "This is private data"

// WeakMap과 Symbol 사용
const privateData = new WeakMap();
const obj = {label: 'Private data'};

const key = Symbol('privateKey');
privateData.set(key, obj);
console.log(privateData.get(key)); // {label: 'Private data'}
반응형