JavaScript 치트시트
7. ES6+ 기능
7.1 디스트럭처링
객체 디스트럭처링
const person = { name: 'Alice', age: 25, city: 'Seoul' };
const { name, age } = person;
console.log(name, age); // Alice 25
배열 디스트럭처링
const numbers = [1, 2, 3];
const [first, second] = numbers;
console.log(first, second); // 1 2
7.2 스프레드 연산자 (...)
const arr1 = [1, 2];
const arr2 = [3, 4];
const combined = [...arr1, ...arr2];
console.log(combined); // [1,2,3,4]
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 };
console.log(obj2); // {a:1, b:2, c:3}
7.3 모듈 (export, import)
// module.js
export const greeting = () => console.log('Hello Module');
// main.js
import { greeting } from './module.js';
greeting();
7.4 클래스 (class, extends, super)
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name}가 소리를 냅니다.`);
}
}
class Dog extends Animal {
constructor(name) {
super(name);
}
speak() {
console.log(`${this.name}가 짖습니다.`);
}
}
const dog = new Dog('Buddy');
dog.speak();
7.5 심볼(Symbol)
const id = Symbol('id');
const obj = {};
obj[id] = 123;
console.log(obj[id]); // 123
7.6 Set과 Map
const mySet = new Set([1, 2, 3, 3]);
console.log(mySet); // Set {1,2,3}
const myMap = new Map();
myMap.set('name', 'Alice');
console.log(myMap.get('name')); // Alice
7.7 Promise, async/await
const promise = new Promise(resolve => setTimeout(() => resolve('완료'), 1000));
promise.then(console.log);
async function fetchData() {
const res = await fetch('https://jsonplaceholder.typicode.com/posts/1');
const data = await res.json();
console.log(data);
}
fetchData();
7.8 Optional Chaining (?.)
const user = { profile: { name: 'Alice' } };
console.log(user.profile?.name); // Alice
console.log(user.address?.city); // undefined
7.9 Nullish Coalescing (??)
let value = null;
console.log(value ?? '기본값'); // '기본값'
7.10 BigInt
const bigNumber = 123456789012345678901234567890n;
console.log(bigNumber);