← Back to JavaScript Course | Chapter 5: ES6+ Features | Lesson 5 of 12

JS नलिश कोलेसिंग

Nullish coalescing आपको एक backup value सिर्फ तभी देता है जब कुछ सच में गायब हो (null या undefined), जैसे अपनी चाबी खोने पर ही एक spare key इस्तेमाल करना। 0 जैसी असली values को रखा जाता है।
Syntax
javascript
const result = value ?? defaultValue;  // only for null or undefined

Basic Nullish Coalescing

?? operator अपनी दाईं तरफ की value सिर्फ तभी return करता है जब बाईं तरफ ठीक null या undefined हो, 0 या खाली string जैसी दूसरी falsy values को अनछुआ छोड़ते हुए। इसे खासतौर पर ||-based defaults की एक आम bug ठीक करने के लिए जोड़ा गया था।

उदाहरण: Basic Nullish Coalescing

javascript
const value = null ?? "default";
console.log(value);

Nullish बनाम OR

|| के उलट, जो किसी भी falsy value पर fallback होता है, ?? सिर्फ null/undefined पर fallback होता है। यह तब मायने रखता है जब 0, NaN, या '' असली values हों जिन्हें आप चुपचाप किसी default से बदलना नहीं चाहते।

उदाहरण: Nullish vs OR

javascript
console.log(0 || "fallback"); // "fallback" - || treats 0 as falsy
console.log(0 ?? "fallback"); // 0 - ?? only checks null/undefined

False और खाली Strings

false, 0, और '' falsy हैं पर nullish नहीं, इसलिए ?? इन्हें valid values मानता है और fallback नहीं होता। यह ठीक वही स्थिति है जहाँ || गड़बड़ करता था और इसे ठीक करने के लिए ?? लाया गया।

उदाहरण: False and Empty Strings

javascript
console.log(false ?? "x"); // false
console.log(0 ?? "x");     // 0
console.log("" ?? "x");    // ""

Objects के साथ

जब बाईं तरफ किसी object से पढ़ी गई property हो, तो ?? वैसे ही काम करता है, जो इसे optional config fields पढ़ने के लिए एक स्वाभाविक विकल्प बनाता है, बिना जानबूझकर रखी गई falsy values को गलती से override किए।

उदाहरण: With Objects

javascript
const config = { timeout: 0 };
console.log(config.timeout ?? 5000); // 0, a real intentional value

Optional Chaining के साथ

?? और ?. (optional chaining) को अक्सर साथ मिलाया जाता है: किसी शायद-गायब object में safely chain करें, फिर सिर्फ तभी एक default दें जब आखिरी result null या undefined हो।

उदाहरण: With Optional Chaining

javascript
const user = { address: null };
console.log(user?.address?.city ?? "Unknown");
Live Example
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. defaults के लिए || इस्तेमाल करना, इसलिए 0, "" और false replace हो जाते हैं; ?? सिर्फ null और undefined replace करता है।
  2. बिना parentheses के ?? को || या && के साथ मिलाना, जो एक SyntaxError है।
  3. यह उम्मीद करना कि ?? undefined और empty strings को same मानेगा, जबकि "" ?? "x" "" return करता है।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.