본문 바로가기
Language/JavaScript

[JS] ES6 특징

by 오우영 2021. 6. 22.

ECMAScript란?

ES는 자바스크립트를 이루는 코어(Core)스크립트 언어로써, 다양한 환경에서 운용될 수 있게 확장성을 갖고 있기때문에 사용처가 웹환경으로 국한되어 있지는 않습니다. 자바스크립트는 웹브라우저에서 돌아갈 수 있도록 BOM과 DOM을 함께 사용하는 확장성이 됩니다. 이러한 확장성들은 ES 버전에 따른 문법과 기능의 확장을 가능하게 합니다.

 

DOM (Document Object Model) : 문서 객체 모델
문서 객체 모델은 객체지향 모델로써 구조화된 문서를 표현하는 형식입니다
-> 문서, 즉 열려진 페이지에 대한 정보를 따로 객체화 시켜서 관리합니다
BOM (Browser Object Model) : 브라우저 객체
BOM은 자바스크립트가 브라우저와 소통하기 위해서 만들어진 모델입니다
-> 뒤로가기, 북마크, 즐겨찾기, 히스토리, URL 정보 등..
-> 브라우저가 가지고 있는 정보를 따로 객체화 시켜 관리합니다

 

ES 히스토리

ES3 (1999)
1. 대중적으로 알고있는 자바스크립트
2. 함수 단위의 스코프, 호이스팅, 클로저, 프로토 타입 등 우리가 익히 알고있는 자바스크립트의 기본적인 특징들을 갖고있다
ES5 (2009)
1. ES4는 너무 시대의 흐름을 앞서갔는지 거절
2. 배열과 관련된 편리한 메소드들이 다수 생겼다
-> forEach, map, reduce, filter, some, every 등
3. 객체 프로퍼티에 대한 설정이 가능해짐
-> Object.Create(), Object.defindProperty(), Object.freeze(), Object.assign() 등
-> gerrer, setter 추가, Object.keys() 메소드를 이용하면 for in 메소드도 대체
4. strict 모드 문법으로 자유분방하던 기존 ES를 안전하고 개발자가 인지할 수 있는 범위 안에서 개발하도록 사용하기 위해 등장
5. bind() 메소드의 등장으로 this를 강제로 바인딩이 가능해짐
ES6 (ES2015) ⭐️⭐️⭐️
ES6보다 ES2015라고 많이 불리우며, ES6 Harmony라고도 불린다
1. 기본 매개 변수 (Default Parameters)
2. 템플릿 리터럴 (Template Literals)
3. 멀티 라인 문자열 (Multi-line Strings)
4. 비구조화 할당 (Destructuring Assignment)
5. 향상된 객체 리터럴 (Enhanced Object Literals)
6. 화살표 함수 (Arrow Functions)
7. Promises
8. 블록 범위 생성자 Let 및 Const (Block-Scoped Constructs Let and Const)
9. 클래스 (Classes)
10. 모듈 (Modules)
ES7 (ES2016)
1. 제곱 연산자 등장 (**)
2. Array.includes 배열에 해당 요소가 존재하는지 확인하는 메소드 등장
ES8 (ES2017)
1. async, await
2. Object.entries(), Object.getOwnPropertyDescriptor() 등 객체의 심화된 메소드들이 등장
3. 매개변수 마지막에 콤마를 붙이는걸 허용
Object.getOwnPropertyDescriptor ?
객체 자신의 속성, 즉 객체 프로토타입 체인을 따라 존재하는 것이 아닌 객체에 직접 제공하는 속성에 대한 속성 설명자(descriptor)를 반환하는 메서드
ES9 (2018)
1. Rest/ Spread Properties : 전개 구문은 기존에 iterable에만 사용이 가능했는데 ES9에서 객체에서도 사용 가능해짐
2. Promise.prototype.finally(): then과 catch만 가능하던 promise에 finally가 추가
-> Promise가 처리된 후 성공 여부에 관계없이 실행되며 Promise 객체를 반환
ES10 (2019)
1. Array.prototype.flat, Array.prototype.flatMap : 다중배열을 펼치는 기능
2. Optional Catch : error 매개변수를 쓰지 않으면 생략 가능
ES11 (2020)
1. Optional Chaining
2. Nullish Coalescing Operator
ES12 (2021)
1. Promise.any
-> 배열의 promise를 받아서 해당 배열의 promise 중 가장 먼저 resolve 처리가 되는 promise를 반환 해주는 메소드 입니다. 이때 모든 promise가 실패할 경우는 모든 promise가 실패했다고 에러를 반환합니다. 이를 통해 여러 요소중 가장 빠른 값을 가져와 처리해야하는 상황에서 유용하게 사용이 가능합니다
2. 논리 할당 연산자 (Logical Operators and Assignment Expressions)
-> 새로운 논리 할당 연산자  &&=,  ||=,  ??=  를 사용하여 논리 연산을 기반으로 변수에 값을 할당 할 수 있습니다

 

ES6

1. 기본 매개 변수 (Default Parameters)

//ES5

var link = function (height, color) {
    var height = height || 50
    var color = color || 'red'
}

//ES6

var link = function(height = 50, color = 'red') {}
ES5에서는  ||  처리 시 0 또는 false 값이 입력 되어도 거짓이 되므로 기본값으로 대체된다
하지만 ES6의 기본 매개 변수를 사용하면 undefined를 제외한 모든 값을 인정한다


