[JS]-ES6

Updated:

ES6 문법

=> 이 게시글은 JS문법에 더해 2015년부터 추가된 ES2015+ 문법들을 정리하기 위한 게시글이다

Map & Set


-> ES6부터 Map과 Set이라고 하는 새로운 자료구조가 추가되었다. Map은 객체와 유사하고, Set은 배열과 유사하다

map


const m = new Map();

m.set('name', 'saemyung');
m.set('age', 23);

console.log(m.get('age'));		// 23
console.log(m.size);		// 2

for(const [key,value] of m){
    console.log(key, value);		// name saemyung age 23
}

console.log(m.has('name'));		// true
m.delete('name');
m.clear();

-> set(키, 값) 의 형태로 Map에 추가한다. 여기서 객체와 다른점은 키를 문자열, 심볼로만 해야하는 객체와 달리 Map은 객체, 숫자 등등도 키로 사용할 수 있다
-> 반복문을 쉽게 쓸 수 있도록 지원한다. delete 키워드를 통해 해당 속성을 지울 수도 있고, clear 키워드를 통해 모든 속성을 지울 수 있다
=> key와 value를 가지는 자료구조는 Map을 사용하는걸 추천!!

set


-> set은 배열과 달리 중복을 허용하지 않는데, 중복될 경우 첫번째 요소만 남긴다

const s = new Set();
s.add('hi');
s.add(3);
s.add(true);
s.add(3);

console.log(s.size);		// 3
console.log(s.has(3));		// true

for(const e of s){
    console.log(e);		// hi 3 true
}

s.forEach((e)=>{
    console.log(e);		// hi 3 true
})

s.delete(3);
s.clear();

-> 중복을 허용하지 않는다는 점을 제외하면 배열과 비슷하다. 또한 사용법은 Map과 유사하다

const arr = [1,1,1,2,2,2,3,3,3];
const s = new Set(arr);
const s_toArr = Array.from(s);

console.log(s);		// Set(3) { 1, 2, 3 }
console.log(s_toArr);		// [ 1, 2, 3 ]

-> 위의 방식으로 배열의 중복을 제거하는 것도 손쉽게 가능하다
-> 중복을 제거한 Set을 다시 배열로 돌리려면 Array.from() 을 이용하면 된다

널병합 & 옵셔널 체이닝

널병합 연산자


-> 널병합 연산자는 주로 ‘   ‘를 대체하여 사용되고, 기존 ‘   ‘이 구분하던 0, ‘’, false, NaN, null, undefined 에서 null 과 undefined만 구분한다
const n1 = 0;
const n2 = n1 ?? 3;

const n3 = null;
const n4 = n3 ?? 3;

const n5 = undefined;
const n6 = n5 ?? 3;

console.log(n2);		// 0
console.log(n4);		// 3
console.log(n6);		// 3

-> 널병합 연산자는 0일 경우는 뒤로 넘어가지 않고 null 과 undefined일 경우에만 뒤로 넘어간다

옵셔널 체이닝


-> 옵셔녈 체이닝 연산자는 ‘TypeError: Cannot read properties of null/undefined’ 의 오류발생빈도를 낮추기 위해 자주 사용된다

const obj = null;
try {
    obj.a;
} catch(e){
    console.error(e);       // TypeError: Cannot read properties of null (reading 'a')
}

try {
    obj.f();
} catch(e){
    console.error(e);       // TypeError: Cannot read properties of null (reading 'f')
}

try {
    obj[0];
} catch(e){
    console.error(e);       // TypeError: Cannot read properties of null (reading '0')
}

obj?.a;
obj?.f();
obj?.[0];

-> obj가 null일 경우 오류를 잡기 위해 try-catch문을 사용해야 하는데, ‘ ?. ‘ 연산자를 사용하면 TypeError 오류를 없앨수 있다
-> 여기서 ‘obj?.a’, ‘obj?.f()’, ‘obj?.[0]’ 값은 모두 undefined가 되므로, 위의 널병합 연산자와 함께 사용할 수도 있다

Tags: ,

Categories:

Updated:

Leave a comment