2021.02.23
ECMAScript 2021(ES12) 버전은 2021년6월에 출시 될 예정이다.
String.prototype.replaceAll("첫번째인자", "두번째인자") : 문자열에서 모든 첫번째인자 값을 두번째인자 값으로 바꾼다.
기존 Javascript 문자열 메서드에는 replace() 메서드가 있다.
replace()메서드는 해당하는 첫 번째 항목만 변환한다.
const str = "black bean, black dress";
const newStr = str.replace("black", "White");
console.log(newStr); //"White bean, black dress"
replace()메서드로 전체교체를 수행 하려면 정규 표현식을 사용해야 했다.
const str = "black bean, black dress";
const newStr = str.replace(/black/g, "White");
console.log(newStr); //"White bean, White dress"
정규표현식
g : 전체 모든 문자열 변경 (global)
i : 영문 대소문자를 무시, 모두 일치하는 패턴 검색 (ignore)
const newStr = str.replace(/black/gi, "White"); -> 대소문자 관계 없이 전체를 검사해서 변경한다.
하지만, 이제 replaceAll()메서드를 사용해서 첫번째인자가 정규식이 아닌 문자열인 경우에도 전체 변환이 가능하다.
const str = "black bean, black dress";
const newStr = str.replaceAll("black", "White");
console.log(newStr); //"White bean, White dress"
null 병합 연산자(nullish coalescing operator)는 ??
를 사용하여 nullish한 값(null
혹은 undefined
)을 판별하는 연산을 하는 연산자이다.
- a ?? b
- a가
null
도 아니고undefined
도 아니면a
- 그 외의 경우는
b
즉, 왼쪽 피연산자가 nullish
한 값일 경우 오른쪽 피연산자를, 그렇지 않은 경우 왼쪽 피연자를 반환한다.
x = (a !== null && a !== undefined) ? a : b; //a ?? b 동일한 결과를 반환
??
와 ||
의 차이
||
는 첫 번째 truthy 값을 반환합니다.??
는 첫 번째 정의된(define) 값을 반환합니다.
||
는 Falsy
한 값 (숫자 0,빈 문자열 '', NaN, null, undefined, 등등 ) 에 적용됩니다.
null
과 undefined
, 숫자 0
을 구분 지어 다뤄야 할 경우 이 둘의 차이점은 매우 중요한 역할을 합니다.
const totalPrice = (price, taxes) => {
let taxes = taxes || 0.05
const total = price * (1 + taxes);
console.log(total);
}
totalPrice(100,0.05); //105
totalPrice(100,0);//105
totalPrice(100,undefined);//105
//0일때는 taxes가 적용 되지 않고 nullish한 값일 때만 기본 taxes가 적용
const totalPrice = (price, taxes) => {
let taxes = taxes ?? 0.05
const total = price * (1 + taxes);
console.log(total);
}
totalPrice(100,0.05); //105
totalPrice(100,0);//100
totalPrice(100,undefined);//105
taxes || 0.05
은 taxes에 0을 할당했지만 0은 falsy한 값으로 null
과 undefined
와 같은 취급을 한다. 따라서 0.05 taxes가 적용된 값이 반환된다.
하지만 taxes ?? 0.05
의 경우 taxes의 값이 정확하게 null
이나 undefined
일 경우에만 0.05값이 적용된다.
옵셔널 체이닝(Optional chaining) ?.
은 .
체이닝과 동일한 기능을 하는데 다른 점은 참조 값이 nullish한 경우에 에러를 뿜지 않고 undefiend를 반환한다.
-> ?.
을 사용하면 프로퍼티가 없는 중첩 객체를 에러 없이 안전하게 접근할 수 있다.
?.
은 ?.
앞의 대상이 undefined
나 null
이면 평가를 멈추고 undefined
를 반환한다.
?.
은 연산자가 아닙니다. 함수나 대괄호와 함께 동작하는 특별한 문법 구조체입니다. 따서 ?.()
와 ?.[]
도 사용이 가능합니다.
class Person {
constructor(name, address) {
this.name = name
this.address = address
}
print() {
console.log(this)
}
}
const nike = new Person("nike", {city: "where"})
console.log(nike.address.street)//street가 정의되어 있지 않기 때문에 에러가 발생한다.
//에러가 발생하지 않게 하려면 아래 처럼 표현해야 한다.
console.log(nike && nike.address && nike.address.street)// undefined, 에러는 발생하지 않음
//옵셔널 체이닝인 ?.을 사용하면 더 쉽게 작성할 수 있다.
console.log(nike?.address?.street)// undefined, 위 결과와 동일함
nike.print()//Person {name: "nike", address: {city: "where"} }
nike.printName()//printName라는 메서드가 없기 때문에 에러가 발생한다.
nike.printName?.()//printName라는 메서드가 없지만 에러는 발생하지 않고 그냥 평가가 멈춘다. (아무것도 실행되지 않음)
console.log(nike["hobby"])//hobby는 정의되지 않았기 때문에 에러 발생
console.log(nike?.["hobby"])//undefined, 에러가 발생하지 않는다.
?.
은 delete
와 조합해 사용할 수도 있습니다.
delete user?.name; // user가 존재하면 user.name을 삭제합니다.