2. 템플릿 리터럴 (Template Literals)

// ES5

var name = 'Your name is ' + first + ' ' + last + '.'

// ES6

var name = `Your name is ${first} ${last}.`


3. 멀티 라인 문자열 (Multi-line Strings)

// ES5

var roadPoem = 'Then took the other, as just as fair,\n\t'
    + 'And having perhaps the better claim\n\t'
    + 'Because it was grassy and wanted wear,\n\t'
    + 'Though as for that the passing there\n\t'
    + 'Had worn them really about the same,\n\t'
    
// ES6

var roadPoem = `Then took the other, as just as fair,
    And having perhaps the better claim
    Because it was grassy and wanted wear,
    Though as for that the passing there
    Had worn them really about the same,`


4. 비구조화 할당 (Destructuring Assignment)

// ES5

// browser
var data = $('body').data(),
  house = data.house,
  mouse = data.mouse

// Node.js
var jsonMiddleware = require('body-parser').json

var body = req.body,
  username = body.username,
  password = body.password
  

// ES6

var {house, mouse} = $('body').data()

var {jsonMiddleware} = require('body-parser')

var {username, password} = req.body
할당하려는 변수명과 구조화된 데이터의 property명이 같아야 한다
또한, 구조화된 데이터가 아니라 배열의 경우 {} 대신 [] 를 사용해서 위와 유사하게 사용할 수 있다


5. 향상된 객체 리터럴 (Enhanced Object Literals)

// ES5

var serviceBase = {port: 3000, url: 'fz7948.tistory.com'},
    getAccounts = function(){return [1,2,3]}

var accountServiceES5 = {
  port: serviceBase.port,
  url: serviceBase.url,
  getAccounts: getAccounts,
  toString: function() {
    return JSON.stringify(this.valueOf())
  },
  getUrl: function() {return "http://" + this.url + ':' + this.port},
  valueOf_1_2_3: getAccounts()
}

// ES6

var serviceBase = {port: 3000, url: 'fz7948.tistory.com'},
    getAccounts = function(){return [1,2,3]}
var accountService = {
    __proto__: serviceBase,
    getAccounts,
    toString() {
     return JSON.stringify((super.valueOf()))
    },
    getUrl() {return "http://" + this.url + ':' + this.port},
    [ 'valueOf_' + getAccounts().join('_') ]: getAccounts()
};
ES5와의 차이
1. __proto__ 속성을 사용해서 바로 프로토타입을 설정할 수 있다
2. getAccounts: getAccounts, 대신 getAccounts, 를 사용할 수 있다 (변수명으로 속성 이름을 지정)
3. [ 'valueOf_' + getAccounts().join('_') ] 와 같이 동적으로 속성 이름을 정의할 수 있다
-> onChange로 여러 키값을 정의할때도 사용된다


6. 화살표 함수 (Arrow Functions)

// ES5

var ids = ['5632953c4e345e145fdf2df8', '563295464e345e145fdf2df9'];
var messages = ids.map(function (value, index) {
  return 'ID of ' + index + ' element is ' + value + ' '
});

// ES6

var ids = ['5632953c4e345e145fdf2df8','563295464e345e145fdf2df9']
var messages = ids.map((value, index) => `ID of ${index} element is ${value} `)


7. Promises

ES6에서는 표준 Promise가 제공된다.

 

// ES5

setTimeout(function(){
  console.log('Yay!')
}, 1000)

// ES6

var wait1000 =  new Promise(function(resolve, reject) {
  setTimeout(resolve, 1000)
}).then(function() {
  console.log('Yay!')
})


8. 블록 범위 생성자 Let 및 Const (Block-Scoped Constructs Let and Const)

 

참고 자료 https://fz7948.tistory.com/22#Scope

 

[JS] 기초

배열 객체 Primitive, Reference, Rest Parameter, spread operator Scope Closure 1. 배열 순서가 있는 값 인덱스(index) [0] [1] [2] [3] [4] 요소(element) 73 98 86 61 96 let myNumber = [73, 98, 86, 61, 96..

fz7948.tistory.com


9. 클래스 (Classes)

ES6에는 class 키워드가 추가되어 ES5의 prototype 기반 상속보다 명확하게 class를 정의할 수 있다
get과 set 키워드 외에도 static 키워드를 사용해 static 메소드를 정의하는 것도 가능하다

 

class baseModel {
  constructor(options = {}, data = []) { // class constructor
    this.name = 'Base'
    this.url = 'http://fz7948.tistory.com'
    this.data = data
    this.options = options
    }

  getName() { // class method
      console.log(`Class name: ${this.name}`)
  }
}


10. 모듈 (Modules)

// ES5

module.exports = {
  port: 3000,
  getAccounts: function() {
    ...
  }
}

var service = require('module.js')
console.log(service.port) // 3000

// ES6

export var port = 3000
export function getAccounts(url) {
  ...
}

import {port, getAccounts} from 'module'
console.log(port) // 3000

 

참조 https://blog.asamaru.net/2017/08/14/top-10-es6-features/

'Language > JavaScript' 카테고리의 다른 글

[JS] undefined, null  (0) 2021.06.24
[JS] Iterable object, Array-like object  (0) 2021.06.23
[JS] 프로토타입과 클래스  (0) 2021.02.26
[JS] OOP  (0) 2021.02.26
[JS] 구조 분해  (0) 2021.02.25

댓글