RaghavBang
Published in

RaghavBang

Nullish Coalescing (??): Modern JS

OR (||) Operator

  • false
  • undefined
  • null
  • “”
  • Nan
  • 0
const val1 = 20;
const val2 = 23;

const result = val1|| val2;

console.log(result); // 20
const val1 = 0;
const val2 = 23;

const result = val1 || val2

console.log(result); // 23

Why we need Nullish Coalescing in JS if we already have OR operator?

  • If x is null or undefined, result will be y
  • If x is not null or undefined, result will be x
let result = undefined ?? "Hello";
console.log(result); // Hello

result = null ?? true;
console.log(result); // true

result = false ?? true;
console.log(result); // false

result = 55 ?? true;
console.log(result); // 55
result = (x !== null && x!== undefined) ? x: y;

Chaining with the AND or OR operator

const result = (null || undefined) ?? 'Hello'; 
console.log(result); // 'Hello'
const result = null || undefined ?? 'Hello'; // syntax error

Logical Nullish assignment (??=)

x ??= y
const result= { marks: null ,name:"Hello"};
result.marks??= 100;
console.log(result.marks); //100
result.name ??= "World";
console.log(result.name);// Hello
result.subject ??= "JavaScript"
console.log(result.subject);// JavaScript

--

--

Technical blogs, Mini project idea, Coding and updates about new technology

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store