💡 เพื่อน ๆ มือใหม่หัดเขียน JavaScript หลาย ๆ คนอาจจะเคยเห็นเครื่องหมาย ?? และ || ในโปรแกรมแล้วไม่รู้ว่ามันคืออะไร และทำงานยังไง วันนี้เรามาไขข้อสงสัยกันเถอะ !! กับสรุปสั้น ๆ วิธีการใช้งาน Nullish Coalescing Operator
.
มันคืออะไร และใช้งานยังไง หากพร้อมแล้วไปอ่านกันเลยจ้าาาาา~~
.
🌟 Nullish Coalescing Operator
.
Nullish Coalescing (??)
เป็นตัวดำเนินการตรรกะที่จะ Return ค่าทางขวามือเมื่อค่าทางซ้ายเป็น Null หรือ Undefined
.
👨💻 Syntax
leftExpr ?? rightExpr
.
📑 ตัวอย่าง
const name1 = null ?? 'Oreo';
console.log(name1);
//output => Oreo
.
OR (||) - เป็นตัวดำเนินการตรรกะ จะ Return ค่าทางขวามือหากทางซ้ายมือเป็นเท็จ (0, ' ', NaN, null, undefined)
.
📑 ตัวอย่าง
let tu = null;
let text = tu || 'stupid!';
console.log(text); // output => stupid!
.
สามารถใช้ร่วมกับ OR (||) และ AND (&&) ได้แต่ต้องใช้วงเล็บ () เพื่อจัดลำดับความสำคัญของตัวดำเนินการด้วยนะ !!
.
📑 ตัวอย่าง OR (||)
let y = (false || true) ?? "foo"
console.log(y) // output => true
.
📑 ตัวอย่าง AND (&&)
let x = (false && true) ?? "foo"
console.log(x) //output => false
.
💥 Source : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator
.
borntoDev - 🦖 สร้างการเรียนรู้ที่ดีสำหรับสายไอทีในทุกวัน
「javascript null or undefined」的推薦目錄:
- 關於javascript null or undefined 在 BorntoDev Facebook 的最讚貼文
- 關於javascript null or undefined 在 How to check for an undefined or null variable in JavaScript? 的評價
- 關於javascript null or undefined 在 [教學]undefined與null的比較 - 米米的部落格 的評價
- 關於javascript null or undefined 在 What is the difference between null and undefined? 的評價
- 關於javascript null or undefined 在 null-vs-undefined - Awesome-JavaScript-Interviews - GitHub 的評價
- 關於javascript null or undefined 在 javascript - Falsy values vs null, undefined, or empty string 的評價
javascript null or undefined 在 [教學]undefined與null的比較 - 米米的部落格 的推薦與評價
而基本型別裡都有「原始值(primitive value)」,原始值是無法經過更改的的,例如布林值只有 truth 、 false ,不會再有其他的值,因此 null 、 undefined ... ... <看更多>
javascript null or undefined 在 What is the difference between null and undefined? 的推薦與評價
The convention in TypeScript is that undefined values have not been defined yet, whereas null values indicate intentional absence of a value ... ... <看更多>
javascript null or undefined 在 How to check for an undefined or null variable in JavaScript? 的推薦與評價
... <看更多>