Skip to main content

คุณสมบัติใหม่ ๆ ใน JavaScript ES2020 เลือกเฉพาะอันที่ชอบมาเล่าให้ฟัง

Kongvut Sangkla
Tags:

Intro

สวัสดีครับ บทความนี้จะพูดถึงคุณสมบัติใหม่ ๆ ใน JavaScript ECMAScript 2020 (ES2020) แต่ไม่ได้พูดทั้งหมด เพราะจะเลือกเฉพาะอันที่ผมชอบและเห็นว่ามีประโยชน์มากจริง ๆ 😆 มาเริ่มกันเลย

Nullish Coalescing (??) vs. Logical OR (||)

ดูตัวอย่างก่อนค่อยมาอ่านความหมาย

Nullish Coalescing (??) vs. Logical OR (||)
console.log(false ?? 'Truthy value') // false
console.log(undefined ?? 'Truthy value') // "Truthy value"
console.log(null ?? 'Truthy value') // "Truthy value"
console.log(NaN ?? 'Truthy value') // NaN
console.log(0 ?? 'Truthy value') // 0
console.log("" ?? 'Truthy value') // ""

console.log(false || 'Truthy value') // "Truthy value"
console.log(undefined || 'Truthy value') // "Truthy value"
console.log(null || 'Truthy value') // "Truthy value"
console.log(NaN || 'Truthy value') // "Truthy value"
console.log(0 || 'Truthy value') // "Truthy value"
console.log("" || 'Truthy value') // "Truthy value"

Nullish Coalescing (??) คือ การดำเนินการ Logical จะเห็นว่าให้ความสำคัญกับสิ่งที่หาค่าได้ แต่ไม่ได้สนว่าจะเป็นจริงหรือเท็จ (ยกเว้น undefined และ null) จากตัวอย่างข้างบนเมื่อเปรียบเทียบ Logical OR (||) มีความใกล้เคียงและแตกต่างกันพอสมควร เพราะ Logical OR จะสนใจเฉพาะกรณีที่เป็นจริงหรือเท็จเท่านั้น

Optional Chaining (?.)

ดูตัวอย่างก่อนค่อยมาอ่านความหมาย

Optional Chaining (?.)
const myPets = {
owner: 'Kongvut',
cat: {
name: 'Pitcha'
}
};

console.log(myPets.dog.name);
// Error: Cannot read property 'name' of undefined

console.log(myPets.dog?.name);
// undefined

คุณสมบัตินี้ใช้กับข้อมูลประเภท Object มีประโยชน์ในกรณีที่เราต้องการเช็คว่าไม่มีข้อมูล ซึ่งแต่ก่อนต้องมาเขียน if กันวุ่นวายมาก พอมี Optional Chaining ด้วยการเติม ? เข้าไปใน Chain ของ Object ก็ทำให้ทำงานง่ายขึ้นมาก

Module Namespace Exports (Re-Export)

ดูตัวอย่างก่อนค่อยมาอ่านความหมาย

export * as MyModule from "./my-module"
// มีค่าเท่ากับ
import * as MyModule from './my-module'
export { MyModule }

แต่ก่อนการทำ Re-Export ทั้ง Named Export กับ Default Export ทำได้หลายท่า หรือเขียนหลายบรรทัด แต่สำหรับ ES2020 นั้นได้มี Export * as ทำให้สะดวกขึ้นกว่าเดิมมาก

References

Loading...