티스토리 뷰

1. ?? 연산자(Nullish coalescing operator)

  • 기존의 &&나 || 연산자처럼, a ?? b 와 같은 형태로 이용 가능
  • a ?? b에서 a(좌변의 피연산자)가 null이거나 undefined일 때만 b(우변의 피연산자) 반환 

    • a 과목의 점수 scoreA, b 과목의 점수 scoreB가 있다. 분명 b 과목의 점수는 0점인데, 위의 console.log에는 0점이 아닌, mystery라고 출력이 된다.
    • 이는 ||는 null, undefined와 더불어 0과 같은 falsy한 값도 거르기 때문
    • 이런 경우, ??를 이용해 해결할 수 있음기존 || 연산자에 대신 이용할 수 있는 예시

 

 

2. Optional Chaining

// 과목에 score가 없을 수도 있다고 가정
const subjects = {
    math: {
        score: 100,
    }, 
    science: {
    },
};

console.log(`수학 점수: ${subjects.math.score}`);

// science의 score를 확인하기 위한 기존 코드
console.log(subjects.science && subjects.science.score);

// optional chaining을 이용한 코드
console.log(subjects?.science?.score);
  • 만약 subjects 내의 각 과목들에 score가 없을 수도 있을 때, science의 점수를 출력하기 위해서는 subjects 내에 science가 존재하고, 이 science에 score가 존재하는지 확인해야 하기에 위와 같이 코드를 작성해야 했음
  • 하지만 optional chaining을 이용하면 위와 같이 간단하게 작성할 수 있음. 
    • obj.key에서 key의 존재가 명확하지 않을 경우, obj 뒤에 '?'를 붙임

 

 

3. padStart

str.padStart(targetLength [, padString])
  • 문자열의 시작 부분에 주어진 문자열을 추가하여 원하는 길이에 도달하게 함
  • targetLength는 결과 문자열의 총 길이를 지정
  • padString 추가할 문자열을 지정하며, 생략하면 공백이 사용됩니다.
  • 문자열의 길이가 이미 targetLength 이상이면, 원본 문자열을 그대로 반환
"5".padStart(3, "0"); // "005"

 

 

4. padEnd

str.padEnd(targetLength [, padString])
  • 문자열의 끝에 주어진 문자열을 추가하여 원하는 길이에 도달하게 함
  • 사용법과 기능은 padStart와 유사
  • padStart와 달리, padEnd는 문자열의 끝에 문자를 추가
"5".padEnd(3, "0"); // "500"

 

 

5. trim

  • 문자열의 양 끝에서 공백을 제거
  • 공백은 공백 문자, 탭, 줄바꿈 문자 등을 포함
"  hello world  ".trim(); // "hello world"

 

 

6. trimStart, trimEnd

  • 각각 문자열 앞부분, 뒷부분의 공백을 제거
"  hello world  ".trimStart(); // "hello world  "
"  hello world  ".trimEnd(); // "  hello world"

 

 


1. Nullish coalescing operator: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing

 

Nullish coalescing operator (??) - JavaScript | MDN

The nullish coalescing (??) operator is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.

developer.mozilla.org

 

2. Optional chaning: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

 

Optional chaining (?.) - JavaScript | MDN

The optional chaining (?.) operator accesses an object's property or calls a function. If the object accessed or function called using this operator is undefined or null, the expression short circuits and evaluates to undefined instead of throwing an error

developer.mozilla.org

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함