[Javascript] Object_Optional chaining

Suyeon·2020년 9월 1일
0

Javascript

목록 보기
12/31

1️⃣ Nullish Coalescing '??'

  • It returns its right-hand side operand when its left-hand side operand is null or undefined and otherwise returns its left-hand side operand.
function showMessage(text) {
 alert(count ?? "unknown");
}

Optional chaining '?.'

  • The optional chaining ?. stops the evaluation and returns undefined if the part before ?. is undefined or null.

The Problem

let user = {};
alert(user.address.street); // Error!

// Error if the result of querySelector(...) is null
let html = document.querySelector('.my-element').innerHTML;

✔️ Alternative: && operator

let user = {}; // user has no address
alert( user && user.address && user.address.street ); // undefined (no error)

Usage

// Access "user.address.street"
let user = {}; 
alert( user?.address?.street ); // undefined (no error)
      
// .() Function
let user1 = {
  admin() {
    alert("I am admin");
  }
}

let user2 = {};

user1.admin?.(); // I am admin
user2.admin?.();

// .[] Key
let user1 = {
  firstName: "John"
};

let user2 = null; 

let key = "firstName";

alert( user1?.[key] ); // John
alert( user2?.[key] ); // undefined

// Delete
delete user?.name; // delete user.name if user exists
profile
Hello World.

0개의 댓글