[JS] ECMAScript

Hadam Cho·2021년 5월 24일
2

Frontend

목록 보기
2/8
post-thumbnail

자바스크립트의 표준화

크로스 브라우징 이슈

마이크로소프트에서 자바스크립트의 파생 버전인 JScript를 인터넷 익스플로러 3.0에 탑재

넷스케이프 커뮤니케이션즈(자바스크립트)와 마이크로소프트(JScript)는 자사 브라우저의 시장 점유율을 높이기 위해 자사 브라우저에서만 동작하는 기능을 경쟁적으로 추가하기 시작

⇒ 브라우저에 따라 웹페이지가 정상적으로 동작하지 않는 크로스 브라우징 이슈 발생

ECMAScript

넷스케이프 커뮤니케이션즈가 ECMA 인터내셔널(컴퓨터 시스템의 표준을 관리하는 비영리 표준화 기구)에 자바스크립트의 표준화 요청

상표권 문제로 ECMAScript로 명명


ES6

Symbol

원시 데이터 형(primitive data type)으로 객체 프로퍼티에 대한 고유한 식별자

console.log(Symbol('foo') === Symbol('foo'));	// false

Map

키-값 쌍을 저장하며, 각 쌍의 삽입 순서를 기억하는 컬렉션
에는 모든 데이터 타입을 사용할 수 있음

Object와의 차이점

  • Map은 어떤 기본 키도 가지지 않지만, Object는 프로토타입으로 인한 기본 키가 존재할 수 있음
  • Map의 키는 모든 값이 가능하지만, Object는 String 또는 Symbol이어야 함
  • Map.prototype.size
  • Map은 순회 가능함
  • Map은 키-값 쌍의 추가와 제거에서 더 좋은 성능을 보임

WeakMap

가 Object형이어야 하며, GC에 의해 제거될 수 있음
열거할 수 없음


Set

자료형에 관계없이 유일한 값을 저장함

WeakSet

객체만의 컬렉션으로, GC 될 수 있음
열거할 수 없음


iterable

반복 가능한 객체

const str = 'hello';
str[Symbol.iterator];	// [Function]

// https://helloworldjavascript.net/pages/260-iteration.html

Symbol.iterator 속성에 함수가 들어있으면 iterable이라고 함

사용 가능 기능

  • for of
  • spread operator
  • destructuring
  • iterable을 인수로 받는 함수 사용

Generator를 이용하면 iterable을 만들 수 있음


Generator

iterable object를 반환하는 특별한 형태의 함수

const gen = function* () {
  yield 1;
  yield 2;
}
const iterable = gen();

for (let num of iterable) {
  console.log(num);	// 1, 2
}

// https://helloworldjavascript.net/pages/260-iteration.html#generator-함수

주의사항
Generator 함수로 생성된 iterable은 한 번만 사용 가능함


Proxy

new Proxy(target, handler)

target에 가해지는 읽기, 쓰기와 같은 작업을 handler에서 중간에 가로채는 객체

예시

let numbers = [0, 1, 2];

numbers = new Proxy(numbers, {
  get(target, prop) {
    if (prop in target) {
      return target[prop];
    } else {
      return 0; // 기본값
    }
  }
});

alert( numbers[1] ); // 1
alert( numbers[123] ); // 0 (해당하는 요소가 배열에 없으므로 0이 반환됨)

// https://ko.javascript.info/proxy

ES8

Object.getOwnPropertyDescriptors

특정 프로퍼티에 대한 정보를 얻음

const person = { name: 'Hadam' };
const descriptor = Object.getOwnPropertyDescriptors(person, 'name');
console.log(descriptor);
/*
{name: {
    configurable: true,
    enumerable: true,
    value: 'Hadam',
    writable: true
}}
*/

ES9

Object rest & spread property

const { x, ...remaining } = { x: 1, a: 2, b: 3 };
console.log(x);	// 1
console.log(remaining);	// { a: 2, b: 3 }

