Utilising Destructuring Assignment and Default Parameters
Sometimes you need to extract one property from an object, and if that property doesn't exist, you need to return a default value. Traditionally this was done using conditionals, something like this:
route.params.subscribe(params => {
if (!!params['id']) {
this.userId = params['id'];
} else {
this.userId = null;
}
});
With ES2015 we can use destructuring assignment and default parameters to achieve the same thing:
route.params.subscribe({id = null} => this.userId = id);
Isn't that marvellous? It's terse, readable, and clean. Plus, we've saved 6 lines of code!
Default Parameters
Let's break it down. We've already seen what this looks like if we don't use destructuring assignment and default parameters, so what would this look like if we only used default parameters?
route.params.subscribe(params = {id: null} => this.userId = params.id);
So the use of a default parameter allows us to completely remove the conditional. There is a downside to this current implementation though. The above code will only use the default value {id: null}
if no object is passed when calling the function. If we pass an object without an id
property the default value won't be used and we'll be in a situation where params.id
is undefined.
Destructuring Assignment
So, how does destructuring assignment help solve this? Well, instead of providing a default value for the object, instead we provide a default value for extracted id
property:
route.params.subscribe({id = null} => this.userId = id);
The above code extracts the id
property from the object passed to the function and sets it's default value to null
. Now, whenever this function is called we know that we'll get the value of the id
property from the passed object or null
.
Conclusion
ES2015 (ES6) introduced some great new language features that can help us write better code. By combining destructuring assignment and default parameters we can reduce boilerplate and write code using a syntax that is terse and readable.