
책 읽다가 ES6 이후 어떤 것이 새로 생긴 지 궁금해서 찾아보기
let 변수 재선언 불가능, 변수 재할당 가능
console.log(foo); // undefined
var foo;
console.log(foo); // ReferenceError
let foo;
let 선언된 변수를 선언문 이전에 참조하면 참조 에러 발생
선언 단계와 초기화 단계가 분리되어 진행되기 때문
const 변수 재선언, 변수 재할당 불가능 (상수)
반드시 선언과 동시에 초기화
const foo = 1;
const bar // Syntax Error
const 키워드로 선언된 변수에 객체를 할당한 경우 값 변경 가능
재할당을 금지할 뿐 "불변" 의미 X
cosnt person = {
name: 'Lee'
}
person.name = 'Kim';
console.log(person) // {name: "Kim"}
기본적으로는 const
재할당이 필요할 경우 한정해 let
es6을 사용한다면 var 사용하지 않는 것이 좋음
기존 함수 정의 방식보다 간략하게 함수 정의
내부 동작도 기존의 함수보다 간략
// ES5
[1,2,3].map(function(v){
return v * 2;
}
// ES6
[1,2,3].map(v => v*2);
}
// 생성자 함수 호출할 수 없음
const Foo = () => {};
new Foo(); // TypeError
// 인스턴스를 생성할 수 없으므로 prototype 프로퍼티 없고 프로토타입 생성 x
const Foo = () => {};
Foo.hasOwnProperty('prototype') // false
//strict 에서는 에러나지만 그냥은 됨
function normal(a,a){ eturn a+a }
console.log(normal(1,2)); // 4
const arrow = (a, a) => a + a; // SyntaxError
화살표 함수는 간결하고 this 바인딩을 유지하며, 주로 단순한 작업에 사용
일반 함수는 생성자로 사용하거나 this를 명시적으로 변경해야 하는 경우에 사용
내장된 표현식을 허용하는 문자열 리터럴
여러 줄로 이뤄진 문자열과 문자 보간기능을 사용
const template = `<ul class="nav-items">
<li><a href="#home">Home</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
</ul>`;
const myFunc = (name, age) => {
return `안녕하세요 저는 ${name}이고 나이는 ${age}살 입니다`;
};
매개 변수 할당을 잊어버렸을 때 해당 값이 사용
const myFunc = (name, age = 21) => {
return `안녕하세요 저는 ${name}이고 나이는 ${age}살 입니다`;
};
console.log(myFunc('예준')); // 안녕하세요 저는 예준이고 나이는 21살 입나다
//ES5
var name = 'BAMBY';
var age = 21;
var person = {
name: name,
age: age,
}
//ES6
const name = 'BAMBY';
const age = 21;
const person = {
name,
age,
};
비동기 코드를 보다 구조화하고, 콜백 지옥을 피하며, 코드를 더 읽기 쉽게 만듦
const myPromise = new Promise((resolve, reject) => {
// 비동기 작업 수행
if (작업이 성공) {
resolve(결과 데이터); // 작업 성공
} else {
reject(에러 정보); // 작업 실패
}
});
// ES5
var numbers = [1, 2, 3];
var a = numbers[0];
var b = numbers[1];
var c = numbers[2];
console.log(a, b, c); // 1 2 3
var person = { name: 'John', age: 30 };
var name = person.name;
var age = person.age;
console.log(name, age); // John 30
// ES6
const numbers = [1, 2, 3];
const [a, b, c] = numbers;
console.log(a, b, c); // 1 2 3
const person = { name: 'John', age: 30 };
const { name, age } = person;
console.log(name, age); // John 30
객체를 생성하는 데 사용
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
sayHello() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
const john = new Person('John', 30);
john.sayHello();
// math.js
export const add = (a, b) => a + b;
// main.js
import { add } from './math.js';
const result = add(5, 3);
console.log(result);
const numbers = [1, 2, 3, 4, 5];
console.log(numbers.includes(3)); // true
console.log(numbers.includes(6)); // false
좌항의 피연산자를 밑으로, 우항의 피연산자를 지수로 거듭 제곱하여 숫자 값을 반환
2 ** 2; // 4
var num = 5;
num **=2; // 25
지수 연산자는 이항 연산자 중에서 우선 순위가 가장 높음
2 * 5 ** 2; // 50
Object.values(obj) 객체의 값들을 배열로 반환
Object.entries(obj) 객체의 [키, 값] 쌍을 배열로 반환
const obj = { a: 1, b: 2, c: 3 };
const values = Object.values(obj); // [1, 2, 3]
const entries = Object.entries(obj); // [['a', 1], ['b', 2], ['c', 3]]
String.prototype.padStart(maxLength, fillString)
pad는 좌우에 특정한 문자열로 채우는 기능
문자열의 길이가 maxLength보다 작을 경우 나머지를 특정한 문자열로 채워주는 기능
const str = '5';
const paddedStr = str.padStart(3, '0'); // '005'
const str = '5';
const paddedStr = str.padEnd(3, '0'); // '500'
객체에서도 Rest 프로퍼티와 Spread 프로퍼티를 사용할 수 있게 됨
ES6
// Rest
const [a, b, ...rest] = [1, 2, 3, 4, 5];
console.log(a); // 1
console.log(b); // 2
console.log(rest); // [3, 4, 5]
// Spread
const arr1 = [1, 2];
const arr2 = [...arr1, 3, 4];
console.log(arr2); // [1, 2, 3, 4]
ES9
// Rest
const { x, y, ...rest } = { x: 1, y: 2, a: 3, b: 4 };
console.log(x); // 1
console.log(y); // 2
console.log(rest); // { a: 3, b: 4 }
// Spread
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3, d: 4 };
console.log(obj2); // { a: 1, b: 2, c: 3, d: 4 }
Promise가 이행(resolve)되던 실패(reject)되던 상관없이 항상 실행되는 콜백을 등록
fetch('https://api.example.com/data')
.then(response => response.json())
.catch(error => console.error(error))
.finally(() => console.log('Fetch completed.'));
Array.prototype.flat()
중첩된 배열을 하나의 배열로 평탄화
const nestedArray = [1, [2, 3], [4, [5, 6]]];
const flatArray = nestedArray.flat(); // [1, 2, 3, 4, [5, 6]]
const flatArray2 = nestedArray.flat(Infinity); // [1, 2, 3, 4, 5, 6]
Array.prototype.flatMap()
map()과 flat()을 결합한 것으로, 배열의 각 요소에 대해 매핑 함수를 적용하고 그 결과를 평탄화한 배열을 반환
const numbers = [1, 2, 3];
const doubledAndFlat = numbers.flatMap(num => [num, num * 2]); // [1, 2, 2, 4, 3, 6]
String.prototype.trimStart() 문자열의 시작 부분에서 공백을 제거
String.prototype.trimEnd() 문자열의 끝 부분에서 공백을 제거
const text = ' Hello, World! ';
const trimmedStart = text.trimStart(); // 'Hello, World! '
const trimmedEnd = text.trimEnd(); // ' Hello, World!'
배열의 키-값 쌍을 가진 배열을 사용하여 새로운 객체 생성
const entries = [['a', 1], ['b', 2], ['c', 3]];
const obj = Object.fromEntries(entries); // { a: 1, b: 2, c: 3 }
Symbol의 설명을 반환
const sym = Symbol('My Symbol');
const description = sym.description; // 'My Symbol'
정수 데이터 타입 중 매우 큰 정수 값을 다루는 데 사용
이전 JavaScript에서는 일반적인 숫자 데이터 타입(Number)이 2^53-1 이상의 큰 정수 값을 처리하지 못했지만, BigInt를 사용하면 이러한 제한을 벗어날 수 있음
?. 연산자는 객체의 중첩된 속성 또는 메서드에 안전하게 접근할 수 있게 함
중첩된 속성 중 하나라도 null 또는 undefined이면 에러가 발생하지 않고 undefined를 반환
const user = {
name: 'John',
address: {
city: 'New York',
zipCode: '10001',
},
};
const zipCode = user.address?.zipCode; // '10001'
?? 연산자는 왼쪽 피연산자가 null 또는 undefined인 경우에만 오른쪽 피연산자를 반환
const value = null;
const defaultValue = 'Default Value';
const result = value ?? defaultValue; // 'Default Value'
Promise 들 중 하나가 실패하더라도 이행처리를 할 수 있는 방법
const promises = [Promise.resolve(1), Promise.reject('Error'), Promise.resolve(3)];
Promise.allSettled(promises).then(results => {
console.log(results);
});
// 결과: [{ status: 'fulfilled', value: 1 }, { status: 'rejected', reason: 'Error' }, { status: 'fulfilled', value: 3 }]
문자열에서 모든 발생을 대상 문자열로 교체
const text = 'Hello, world! Hello, universe!';
const newText = text.replaceAll('Hello', 'Hi');
console.log(newText); // 'Hi, world! Hi, universe!'
여러 개의 Promise 중 하나가 이행(resolve)될 때까지 기다림
모든 Promise가 거부(reject)될 때까지 기다리지 않고, 가장 먼저 이행되는 Promise의 결과를 반환
const promises = [Promise.reject('Error 1'), Promise.resolve('Success'), Promise.reject('Error 2')];
Promise.any(promises).then(result => {
console.log(result); // 'Success'
});
숫자 리터럴에서 밑줄(_)을 사용하여 숫자를 구분
긴 숫자를 더 가독성 있게 작성 가능
const billion = 1_000_000_000;
console.log(billion); // 1000000000
등록한 객체가 메모리에 있으면 해당 객체를 반환하고, 가비지 콜렉터가 객체를 삭제했다면 undefined를 반환
const foo = {
name: "foo"
};
// 강한 참조
const x = foo;
// 약한 참조
const xWeak = new WeakRef(x);
// 값을 사용하기
const xWeakDeref = xWeak.deref(); // { name: "foo" }
// before
obj.prop = obj.prop || foo(); // obj.prop이 잘못된 값일 경우 할당
obj.prop = obj.prop && foo(); // obj.prop이 올바른 값일 경우 할당
obj.prop = obj.prop ?? foo(); // obj.prop이 null이나 undefined일 경우 할당
// after
obj.prop ||= foo();
obj.prop &&= foo();
obj.prop ??= foo();
양수 및 음수 인덱스를 모두 사용하여 문자열을 인덱싱
const temp = [1, 2, 3];
temp[temp.length - 1]; // 3
temp.at(-1); // 3
구체적인 혹은 유용한 에러 메시지를 추가할때 사용
try {
connectToDatabase();
} catch (err) {
throw new Error("Connecting to database failed.", cause: { code: "NonCoprime", values: [p, q] },);
}
Array.prototype.findLast
배열을 역순으로 순회하며 제공된 테스트 함수를 만족하는 첫 번째 요소의 값을 반환
테스트 함수를 만족하는 요소가 없으면 undefined 반환
즉, 뒤에서부터 배열 돌려서 찾음
const array1 = [5, 12, 50, 130, 44];
const found = array1.findLast((element) => element > 45);
console.log(found); // 130
Array.prototype.findLastIndex
배열을 역순으로 순회하며 주어진 판별 함수를 만족하는 만족하는 배열의 첫번째 요소의 인덱스를 반환
만족하는 요소가 없으면 -1 반환
const array1 = [5, 12, 50, 130, 44];
const isLargeNumber = (element) => element > 45;
console.log(array1.findLastIndex(isLargeNumber)); // 3
Array.prototype.toReversed()
reverse()에 대응되는 복사 메서드
요소들을 반대로 뒤집은 새로운 배열을 반환
// reverse()
const array1 = ['one', 'two', 'three'];
const reversed = array1.reverse();
console.log(reversed); // ["three", "two", "one"]
// 원본 배열도 변경됨
console.log(array1); // ["three", "two", "one"]
// toReversed()
const items = [1, 2, 3];
const reversedItems = items.toReversed();
console.log(reversedItems); // [3, 2, 1]
// 원본 배열 유지
console.log(items); // [1, 2, 3]
Array.prototype.toSorted()
sort()에 대응되는 복사 메서드
이요소들을 오름차순으로 정렬한 새로운 배열을 반환
const months = ["Mar", "Jan", "Feb", "Dec"];
const sortedMonths = months.toSorted();
console.log(sortedMonths); // ['Dec', 'Feb', 'Jan', 'Mar']
Array.prototype.toSpliced()
splice()에 대응되는 복사 메서드
주어진 인덱스에서 일부 요소를 제거하거나 대체한 새로운 배열을 반환
const months = ["Jan", "Mar", "Apr", "May"];
// 인덱스 1에 요소를 삽입
const months2 = months.toSpliced(1, 0, "Feb");
console.log(months2); // ["Jan", "Feb", "Mar", "Apr", "May"]
// 인덱스 2에서 시작하여 두 개의 요소를 삭제
const months3 = months2.toSpliced(2, 2);
console.log(months3); // ["Jan", "Feb", "May"]
// 원본 배열 유지
console.log(months); // ["Jan", "Mar", "Apr", "May"]
지정된 인덱스의 요소가 지정된 값으로 대체된 새 배열을 반환
const arr = [1, 2, 3, 4, 5];
console.log(arr.with(2, 6)); // [1, 2, 6, 4, 5]
console.log(arr); // [1, 2, 3, 4, 5]
스크립트 앞에 #! 을 붙이는 것
#!/usr/bin/env node