이 페이지는 모든 언어로 번역되지 않았습니다. 번역이 없는 언어는 선택할 수 없습니다.

빠른 참조

JavaScript ES2015+ 빠른 참조

ES2015 이후 JavaScript 문법 예제와 참고 자료입니다.

· 게시일 · 수정일

ES2015, ES2016, ES2017, ES2018 이후의 기능을 다룹니다. 예제는 독립적이며 줄임표는 응용 코드의 생략을 뜻합니다.

블록 스코프

Let

function fn () {
  let x = 0
  if (true) {
    let x = 1 // only inside this `if`
  }
}

Const

const a = 1

let과 const는 블록 스코프, var는 함수 스코프입니다. const는 재할당을 막지만 객체를 동결하지 않습니다. let and const

템플릿 리터럴

보간

const message = `Hello ${name}`

여러 줄 문자열

const str = `
hello
world
`

템플릿은 보간과 여러 줄 문자열을 지원합니다. Template strings

이진 및 팔진 리터럴

let bin = 0b1010010
let oct = 0o755

Binary and octal literals

새 메서드

문자열 메서드

"hello".repeat(3)
"hello".includes("ll")
"hello".startsWith("he")
"hello".padStart(8) // "   hello"
"hello".padEnd(8) // "hello   "
"hello".padEnd(8, '!') // hello!!!
"\u1E9B\u0323".normalize("NFC")

New methods

클래스

class Shape {
  constructor (radius) { this.radius = radius }
  expand (n) { return this.radius * n }
}
class Circle extends Shape {

생성자

  constructor (radius) {
    super(radius)
    this.radius = radius
  }

메서드

  getArea () {
    return Math.PI * this.radius ** 2
  }

상위 클래스 메서드 호출

  expand (n) {
    this.radius = super.expand(n)
    return this
  }

정적 메서드

  static createFromDiameter(diameter) {
    return new Circle(diameter / 2)
  }
}

클래스 문법은 프로토타입에 기반합니다. 이 코드 조각은 하나의 예제를 이루며 파생 클래스 생성자는 this에 접근하기 전에 super를 호출합니다. Classes

거듭제곱

const byte = 2 ** 8
// Same as: Math.pow(2, 8)

Promise

Promise 만들기

new Promise((resolve, reject) => {
  if (ok) { resolve(result) }
  else { reject(error) }
})

Promise는 비동기 작업의 성공이나 실패를 나타냅니다. Promises

Promise 사용

promise
  .then((result) => { ··· })
  .catch((error) => { ··· })

finally 사용

promise
  .then((result) => { ··· })
  .catch((error) => { ··· })
  .finally(() => { /* logic independent of success/error */ })

이행 핸들러는 결과를 받고 거부 핸들러는 오류를 받습니다. finally는 처리 완료 후 실행되며 두 값 모두 받지 않습니다.

Promise 보조 메서드

Promise.all(···)
Promise.race(···)
Promise.reject(···)
Promise.resolve(···)

async / await

async function run () {
  const user = await getUser()
  const tweets = await getTweets(user)
  return [user, tweets]
}

async 함수는 Promise를 반환합니다. await는 피연산자의 결과가 확정될 때까지 함수 실행을 일시 중단합니다.

Async functions

구조 분해

구조 분해 할당

배열

const [first, last] = ['Nikola', 'Tesla']

객체

let {title, author} = {
  title: 'The Silkworm',
  author: 'R. Galbraith'
}

구조 분해는 배열의 값과 객체의 속성을 추출합니다. Destructuring

기본값

const scores = [22, 33]
const [math = 50, sci = 50, arts = 50] = scores
// Result:
// math === 22, sci === 33, arts === 50

기본값은 undefined에 적용되고 null에는 적용되지 않습니다.

함수 매개변수

function greet({ name, greeting }) {
  console.log(`${greeting}, ${name}!`)
}
greet({ name: 'Larry', greeting: 'Ahoy' })

함수 매개변수에서도 배열과 객체를 구조 분해할 수 있습니다.

기본값

function greet({ name = 'Rauno' } = {}) {
  console.log(`Hi ${name}!`);
}
greet() // Hi Rauno!
greet({ name: 'Larry' }) // Hi Larry!

속성 이름 바꾸기

function printCoordinates({ left: x, top: y }) {
  console.log(`x: ${x}, y: ${y}`)
}
printCoordinates({ left: 25, top: 90 })

