post/

Where Will We Go

February 6, 20212 min read

Lifestyle, JavaScript, Coding

The real hidden features are the friends we made along the way. ā€” Jane Manchun Wong

Defaulting values

1.) Use ?? - nullish coalescing operator to default values if the variable is undefined or null.

Example where dataSet is an object.

const dataSet = {};

// destruct -> assign
const { expirationDate } = dataSet;

console.log(expirationDate ?? 'N/A');

For this example, the code above will return "N/A" because the expirationDate is not defined.

2.) Use the || - OR operator to default values if the variable is defined but falsy.

Here's an example with a key of an object to compare is defined but falsy.

const dataSet = {
  expirationDate: '', // <- defined
};

const { expirationDate } = dataSet;

console.log(expirationDate || 'N/A');

For this example, the code above will return "N/A" because the expirationDate is falsy. It is falsy because it is declared as an empty string.

Check the complete list of falsy values in JavaScript at MDN.

Summary

  • ?? - nullish coalescing returns the right side if the left value is either undefined or null.
  • || - OR operator returns the right side if the left value is falsy.
Now playing :Not playing any music.