Null / Nullish Coalescing (Double Question Mark ??) operator in JavaScript and React.
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 and otherwise returns its left-hand side operand. Contrary to the logical OR (||) operator, the left operand is returned if it is a falsy value that is not null or undefined. In other words, if you use || to provide some default value to another variable foo, you may encounter unexpected behaviors if you consider some falsy values as usable (eg. '' or 0). const foo = null ?? 'bar'; console.log(foo); // output: "bar" const baz = 0 ?? 42; console.log(baz); // output: 0
Difference Between logical OR (||) and nullish coalescing (??) operators:
The common pattern is to use the logical OR operator (||): let foo; // foo is never assigned any value so it is still undefined let someDummyText = foo || 'Hello!'; But, due to || being a boolean logical operator, the left-hand-side operand was coerced to a boolean for the evaluation and any falsy value (0, '', NaN, null, undefined) was not returned. This behavior may cause unexpected consequences if you consider 0, '', or NaN as valid values. let count = 0; let text = ""; let qty = count || 42; let message = text || "hi!"; console.log(qty); // 42 and not 0 console.log(message); // "hi!" and not "" The nullish coalescing operator avoids this pitfall by only returning the second operand when the first one evaluates to either null or undefined (but no other falsy values): let myText = ''; // An empty string (which is also a falsy value) let notFalsyText = myText || 'Hello world'; console.log(notFalsyText); // Hello world let preservingFalsy = myText ?? 'Hi neighborhood'; console.log(preservingFalsy); // '' (as myText is neither undefined nor null)
Chaining and Nullish Coalescing Operators
React's create-react-app version 3.3.0 (released 5.12.2019) tool-chain supports the null-coalescing. // Optional chaining a?.(); // undefined if a is null/undefined b?.c; // undefined if b is null/undefined // Nullish coalescing undefined ?? 'some other default'; // result: 'some other default' null ?? 'some other default'; // result: 'some other default' '' ?? 'some other default'; // result: '' 0 ?? 300; // result: 0 false ?? true; // result: false Further reading: - The Easiest Way to Install Windows 10 with ISO File From USB Drive - What is CSS4? Does CSS 4 really exist? - How to earn money by guest posting? Here are guest blog websites paying writers. Read the full article










