Skip to content

JS Operator

Sunday, 25 May 2025
       

Optional Chaining ?. และ Nullish Coalescing ?? เป็นคุณสมบัติของ JavaScript ที่จัดการกับค่า null หรือ undefined ได้อย่างมีประสิทธิภาพ และได้สรุปเพื่อให้เข้าใจง่าย

user object

js
const user = {
  profile: {
    email: 'email@example.com'
  }
}

Optional Chaining (?.)

จาก user object หาก property ใดๆก็ตามใน chain ที่อยู่ก่อน ?. เป็นค่า null หรือ undefined จะได้ค่าเป็น undefined

js
const email = user?.profile?.email
// ผลลัพธ์: "email@example.com"

const address = user?.address?.street
// หาก user.address เป็น null หรือ undefined
// ผลลัพธ์: undefined โดยไม่มี error

Nullish Coalescing (??)

จาก user object ใช้กำหนดค่าค่าเริ่มต้น ให้กับตัวแปร เฉพาะในกรณีที่ค่าทางด้านซ้ายของ ?? เป็นค่า null หรือ undefined เท่านั้น

js
const name = user.name ?? 'Guest'
// หาก user.name เป็น null หรือ undefined
// ดังนั้น name จะเป็น "Guest"

const age = user.age ?? 0
// หาก user.age เป็น null หรือ undefined
// ดังนั้น age จะเป็น 0

const emptyString = '' ?? 'Default'
// "" ไม่ใช่ null หรือ undefined
// ดังนั้น emptyString จะเป็น ""

const zeroValue = 0 ?? 10
// ค่า zeroValue มีค่า 0 ไม่ใช่ null หรือ undefined
// ดังนั้น zeroValue จะเป็น 0

Built with: VitePress.