JS

Javascript ES13 문법정리

Kir93 2023. 12. 4. 18:10
728x90
반응형

1. Top-level await(최상위 await)

지금까지 JavaScript에서는 await 키워드를 async 함수 내에서만 사용할 수 있었습니다.

그러나 ECMAScript 2022에서는 최상위 모듈에서도 Promise를 기다리기 위해 await 키워드를 사용할 수 있게 되었습니다.

이를 통해 부모 모듈의 실행이 자식 모듈의 실행이 완료될 때까지 기다리게 됩니다.

// before
await Promise.resolve(console.log("Inkoop"))
// SyntaxError: await is only valid in async function

const print = async () => {
  await Promise.resolve(console.log("Inkoop"))
}

print() // 결과: Inkoop

// ES13
await Promise.resolve(console.log("Inkoop")) // Inkoop

2. Private Class Fields and Methods

기본적으로 JavaScript의 클래스 필드와 메서드는 public이었습니다.

이는 이러한 필드 및 메서드가 전역적으로 접근 가능하며 클래스 외부에서 읽거나 수정할 수 있다는 것을 의미합니다.

그러나 ES2022에서는 클래스 필드 또는 메서드를 개인(private)으로 만들기 위해 해시 #을 접두사로 사용할 수 있게 되었습니다.

이를 통해 #으로 시작하는 필드와 메서드는 JavaScript 사양에서 자체적으로 비공개로 만들어지며 클래스 내부에서만 접근 가능합니다.

class MyClass {
  #firstName = "Lorem"
  lastName = "Ipsum"

  printPrivateField() {
    console.log(this.#firstName)
  }

  #sayBye() {
    console.log("Bye")
  }
}

const instance = new MyClass()
console.log(instance.#firstName) // SyntaxError: Private field '#firstName' must be declared in an enclosing class
console.log(instance.lastName) // Ipsum
instance.printPrivateField() // Lorem
instance.#sayBye() // SyntaxError: Private field '#sayBye' must be declared in an enclosing class

3. at() 메서드 (String, Array 및 TypedArray용)

ES2022에서는 String, Array 및 TypedArray에 새로운 at() 메서드가 추가되었습니다.

이 메서드를 사용하여 배열 또는 문자열의 요소를 역방향으로 액세스 할 수 있습니다.

at() 메서드는 음수 인덱싱을 지원하므로 이제 음수 인덱스를 사용하여 배열이나 문자열의 요소에 접근할 수 있습니다.

const array = ["inkoop", "draxlr", "sup"]

// before
const lastItem = array[array.length - 1]
console.log(lastItem) // 결과: sup

// ES13
const lastElement = array.at(-1)
console.log(lastElement) // 결과: sup
console.log(array.at(-2)) // 결과: draxlr
console.log(array.at(0)) // 결과: inkoop

4. Object.hasOwn 메서드

Object.hasOwn 메서드는 객체에 특정 속성이 있는지 여부를 확인하는 데 사용됩니다.

이 메서드는 Object.prototype.hasOwnProperty 메서드의 편리한 대안입니다.

Object.prototype.hasOwnProperty는 오랫동안 JavaScript 사양에 존재했지만 몇 가지 단점이 있었습니다.

이러한 문제를 극복하기 위해 ES2022에서는 Object.hasOwn 메서드가 도입되었습니다.

const object = {
  name: "Draxlr",
}

console.log(object.hasOwnProperty("name")) // 결과: true
console.log(object.hasOwnProperty("hasOwnProperty")) // 결과: false

const object2 = Object.create(null)
object2.name = "lorem"
console.log(object2.hasOwnProperty("name")) // TypeError: object2.hasOwnProperty is not a function

console.log(Object.hasOwn(object2, "name")) // 결과: true

const object3 = {
  name: "JavaScript",
  hasOwnProperty() {
    return false
  },
}
console.log(object3.hasOwnProperty("name")) // 결과: false

console.log(Object.hasOwn(object3, "name")) // 결과: true
console.log(Object.hasOwn(object3, "hasOwnProperty")) // 결과: true

5. RegExp match indices

정규 표현식의 새로운 기능 중 하나로 매치 색인(match indices)이 추가되었습니다.

이 기능을 사용하면 캡처된 부분 문자열의 시작 및 끝 색인에 대한 추가 정보를 얻을 수 있습니다.

const str = "next time there won't be a next time."

// d 플래그 없이
const regex = /(next)/g
console.log(...str.matchAll(regex))

// d 플래그 함께
const regex2 = /(next)/dg
console.log(...str.matchAll(regex2))

6. Ergonomic brand checks for Private Fields

ES2022에서 개인 필드에 대한 에르고노믹 브랜드 확인 기능이 추가되었습니다.

클래스 내에서 개인 필드가 있는지 여부를 확인하기 위해 in 연산자를 사용할 수 있습니다.

class User {
  #name = "Random User"

  static isNamePresent(object) {
    console.log(#name in object)
  }
}
const instance = new User()

User.isNamePresent(instance) // 결과: true
User.isNamePresent({}) // 결과: false
반응형