Skip to content

Instantly share code, notes, and snippets.

@okovalov
Created December 18, 2019 17:28
Show Gist options
  • Save okovalov/3144191cf837db2d894be270a83008b6 to your computer and use it in GitHub Desktop.
Save okovalov/3144191cf837db2d894be270a83008b6 to your computer and use it in GitHub Desktop.
const data = {
foo: 'bar',
falsyValue: false
}
// this one is good
const containerOne = data.foo || 'fallback'
console.log('container one =', containerOne); // container one = bar
// non existed - still "good"
const containerTwo = data.unexisted || 'fallback'
console.log('container two =', containerTwo); // container two = fallback
// this one is WRONG! because falsyValue value is equal to false, so it would lead to a bug
const containerThree = data.falsyValue || 'fallback'
console.log('container three =', containerThree); // container three = fallback, however it should be 'false'
// this is a correct way - using nullish coalescing
// NOTE - that is NOT part of js implementation yet
// const containerFour = data.falsyValue ?? 'fallback'
// console.log('container four =', containerFour); // container three = fallback
// kind of ugly but safe way for a temporarly substitution of nullish coalescing
const containerFive = [undefined, null].includes(data.falsyValue) || 'fallback'
console.log('container five =', containerFive); // container three = fallback
// with || the second operand is evaluated if the first operand is undefined, null, false, 0, NaN or ''.
// with ?? on the other hand limits this list to only undefined and null.
// inspired by https://flaviocopes.com/javascript-nullish-coalescing/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment