[JS] ES2021에 추가된 replaceAll | 논리 할당 연산자 | 숫자 구분자

insuzy·2021년 8월 16일
post-thumbnail

1. replaceAll

String.prototype.replaceAll 메서드는 문자열 변경을 한꺼번에 가능하다.

  • 정규표현식(/regexp/g) 사용할 경우(Before)
const text = 'I love apple, apple is 👍🏻';
const textReplace = text.replace(/\apple/g, '🍎');
console.log(textReplace); //I love 🍎, 🍎 is 👍🏻
  • replaceAll()을 사용할 경우(After)
const text = 'I love apple, apple is 👍🏻';
const textReplace = text.replaceAll('apple', '🍎');
console.log(textReplace); //I love 🍎, 🍎 is 👍🏻

전에는, replace + 정규표현식으로 했다면, replaceAll은 한방에 해결 가능하다!
기존 문자열은 변경되지 않은채 유지되기 때문에 변수에 따로 담아줘야한다.

  • 브라우저 호환성

2. 논리 할당 연산자(Logical assignment operators)

자바스크립트에 논리 할당(AND, OR, NOT) + 할당 연산자(=, +=, -=)를 결합해 새로운 연산자가 도입되었다.

  • a ||= b 에 해당 `a || (a = b) false인 경우

  • a &&= b 에 해당 a && (a = b) true인 경우

  • a ??= b 에 해당 a ?? (a = b) null이나 undefined인 경우

  • Before

let a = 1;
lf(a){ //a가 true일 경우
  a = 2;
}
  • After
let a = 1;
a ||= 2; //a가 false 경우
a &&= 2; //a가 true일 경우
a ??= 2;  //a가 null이나 undefined가 아닐 경우

//+추가
let b = 3;
a &&= b; //a가 true라면 3 
console.log(a) //3

한줄만의 간단한 코드로 작업을 수행할 수 있다! (undefined 쓰는 것도 귀찮았는데.. 편하다 👍🏻)

  • 브라우저 호환성(AND, OR, NOT 동일)

3. 숫자 구분자(Numeric separator)

큰 숫자를 시각적으로 구분하여 숫자 리터럴을 더 읽기 쉽다.
가독성을 향상시키기 위해 _로 구분할 수 있다.

  • Before
let a = 1000000000; //10억
console.log(a) //1000000000
  • After
let a = 1_000_000_000; //10억
  • 브라우저 호환성(익스, 오페라 안드로이드 제외 지원)

참고
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND_assignment
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar
https://www.youtube.com/watch?v=yn32aDWUgZU&list=LL&index=2

profile
UI Developer. publisher

0개의 댓글