const sample = { x: 1, y: 2 };
const newObject = { ...sample, z: 3 };
console.log(newObject);	// {  x: 1, y: 2, z: 3 }

// https://nitayneeman.com/posts/object-rest-and-spread-properties-in-ecmascript-2018/

async generator, for await of

Generator에서 await을 사용해야 할 때, async를 Generator 함수 앞에 붙여 사용

const generateSequence = async function* (start, end) {
  for (let i = start; i <= end; i++) {
    await new Promise(resolve => setTimeout(resolve, 1000));
    yield i;
  }
}

(async () => {
  let generator = generateSequence(1, 5);
  for await (let value of generator) {
    alert(value); // 1, 2, 3, 4, 5
  }
})();

// https://ko.javascript.info/async-iterators-generators

ES10

Object.fromEntries

키-값 쌍의 목록을 객체로 변환

const entries = new Map([
  ['foo', 'bar'],
  ['baz', 42]
]);

const obj = Object.fromEntries(entries);

console.log(obj);
// expected output: Object { foo: "bar", baz: 42 }

Array.prototype.flat

중첩 배열 구조를 평탄화한 새로운 배열 생성

const arr1 = [1, 2, [3, 4]];
arr1.flat();
// [1, 2, 3, 4]

// https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/flat

Array.prototype.flatMap

각 엘리먼트에 대해 map 수행 수, 깊이 1로 평탄화된 새로운 배열 반환

arr1.flatMap(x => [x * 2]);
// [2, 4, 6, 8]

// https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap

optional catch binding

catch 매개변수에 에러를 전달하지 않고 에러 처리를 간단히 수행

try {
  throw new Error('Oops')
} catch {
  console.error('Oh no... something went wrong...')
}

// https://sergioviniciuss.medium.com/optional-catch-binding-es2019-is-coming-c5f8eb249f6c

ES11

String.prototype.matchAll

정규표현식과 일치하는 모든 결과를 iterator로 반환

const regexp = /t(e)(st(\d?))/g;
const str = 'test1test2';

const array = [...str.matchAll(regexp)];

console.log(array[0]);
// expected output: Array ["test1", "e", "st1", "1"]

console.log(array[1]);
// expected output: Array ["test2", "e", "st2", "2"]

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll

BigInt

Number(2⁵³ - 1)보다 큰 정수를 표현할 수 있는 내장 객체

// 정수 리터럴n
const theBiggestInt = 9007199254740991n;
// BigInt()
const alsoHuge = BigInt(9007199254740991);

// https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/BigInt

globalThis

전역 this 값을 가진 전역 객체 반환


Promise.allSettled

배열이나 iterable을 통해 나열된 Promise 모음이 모두 이행 혹은 거부 되었을 때에 대응할 수 있는 Promise 객체 반환

const promise1 = Promise.resolve(3);
const promise2 = new Promise((resolve, reject) => setTimeout(reject, 100, 'foo'));
const promises = [promise1, promise2];	// Promise 모음

Promise.allSettled(promises).
  then((results) => results.forEach((result) => console.log(result.status)));

// expected output:
// "fulfilled"
// "rejected"

// https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled

Nullish coalescing operator

왼쪽 피연산자가 null 또는 undefined일 때는 오른쪽 피연산자, 아닐 때는 왼쪽 피연산자를 반환하는 논리 연산자

const foo = null ?? 'default string';
console.log(foo);
// expected output: "default string"

const baz = 0 ?? 42;
console.log(baz);
// expected output: 0

// https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator

Optional chaining operator

각 프로퍼티가 유효한지 명시적으로 검증하지 않고 객체 체인 내 프로퍼티를 읽을 수 있는 연산자
(존재하지 않으면 undefined를 리턴)

const adventurer = {
  name: 'Alice',
  cat: {
    name: 'Dinah'
  }
};

const dogName = adventurer.dog?.name;
console.log(dogName);
// expected output: undefined

// https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Optional_chaining

for in enumeration order

ECMAScript® 2020 Language Specification - 13.7.5

profile
(。・∀・)ノ゙

0개의 댓글