left 속성은 지역 변수 x에, top은 y에 대입됩니다.

반복문

for (let {title, artist} of songs) {
  ···
}

반복문 변수 선언에도 구조 분해를 사용할 수 있습니다.

객체 구조 분해

const { id, ...detail } = song;

객체의 나머지 문법은 선택한 속성을 제외한 열거 가능한 자체 속성을 모읍니다.

전개 구문

객체 전개

객체 전개 사용

const options = {
  ...defaults,
  visible: true
}

객체 전개 없이

const options = Object.assign(
  {}, defaults,
  { visible: true })

객체 전개는 열거 가능한 자체 속성의 얕은 복사를 만듭니다. 뒤쪽 속성이 앞쪽 속성을 덮어씁니다.

Object spread

배열 전개

배열 전개 사용

const users = [
  ...admins,
  ...editors,
  'rstacruz'
]

배열 전개 없이

const users = admins
  .concat(editors)
  .concat([ 'rstacruz' ])

배열 전개는 반복 가능한 값에서 새 배열을 만듭니다.

Spread syntax

함수

함수 매개변수

기본 매개변수

function greet (name = 'Jerry') {
  return `Hello ${name}`
}

나머지 매개변수

function fn(x, ...y) {
  // y is an Array
  return x * y.length
}

전개 구문

fn(...[1, 2, 3])
// same as fn(1, 2, 3)

기본 매개변수, 나머지 매개변수 및 인수 전개입니다. Function parameters

화살표 함수

화살표 함수

setTimeout(() => {
  ···
})

매개변수 사용

readFile('text.txt', (err, data) => {
  ...
})

암시적 반환

numbers.map(n => n * 2)
// No curly braces = implicit return
// Same as: numbers.map(function (n) { return n * 2 })
numbers.map(n => ({
  result: n * 2
}))
// Implicitly returning objects requires parentheses around the object

화살표 함수는 바깥 스코프의 this를 사용하며 생성자로 쓸 수 없습니다. Arrow functions

객체

속성 축약

module.exports = { hello, bye }
// Same as: module.exports = { hello: hello, bye: bye }

Enhanced object literals

메서드

const App = {
  start () {
    console.log('running')
  }
}
// Same as: App = { start: function () {···} }

Enhanced object literals

게터와 세터

const App = {
  get closed () {
    return this.status === 'closed'
  },
  set closed (value) {
    this.status = value ? 'closed' : 'open'
  }
}

Enhanced object literals

계산된 속성 이름

let event = 'click'
let handlers = {
  [`on${event}`]: true
}
// Same as: handlers = { 'onclick': true }

Enhanced object literals

값과 항목

const fatherJS = { age: 57, name: "Brendan Eich" }

Object.values(fatherJS)
// [57, "Brendan Eich"]
Object.entries(fatherJS)
// [["age", 57], ["name", "Brendan Eich"]]

모듈

가져오기

import 'helpers'
// aka: require('···')
import Express from 'express'
// aka: const Express = require('···').default || require('···')
import { indent } from 'helpers'
// aka: const indent = require('···').indent
import * as Helpers from 'helpers'
// aka: const Helpers = require('···')
import { indentSpaces as indent } from 'helpers'
// aka: const indent = require('···').indentSpaces

ES 임포트와 CommonJS require는 서로 다른 모듈 방식입니다. 주석은 관련 사용 사례를 보여 줍니다. Module imports

내보내기

export default function () { ··· }
// aka: module.exports.default = ···
export function mymethod () { ··· }
// aka: module.exports.mymethod = ···
export const pi = 3.14159
// aka: module.exports.pi = ···

export는 ES 모듈의 내보내기를 선언합니다. 의미는 CommonJS module.exports와 다릅니다. Module exports

제너레이터

제너레이터

function* idMaker () {
  let id = 0
  while (true) { yield id++ }
}
let gen = idMaker()
gen.next().value  // → 0
gen.next().value  // → 1
gen.next().value  // → 2

제너레이터는 이터레이터를 반환하고 yield에서 일시 중단됩니다. Generators

for-of 반복

for (let i of iterable) {
  ···
}

for-of는 배열이나 제너레이터처럼 반복 가능한 객체의 값을 순회합니다. For-of iteration

컬렉션 도구

const unique = [...new Set([1, 1, 2])];
const scores = new Map([["Ada", 10]]);
for (const [name, score] of scores) console.log(name, score);

참고 자료

MDN JavaScript guide

관련 주제