JS 쓸만한 문법

WhereDo?·2024년 6월 18일

study

목록 보기
3/4

학습 이유

ECMAScript가 업데이트 되면서 추가된 새로운 js 문법을 학습하고 프로젝트에서 사용하고 싶어짐
실제로 사용할 것들만 정리

학습 목표

최신 js 문법 파악

ES2021(ES12)

??=, ||=, &&=

let a = null;
a ??= 10;
console.log(a); // 10

let b = 0;
b ||= 20;
console.log(b); // 20

let c = 5;
c &&= 15;
console.log(c); // 15
  • 백엔드로 부터 데이터 응답을 받을 때 데이터가 없을 경우(type이 정해져 있지 않아 데이터 유무를 확인해야할 경우) 위의 연산자를 쓰면 될 것 같음

String.prototype.replaceAll

문자열 내에 바꾸고 싶은 요소들을 한번에 바꿔줌

let str = "hello world";
let newStr = str.replaceAll("l", "L");
console.log(newStr); // "heLLo worLd"
  • 코테 풀 때 유용할 것 같기도 하고...

Promise.any(iterable)

Promise 객체들을 여러 개 묶어서 제일 먼저 성공한 promise 반환, 아무것도 성공하지 못하면 실패

let promises = [
  Promise.reject("Error 1"),
  Promise.resolve("Success 1"),
  Promise.reject("Error 2")
];

Promise.any(promises)
  .then(result => {
    console.log(result); // Output: "Success 1"
  })
  .catch(error => {
    console.error(error); // Output: AggregateError: All promises were rejected
  });
  • 네트워크 요청 여러 개 하고 그 중 제일 먼저 온 응답을 보여줄 때 사용?

숫자 구분 기호

// before
10000000000 // 100억
// after
10_000_000_000 // 100억
console.log(10_000_000_000); // 10000000000

ES2022(ES13)

Top-level Await Operator

비동기 함수 외부에서 await 연산자를 선언하여 동기화 문제를 해결
기존에는 await를 async 함수 내에서만 사용가능했지만 이제 모듈 최상위 레벨에서도 await가 사용이 가능

//기존
async function fetchData() {
  let response = await fetch('https://api.example.com/data');
  let data = await response.json();
  return data;
}

fetchData().then(data => {
  console.log(data);
});

//현재
import { fetchData } from './api';

const data = await fetchData(); // 최상위 레벨에서 await 사용

console.log(data);

Array.prototype.at(index)

Array[index]와 동일하나 index가 음수 인경우 index + array.length로 접근
기존에 array[array.length-1]로 마지막 요소를 가져왔다면 array.at(-1)이 가능

let sthList = ["foo", "bar", "baz"]
console.log(sthList.at(-1)) //baz

Object.hasOwn()

객체 내에 속성 존재 유무

const object1 = {
  prop: 'exists',
};

console.log(Object.hasOwn(object1, 'prop'));
// Expected output: true

console.log(Object.hasOwn(object1, 'toString'));
// Expected output: false

console.log(Object.hasOwn(object1, 'undeclaredPropertyValue'));
// Expected output: false
  • 내부 속성이 undefined거나 null이어도 존재하기만 하면 true를 반환
  • 상속되었거나 전혀 선언되지 않은 경우 false를 반환

ES2023(ES14)

Array.prototype.findLast
Array.prototype.findLastIndex

기존에 find함수는 array의 앞 부분부터 조건을 만족하는 요소를 찾아냄
ES14 부터는 뒤에서 부터 요소를 찾는 것이 가능

const numbers = [1,2,3,4,5]
const largestEvenNum = numbers.findLast(num => num % 2 === 0);
console.log(largestEvenNum); // 4

toReversed, toSorted, toSpliced, with

기존의 reverse, sort, splice 함수들은 원래 배열의 구조를 변경시켰으나 ES14부터는 위의 함수를 사용하여 원래의 배열을 보존하고 새로운 배열 사용이 가능
with를 사용하여 기존 배열의 요소를 변경할 때 원본을 유지하고 변경된 요소가 반영된 새로운 배열 사용이 가능

const users = ["jw", "cj", "dh", "gb", "sj"]
const reversedUsers = users.toReversed() // ["sj", "gb", "dh", "cj", "jw"]
const sortedUsers = users.toSorted() // ["cj", "dh", "gb", "jw", "sj"]
const splicedUsers = users.toSplice(3, 1) // ["jw", "cj", "dh", "sj"]
const changedUsers = users.with(1, "JW") // ["JW", "cj", "dh", "gb", "sj"]
console.log(users) // ["jw", "cj", "dh", "gb", "sj"]
profile
FE developer

0개의 댓글