ES6 (ECMAScript 2015)
2015년도에 도입된 JavaScript 버전으로 새로운 기능과 구문들이 도입이 되었다.
1. let / const 키워드
2. 화살표 함수 (Arrow Function)
const arrow_func = (a,b) => a + b;
3. 템플릿 리터럴 (Template Literal)
const response = await axios.get(`http://localhost:8080/api/member/${memberId}`);
4. 객체 리터럴 (Object Literal)
- 변수명과 프로퍼티 키가 동일한 이름이라면 프로퍼티 키를 생략할 수 있다.
const name = 'dongwook';
const age = 26;
const person = { name, age };
- 객체 리터럴 내부에서도 프로퍼티명으로 프로퍼티 키를 동적 생성할 수 있다.
const dynamicKey = 'hello';
const obj = {
[dynamicKey]: 'world';
};
console.log(obj); // { hello: 'world' }
- 객체 리터럴 내부에서 메서드를 정의하고자 할때
function()
키워드를 생략하여 사용할 수 있다.
const obj = {
callFunc() { return 'call Function'; }
};
obj.callFunc(); // 'call Function'
5. 구조 분해 할당 (Destructuring)
// 배열 구조 분해 할당
const [ firstElement, secondElement ] = [ 1, 2 ];
// 객체 구조 분해 할당
const { name, age } = { 'dongwook', 26 };
6. 프로미스 (Promise)
const asyncFunc = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
const currentDate = new Date();
if(currentDate.getFullYear() > 2022) {
resolve('Success!');
} else {
reject(new Error('Failed'));
}
}, 1000);
});
}
7. for ... of 구문
- 해당 구문을 사용하기 위해서는 객체가
[Symbol.iterator]
속성을 지니고 있어야 함
const oddElement = [ 1, 3, 5, 7, 9 ];
for( const element of oddElement) {
console.log(element); // 1, 3, 5, 7, 9
}
8. 전개 연산자 / 나머지 매개변수 (spread operator / rest parameter)
// 전개 연산자 (spread operator)
const numList = [ 1, 2, 3, 4, 5 ];
const newNumList = [ ...numList, 6, 7, 8 ];
console.log(newNumList); // [ 1, 2, 3, 4, 5, 6, 7, 8 ]
// 나머지 매개변수 (rest parameter)
const addNumList = (...numList) => {
return numList.reduce((total, current) => total + current, 0);
}
9. 기본 매개변수 (default parameter)
const createElement = (width = '300px', height = '300px') => {
let element = document.createElement('div');
element.style.width = width;
element.style.height = height;
document.body.appendChild(element);
return element;
}
10. Symbol
- ES6에서 새롭게 추가된 변경 불가능한 원시 타입의 값
- 이름의 충돌 위험이 없는 유일한 객체의 프로퍼티 키(property key)를 만들기 위해 사용
const symbol = Symbol("foo");
typeof symbol // "symbol"
const symbolObject = Object(symbol);
typeof symbolObject // "object"
11. Map / Set
// Map
const memberMap = new Map([
['A', 26],
['B', 52],
['C', 56]
])
for(const name of memberMap.keys()) {
console.log(name) // A B C
}
for(const age of memberMap.values()) {
console.log(age) // 26, 52, 56
}
for (const entry of memberMap) {
console.log(entry) // A,26 ...
}
// Set
const firstNumSet = new Set([ 1, 2, 3, 4 ]);
const secondNumSet = new Set([ 3, 5, 7, 8 ]);
const union = new Set([...firstNumSet, ...secondNumSet]);
console.log([...union]); // [1,2,3,4,5,7,8]
const intersection = new Set([...firstNumSet].filter((value) => secondNumSet.has(value)));
console.log([...intersection]); // [3]
const difference = new Set([...firstNumSet].filter((value) => !secondNumSet.has(value)));
console.log([...difference]); // [1,2,4]