From fd77bbebb77362ddecfef7aba3bf6abf7bdd81f2 Mon Sep 17 00:00:00 2001 From: Khadija-Batool Date: Sun, 2 Jul 2023 23:51:01 +0500 Subject: [PATCH] [guide] add nullish-coalescing-operator definition --- README.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/README.md b/README.md index 5732b91c..026c7ebe 100644 --- a/README.md +++ b/README.md @@ -2198,6 +2198,33 @@ Other Style Guides const bar = a + (b / c) * d; ``` + + - [15.9](#nullish-coalescing-operator) 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`. Otherwise, it returns the left-hand side operand. + + > Why? It provides precision by distinguishing null/undefined from other falsy values, enhancing code clarity and predictability. + + ```javascript + // bad + const value = 0 ?? 'default'; + // returns 0, not 'default' + + // bad + const value = '' ?? 'default'; + // returns '', not 'default' + + // good + const value = null ?? 'default'; + // returns 'default' + + // good + const user = { + name: 'John', + age: null + }; + const age = user.age ?? 18; + // returns 18 + ``` + **[⬆ back to top](#table-of-contents)** ## Blocks