📕ES6 주요 문법 정리
⭐ 새로 추가된 string 메서드
- startsWith( ) : string의 시작이 일치하는 문자열이 있는지 판단한다.
- endWith( ) : string의 끝이 일치하는 문자열이 있는지 판단한다.
- includes( ) : 해당 문자열이 포함되어 있는지 판단한다.
const weather = "The weather is sunny today.";
weather.startsWith("The"); // true
weather.endsWith("today"); // true
weather.includes("is"); // true
weather.includes("rain"); // false
⭐ shorthand property names
obj의 key와 value의 이름이 동일하다면, 축약해서 이름 하나로 작성할 수 있다.
const human = {
name: 'mini',
age: '20'
};
const name = 'mini';
const age = '20';
const human2 = {
name: name,
age: age
};
const human3 = {
name,
age
}; // -> shorthand property names
⭐ Destructuring
1. obj destructuring
각 객체의 프로퍼티를 각 변수에 할당할때, { } 를 사용하여 한 줄로 정의할 수 있다.
이때 할당 기준은 key이름이다.
const dog = {
name: 'mingki',
age: '7'
};
// 기존
const name = dog.name;
const age = dog.age;
// es6
const {name, age} = dog;
만약에 변수이름을 key값의 이름말고 다른이름으로 정의하고싶을때는?
const {name:myDogName, age:myDogAge} = dog;
이렇게 : 을 이용하여, 'obj의 key이름' : '내가 정의 하고싶은 변수이름' 으로 작성해주된다.
2. array destructuring
배열도 마찬가지로 적용이 가능하다.
const fruites = ['🍓', '🍍', '🍑'];
// 기존
const strawberry = fruites[0];
const pineapple = fruites[1];
const peach = fruites[2];
// es6
const [strawberry,pineapple,peach] = fruites;
이렇게 [ ] 안에 변수이름을 배열안에 있는 값 순서대로 정의해주면 된다.
⭐ Spread 연산
[ ...array ] 로 입력하며, array안의 있는 값을 하나씩 분산시켜 낱개로 가져와 복사할 수 있다.
✍ 주의할 점
spread 연산자는 복사할때 값을 하나씩 복사하는 것이 아니라 위 obj가 가리키고 있는 주소의 참조값만 복사하여 나타내는 것 이기 때문에, 만약 원래의 obj의 값을 변경하게되면, 전부 영향이 갈 수 있기 때문에 이 점을 주의해서 사용해야 한다.
const human = {age:'20'};
const human2 = {age:'21'};
const array = [human, human2];
// array, obj 모두 적용 가능하다.
const arrayCopy = [...array];
const objCopy = {...human}
// 복사하는 동시에 새로운값을 추가하고 싶다면?
const arrayCopy = [...array,{ age: '22' }];
//또한, 하나 이상을 배열을 합칠 수 있다.
const animals = ['🐴','🐔']
const animals2 = ['🐶','🐱']
const animals3 = [...animals,...animals2]
console.log(animals3) // ['🐴','🐔',🐶','🐱']
// obj도 동일하게 가능하다.
const animal = {dog:'🐶'};
const animal2 = {cat:'🐱'};
const animals3 = {...animals,...animals2};
console.log(animals3) // {dog:'🐶',cat:'🐱'};
// *주의할 점*
// 만약 key값이 동일한 obj를 병합하게 된다면, 제일 뒤에있는 obj값만 올 수 있다.
const animal = {dog:'🐶'};
const animal2 = {dog:'🐕🦺'};
const animals3 = {...animals,...animals2};
console.log(animals3) // {'🐕'};
⭐ Default parameters
function sayHello(message = 'Hello'){
console.log(message)
}
sayHello('Hi'); // Hi
sayHello(); // Hello
인자에 default값을 지정해주면, 위처럼 함수를 불러올때 인자에 새로운값을 지정해주면 새로운값인 Hi가 출력되고,
인자가 전달되지 않는다면 default값으로 저장한 Hello가 출력된다.
+ ES11 문법 두가지
⭐ Optional Chaining
const human1 = {
name: 'Doni',
personalInfo: {
age: 20,
favoritFood:{
name: 'kimchi',
},
},
};
const human2 = {
name:'euni',
};
// 만약 위 obj에서 favoritFood 의 name을 출력하고 싶을때,
function favoritFood(hunam) {
console.log(human.personalInfo && human.personalInfo.favoritFood && human.personalInfo.favoritFood.name);
}
favoritFood(human1); //kimchi
favoritFood(human2); //undifined
// && 연산자로 출력하는 방식으로 구현해 볼 수 있지만, 코드가 계속 중복이되기 때문에
// 이럴때 optional chaning을 이용해 축약할 수 있다.
function favoritFood(hunam) {
console.log(human.personalInfo?.favoritFood?.name);
}
favoritFood(human1); //kimchi
favoritFood(human2); //undifined
⭐ Nullish Coalescing Operator
false는 false, ' ', 0, null, undefined 모두 false로 간주되어지기 때문에,
만약, ' ' , 0 을 포함한 값을 제공하고 싶다면, && 또는 || 연산자는 사용할때 예기치 못한 상황이 발생할 수 있다.
const name = '';
const userName = name || 'Guest';
console.log(userName); // Guest
//name에 공백까지 name으로 받고싶을때, || 연산자를 쓰면 Guest로 할당되지만,
//nullish coalescing 연산자를 사용한다면,
const name = '';
const userName = name ?? 'Guest'; // name에 값이 있으면 name으로 반환
console.log(userName); // 공백으로 출력된다.
// 두번째 예시
const num = 0;
const message = num ?? 'undefined';
console.log(message); // 0