Skip to content

Instantly share code, notes, and snippets.

@Weiyuan-Lane
Last active January 28, 2020 15:49
Show Gist options
  • Save Weiyuan-Lane/59332e04a1f2a5ef401f9fa4eb772709 to your computer and use it in GitHub Desktop.
Save Weiyuan-Lane/59332e04a1f2a5ef401f9fa4eb772709 to your computer and use it in GitHub Desktop.
Showcase nullish coalescing in JavaScript
const strVar = '';
const numVar = 0;
const boolVar = false;
const nullVar = null;
const undefinedVar = undefined;
// Example for OR operator ||
console.log("strVar || 'default string' = ");
console.log(`'${strVar || 'default string'}'`); // Output will be 'default string'
console.log("numVar || 100 = ");
console.log(numVar || 100); // Output will be 100
console.log("boolVar || true = ");
console.log(boolVar || true); // Output will be true
console.log("nullVar || 'another string' = ");
console.log(`'${nullVar || 'another string'}'`); // Output will be 'another string'
console.log("undefinedVar || 'undefined string' = ");
console.log(`'${undefinedVar || 'undefined string'}'`); // Output will be 'undefined string'
// Example for nullish operator ??
console.log("strVar ?? 'default string' = ");
console.log(`'${strVar ?? 'default string'}'`); // Output will be ''
console.log("numVar ?? 100 = ");
console.log(numVar ?? 100); // Output will be 0
console.log("boolVar ?? true = ");
console.log(boolVar ?? true); // Output will be false
console.log("nullVar ?? 'another string' = ");
console.log(`'${nullVar ?? 'another string'}'`); // Output will be 'another string'
console.log("undefinedVar ?? 'undefined string' = ");
console.log(`'${undefinedVar ?? 'undefined string'}'`); // Output will be 'undefined string'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment