- Write Cleaner Code by Using JavaScript Destructuring
- Originally published by Juan Cruz Martinez
- The Nuggets translation Project
- Permanent link to this article: github.com/xitu/gold-m…
- Translator: zenblo
- Proofreader: NieZhuZhu, Regon-Cao
Using JavaScript deconstruction makes code more elegant
Deconstruction is one of my favorite JavaScript features. In short, deconstruction can decompose complex structures (such as sets of numbers or objects) into simpler parts, simplifying the structure of the code relatively, although there is much more to it.
Let’s take a look at an example to better understand:
const article = {
title: "My Article".rating: 5.author: {
name: "Juan".twitter: "@bajcmartinez"}}// Now print it out
console.log(`"${article.title}" by ${article.author.name} had ${article.rating} stars`)
// This can also be done using deconstruction
const { title, rating, author: { name } } = article
console.log(`"${title}" by ${name} had ${rating} stars`)
------------------------
Output
------------------------
"My Article" by Juan had 5 stars
"My Article" by Juan had 5 stars
Copy the code
Now, some people have been developing with deconstruction for a while, probably when building React applications, but they don’t fully understand it. For others, this may be the first time deconstruction is used. Therefore, this paper will complete the whole process from beginning to end, and finally make everyone’s cognition of deconstruction reach the same level.
Deconstruction object
In the above example, all the hidden content takes place in this line of code:
const { title, rating, author: { name } } = article
Copy the code
Now, using curly braces like this on the left side of an expression might seem a little strange, but that’s how we tell JavaScript we’re shredding an object.
Destruct objects can be bound to any property at any level within the object. Let’s start with a simpler example:
const me = {
name: "Juan"
}
const { name } = me
Copy the code
In the example above, we declare a variable named name that will get an initialization property of the same name from the object me, so when we evaluate name, we get Juan. That’s great! This operation also applies to attributes at any level. Back to our example:
const { title, rating, author: { name } } = article
Copy the code
For title and rating, just like we did before. But in author’s case, things are a little different. When we encounter a property that is an object or array, we have the choice of creating a reference object, article. Author, to the variable author, or doing a deep deconstruction and immediately accessing the properties of the internal object.
Accessing object properties:
const { author } = article
console.log(author.name)
------------------------
Output
------------------------
Juan
Copy the code
Perform deep or nested deconstruction:
const { author: { name } } = article
console.log(name)
console.log(author)
------------------------
Output
------------------------
Juan
Uncaught ReferenceError: author is not defined
Copy the code
What happened to the above example? If author is deconstructed, why is it not defined? It’s actually pretty simple. Remember that when we ask JavaScript to also deconstruct the author object, the binding itself is not created, but instead we have access to all author attributes of our choice.
Extended operators (…) :
const article = {
title: "My Article".rating: 5.author: {
name: "Juan".twitter: "@bajcmartinez"
const{ title, ... others } = articleconsole.log(title)
console.log(others)
------------------------
Output
------------------------
My Article
> {rating: 5.author: {name: "Juan".twitter: "@bajcmartinez" }}
Copy the code
In addition, we can use the extension operator… Create an object that contains all undeconstructed attributes.
If you’re interested in learning more about extension operators, check out my article.
Renaming attributes
An important feature of deconstruction is the ability to select different variable names for the attributes we extract. Let’s look at the following example:
const me = { name: "Juan" }
const { name: myName } = me
console.log(myName)
------------------------
Output
------------------------
Juan
Copy the code
By using it on an attribute: we can give it a newName (newName in our case). We can then access this variable in our code. Note that the variable for the original property name is not defined.
The lack of properties
So what happens if we try to deconstruct a property that is not defined in an object?
const { missing } = {}
console.log(missing)
------------------------
Output
------------------------
undefined
Copy the code
In this case, the value of the variable is undefined.
The default value
Extend missing attributes to specify a default value when the attribute does not exist. Let’s look at some examples:
const { missing = "missing default" } = {}
const { someUndefined = "undefined default" } = { someUndefined: undefined }
const { someNull = "null default" } = { someNull: null }
const { someString = "undefined default" } = { someString: "some string here" }
console.log(missing)
console.log(someUndefined)
console.log(someNull)
------------------------
Output
------------------------
missing default
undefined default
null
some string here
Copy the code
These are all examples of deconstructing object assignment. The default value is assigned only to the property undefined. For example, if the value of an attribute is null or string, the default value is not assigned, but the actual value of the attribute is assigned.
Deconstruct arrays and iterables
We’ve seen some examples of deconstructing objects, but the same applies to arrays or iterables. Let’s start with an example:
const arr = [1.2.3]
const [a, b] = arr
console.log(a)
console.log(b)
------------------------
Output
------------------------
1
2
Copy the code
When we need to deconstruct an array, we need to use [] instead of {}, and we can map each position of the array with different variables. But there are some good ones:
Skip the element
By using the, operator, we can skip some elements of the iterable data item, as follows:
const arr = [1.2.3]
const [a,, b] = arr
console.log(a)
console.log(b)
------------------------
Output
------------------------
1
3
Copy the code
Note that leaving a space between, skips elements. It’s a small detail, but it makes a big difference.
What else can you do? You can also use extension operators… Perform the following operations:
const arr = [1.2.3.4.5.6.7.8.9.10]
const [a,, b, ...z] = arr
console.log(a)
console.log(b)
console.log(z)
------------------------
Output
------------------------
1
3
(7) [4.5.6.7.8.9.10]
Copy the code
In this case, z will get all the values after B as an array. Or you have a more specific requirement that you want to deconstruct at a specific location in the array. No problem, JavaScript can still do this:
const arr = [1.2.3.4.5.6.7.8.9.10]
const { 4: fourth, 9: ninth } = arr
console.log(fourth)
console.log(ninth)
------------------------
Output
------------------------
5
10
Copy the code
If we deconstruct an array as an object, we can use indexes as properties to access values anywhere in the array.
The lack of properties
As in the case of objects, you can set default values for undefined elements in an array. Let’s look at some examples:
const [missing = 'default missing'] = []
const [a, b, c = "missing c". others] = [1.2]
console.log(missing)
console.log(a)
console.log(b)
console.log(c)
console.log(others)
------------------------
Output
------------------------
default missing
1
2
missing c
[]
Copy the code
You can also set the default value for the undefined property when deconstructing an array. However, when we use the extension operator… Cannot set a default value for a variable. In the use of… When you deconstruct undefined, it returns an empty array:
Switching variable
This is an interesting example of deconstruction. Two variables can be swapped in an expression:
let a = 1
let b = 5
[a, b] = [b, a]
console.log(a)
console.log(b)
------------------------
Output
------------------------
5
1
Copy the code
Destruct using computed properties
Until now, whenever we wanted to deconstruct an object property or an iterable element, we used static keys. If we want dynamic keys (such as keys stored in variables), we need to use computed properties:
Here’s an example:
const me = { name: "Juan" }
let dynamicVar = 'name'
let { [dynamicVar]: myName } = me
console.log(myName)
------------------------
Output
------------------------
Juan
Copy the code
By using a variable in [], we can evaluate its value before assigning it. Therefore, although you must provide a name for this new variable, dynamic deconstruction is possible.
Destruct function parameters
Destructuring variables can be used anywhere we declare variables (for example, by using let, const, or var), as well as function arguments. Here’s a simple example:
const me = { name: "Juan" }
function printName({ name }) {
console.log(name)
}
printName(me)
------------------------
Output
------------------------
Juan
Copy the code
Very simple. In addition, all the rules we discussed earlier apply.
conclusion
Deconstruction can be uncomfortable at first, but once you get used to it, there’s no going back. It can really make your code cleaner, which is a concept to understand.
Did you know that you can also use deconstruction when importing modules? Check out my article on this topic.
Thanks for reading! I hope you like it.
If you find any mistakes in your translation or other areas that need to be improved, you are welcome to the Nuggets Translation Program to revise and PR your translation, and you can also get the corresponding reward points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.
The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.