var: 함수 스코프를 가짐, 재선언 가능
let, const: 블록 스코프를 가짐
문자열을 백틱으로 표현하고 ${}로 변수를 포함할 수 있는 것
참고: 따옴표로 문자를 표현하면 '문자열 리터럴', 그냥 숫자로 쓰면 숫자 리터럴이라고 함.
속성명과 변수명이 동일한 경우 한 번만 써도 됨.
{ name: name, age: age } // ES5
{ name, age } // ES6
리터럴: 소스 코드 내에서 고정된 값을 대표하는 용어
this 바인딩 방식이 달라짐.
화살표 함수는 바깥 스코프를 this로 바인딩 함.
(일반 함수는 최상위 객체를 this로 바인딩)
배열이나 객체의 속성을 변수에 담을 수 있게 분해하는 것
// 배열 구조 분해
const colors = ['red', 'green', 'blue'];
const [firstColor, secondColor] = colors;
// 객체 구조 분해
const person = {
name: "John Doe",
age: 30,
job: "Developer"
};
const { name, age, job } = person;
프로토타입 기반으로 동적하지만, 이걸 마치 객체 지향 클래스처럼 사용할 수 있음.
자바스크립트는 클래스 기반이 아니라 프로토타입 기반으로 동작함.
콜백 대신 프로미스 객체 기반으로 사용
const promise = new Promise((resolve, reject) => {
if (condition) {
resolve('성공');
} else {
reject('실패');
}
}
promise
.then((message) => {
...
}
.catch((error) => {
...
}
.finally(() => {
...
}
promise가 resolve를 실행하면 then 구문이 실행
reject를 실행하면 catch 구문이 실행
resolve, reject의 매개변수를 각각 then과 catch가 받는다.
promise.all([])로 여러 프로미스를 동시에 실행할 수 있음.
promise.resolve도 있음. 즉시 resolve함.
promise.reject도 있음. 즉시 reject함.
promise.all는 결과가 배열로 넘어가는데 하나라도 실패하면 catch로 넘어가고,
뭐가 문제인지 모름. 그래서 promise.allSettled를 사용해야 함.
const promise1 = Promise.resolve('성공');
const promise2 = Promise.reject('실패');
const promise3 = Promise.resolve('성공');
Promise.allSettled([promise1, promise2, promise3])
.then((result) => {
console.log(result);
})
.catch((error) => {
console.log(error);
});
async function으로 promise에 await를 붙여서 처리
성공하면 try, 실패하면 catch 구문 실행
async 함수의 반환값은 항상 Promise로 감싸진다.
즉, 실행 후 then이나 다른 async 함수에서 await로 활용할 수 있다.
Map: 객체와 유사
Set: 배열과 유사, 중복을 허용하지 않는 자료
// Map
const m = new Map();
m.set('key', 'value');
m.set(3, 'c');
const d = {};
m.set(d, 'e');
m.get(d);
m.size;
m.has(1);
m.delete(d);
m.claer();
// Set
const s = new Set();
s.add(false);
s.add(1);
s.has(1);
s.delete(2);
s.clear();
Map은 속성 간의 순서를 보장하고 반복문 사용 가능
속성명으로 문자열이 아닌 값도 사용 가능
size를 통해 속성의 수를 쉽게 알 수 있음.
Set은 중복을 허용하지 않음.
const b = a || 3; // (비교)이건 앞이 fasle면 뒤로 넘어감
const d = c ?? 3; // 이건 앞이 null, undefiend면 뒤로 넘어감
속성명이 null이나 undefined를 조회하는 경우 발생하는 에러 방지
const person = {
name: "John Doe",
address: {
street: "123 Main St",
city: "Anytown"
}
};
// 옵셔널 체이닝을 사용하지 않는 경우
console.log(person.address.city); // 출력: Anytown
console.log(person.address.zipCode); // TypeError: Cannot read property 'zipCode' of undefined
// 옵셔널 체이닝을 사용하는 경우
console.log(person.address?.city); // 출력: Anytown
console.log(person.address?.zipCode); // 출력: undefined
해당 프로퍼티가 있으면 출력하고 없으면 에러가 아닌 undefined를 출력