let
변수 선언 키워드와 상수 선언 키원드 const
가 추가되었다.var
키워드만 있었을 때 보다 예측 가능한 코드를 작성 할 수 있게 되었다*메소드
에 더 이상 콜론(:) 이나 function을 붙이지 않아도 된다.*const ellie1 = {
name: 'Ellie',
age: '18',
};
const name = 'Ellie2';
const age = '20';
// 이전
const ellie2 = {
name: name,
age: age,
};
// 이후
const ellie3 = {
name,
age,
}
console.log(ellie1, ellie2, ellie3);
// {name: "Ellie", age: "18"}
// {name: "Ellie2", age: "20"}
// {name: "Ellie2", age: "20"}
구조 분해 할당이란 펼치다란 뜻으로 객체나 배열에서 사용하며, 값을 해제한 후, 개별 값을 변수에 새로 할당하는 과정을 말한다.
// 01. object (객체)
const student = {
name: 'Anna',
level: 1,
};
// 이전
{
const name = student.name;
const level = student.level;
console.log(name, level); // Anna 1
}
// 이후
{
const { name, level } = student; // { 이름으로 구분 }
console.log(name, level); // Anna 1
// 다른 이름으로 작성하고 싶을 때
const { name: myName, level: myLevel } = student;
console.log(myName, myLevel); // Anna 1
}
// 02. array (배열)
const animals = ['dog', 'rabbit'];
// 이전
{
const first = animals[0];
const second = animals[1];
console.log(first, second); // dog rabbit
}
// 이후
{
const [first, second] = animals; // [순서로 구분]
console.log(first, second); // dog rabbit
}
{
const obj1 = { key: 'key1' };
const obj2 = { key: 'key2' };
const array = [obj1, obj2];
// 01-1. array copy
const arrayCopy = [...array]; // [...배열명]
console.log(arrayCopy);
// [ {key: "key1"}, {key: "key2"} ]
// 01-2. array copy / new item add
const arrayCopy2 = [...array, { key: 'key3' }];
console.log(arrayCopy2);
// [ {key: "key1"}, {key: "key2"}, {key: "key3"} ]
// 01-3. array concatenation
const fruit1 = ['a', 'b'];
const fruit2 = ['c', 'd'];
const fruits = [...fruit1, ...fruit2];
console.log(fruits);
// ["a", "b", "c", "d"]
// 02-1. object copy
const obj3 = { ...obj1 } // {...객체명}
console.log(obj3);
// {key: "key"}
// 02-2. object merge
const dog1 = { dog1: '1'};
const dog2 = { dog2: '2'};
const dog = { ...dog1, ...dog2 };
console.log(dog);
// {dog1: "1", dog2: "2"}
// ※ 주의할 점 : object 의 key의 이름이 같은경우, 맨 뒤에오는 같은 이름이 앞의 같은 이름의 key의 값을 덥어 씌운다.
// const dog1 = { dog1: '1'};
// const dog2 = { dog1: '2'};
// const dog = { ...dog1, ...dog2 };
// console.log(dog); -> {dog1: "2"}
}