Best of Modern JavaScript — Destructuring and Defaults

Image for post
Image for post
Photo by Todd Quackenbush on Unsplash

Since 2015, JavaScript has improved immensely.

It’s much more pleasant to use it now than ever.

In this article, we’ll look at JavaScript destructuring.

Array Patterns Work with Iterable Object

We can use array patterns like the rest operator with iterable objects.

For example, we can write:

The x is 'f' and y is ['o', 'o'] .

Since strings are iterable, we can destructure them.

Destructuring also works with string code points.

For example, we can write:

The x is 'a' , b is '\uD83D\uDCA9' and z is 'c' .

Default Values

We can set default values when destructuring.

For example, we can write:

Then x is 13 and y is undefined since the array is empty.

Since 13 is the default value of x , it’s assigned to it.

Therefore undefined triggers default values to be assigned.

Default values are computed on demand.

If they aren’t needed, then they won’t be used.

For example, if we have:

Then that’s the same as:

Default values can refer to other variables in the pattern.

For instance, we can write:

Then x and y are both 13.

If we have:

Then x and y are both 17.

And if we write:

Then x is 7 and y is 4.

The default value is only used when there’s no corresponding value on the right side.

We can also have default object values when destructuring.

For example, we can write:

Then x is an empty object since there’s nothing on the right side.

If we have:

we get the same thing.

If we have:

Then x is foo since we assigned an object to the left side with the default value.

However, if we have:

Then x us undefined since we have an object in the array on the right side, so the default value won’t be assigned on the left side.

If we want to trigger the default value assignment, then we’ve to assign a default value to the property itself:

Then x would be 'foo' since prop isn’t found on the right side.

Property Value Shorthands

Property value shorthand works like we expect with destructuring as we can see from the previous examples.

So:

is the same as:

Image for post
Image for post
Photo by Behzad Ghaffarian on Unsplash

Conclusion

Destructuring can be done with objects and arrays.

There’re many tricks with default values.

Written by

Web developer. Subscribe to my email list now at http://jauyeung.net/subscribe/. Email me at hohanga@gmail.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store