Destructuring assignment
Check out the video course and find the latest coupon code in the comment area below.
coupon code template: 2019OCT, 2019NOV, 2019DEC, etc.
Destructuring assignment allows us to quickly retrieve values from an array or an object and assign them to variables. It also allows us to set default variable values.
Let’s start with an array.
First, we declare four variables. We only need one let or var here. Just separate each variable name with a comma.
Then we put the four variables in a set of square brackets and assign the list array to it.
The key of successful destructuring assignment is matching patterns. As long as the left pattern is the same as the right one, all variables will receive the right value.
In your future projects, you should keep the pattern as simple as possible. Overly complicated patterns are bad for program efficiency. They will also make your program more difficult to maintain.
When we destructure an array, we also also use the spread operator. But the spread operator only works with the last variable.
You can also set default variable values.
Destructuring assignment also works with objects. But you need to wrap the assignment expression using a set of parenthesis.
But the parenthesis is not needed if you merge the declaration and value assignment.
When you are developing programs using frameworks or third-party libraries, destructuring objects can be very convenient.
Sometimes, we might want to name the variable differently than the property. What should we do?
Inside the left object, we set a key value pair.
The key must be the same as the property name. The value is set by us and will be used as variable name.
Attention here, the key is only used as an identifier. It will not be declared as a variable. Even if we declare the key as a variable, it still won’t receive any value.
You need to keep the parenthesis this time.
Real-life application:
Next, let’s take a look at the real-life application of object destructuring.
We got a negative number and we want to turn it into a positive one. The ABS method from the math constructor can help us do this.
But every time we use the ABS method, we need to prefix it with math. This is just not so convenient.
Using object destructuring, we can retrieve and assign the abs method to the abs variable.
Next time we need the abs method, we no longer need prefix it with the Math object.
You can also destructure a string.
If you destructure a string as an array, you will retrieve each character.
If you destructure a string as an object, you will retrieve properties and methods from the String constructor.
A number can only be destrucutred as an object. You CANNOT destructure it as an array.
A boolean can only be destructured as an object.
NULL and undefined CANNOT be destructured at all.