# ECMAScript6 Overview and Comparison
1. String Literal (backtick)
const name = 'Brian';
const welcome = 'Welcome to Our Website!'
consol.log(`${name}..! ${welcome}`);
// "Brian..! Welcome to Our Website!" 로 출력됨
2. Object
// # [Object Destructuring]
const movie ={
name : '바람과 함께 사라지다',
country : 'Korea',
release_date : '1999-08-01',
star : 4.8,
}
const {name, star} = movie;
console.log(`${name} : 평점 ${star}`); // "바람과 함께 사라지다 : 평점 4.8" 으로 출력
// # [Object Properties Initialization]
const makeMovieInfo = (name, star) => {
const obj = {name, star};
return obj;
};
const movieInfo = makeMovieInfo("바람과 함께 사라지다","4.8");
console.log(movieInfo); // "{ name: '바람과 함께 사라지다', star: '4.8' }" 으로 출력
3. Extended Parameter Handling
// # [Default Parameter Values]
function f(x, y=7, z=42){
return x+y+z;
}
console.log(f(1)); //50
// # [Rest Parmeter] - 가변인자
function func1(x,y, ...args){ // rest param 은 배열에 담긴다. 접근할때 args[idx] 로 접근
return args.length;
}
console.log(func1(1,2, "foo", false, {name:"sun",age:"50"})); // 3
// # [Spread Operator] - iterable collection 의 아이템을 복사해준다 생각하면 된다.
const params = ["sun",false,7];
const other = [1,2, ...params]; // [1,2, "sun",false,7]
const str = "foo";
const char = [1, ...str]; // [1, "f","o","o"]
// object 를 합칠때, 프로퍼티가 겹치면, 뒤의 object의 value를 따름.
const userBase = {name:"Sun",age:29};
const userAddress = {city:"Daegu",street:"Queen St"};
const user = {...userBase, ...userAddress}; // {name:"Sun",age:29,city:"Daegu",street:"Queen St"}
4. 반복문
const fruit = ["apple","banna","monkey","kiwi"];
// ES5 (break 사용불가능)
fruit.forEach((it)=>{
console.log(it);
})
// ES6 (break 사용가능)
for(let it of fruit){
console.log(it);
if(it=="monkey"){
console.log("This is hell not fruit..!");
break;
}
}
5. Arrow Function
// ES5
function add(x,y){
return x+y;
}
// ES6
const add2 = (x,y) => x+y; // 바로 리턴할 때
const add3 = (x,y) =>{ // 다른연산을 수행할 때
const c = "result : ";
return c+(x+y);
};
console.log(add2(1,3)); //4
console.log(add3(1,3)); //result : 4
6. 유용한 배열 메소드
const fruit = ['apple', 'banana', 'kiwi'];
console.log(fruit.includes('banana')); // true
console.log(fruit.indexOf('kiwi')); // 2
7. Map, Set 자료구조 추가
const map = new Map();
map.set("Sun",29);
map.set("Brian",27);
console.log(map); // Map(2) { 'Sun' => 29, 'Brian' => 27 }
console.log(map.get("Sun")); // 29
console.log(map.has("Brian")); // true
const set = new Set();
set.add("Sun"); set.add("Sun");
set.add("Brian"); set.add("Brian");
set.add(1); set.add(1); set.add(1);
console.log(set); // Set(3) { 'Sun', 'Brian', 1 }