3 Ways to set default values

afozbek

Abdullah Furkan Özbek

Posted on September 1, 2021

3 Ways to set default values

1. Variables

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. We can use this to set default values, for example when we receive a list that has not been set to an array yet:

const bookList = receivedBooks ?? [];
Enter fullscreen mode Exit fullscreen mode

2. Parameters

We could use the null coalescing operator to set defaults for variables in functions but there is a better way, default parameters:

function calculateArea(width, height = 100) {
    return width * height;
}

const area = calculateArea(50);
console.log(area); // 5000

Enter fullscreen mode Exit fullscreen mode

3. Objects

We can also give default value once we destructure object properties. ES6 destructuring default values only kick in if the value is undefined.

const rectangle = { height: 400 };
const { height = 750, width = 500 } = rectangle;
console.log(height); // 400 - comes from rectangle object
console.log(width);  // 500 - fallback to default

Enter fullscreen mode Exit fullscreen mode

Links

💖 💪 🙅 🚩
afozbek
Abdullah Furkan Özbek

Posted on September 1, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

3 Ways to set default values
javascript 3 Ways to set default values

September 1, 2021

#100DaysOfJavascriptTeaching
javascript #100DaysOfJavascriptTeaching

December 31, 2019