Welcome to the 58th Easy JavaScript Tutorial! Thought I'd do another JS tutorial as I work on more Raspberry Pi videos (RPi takes much longer to do).
The objective of this tutorial is to learn about destructuring in JavaScript. There are two types: Array Destructuring and Object Destructuring.
Destructuring allows you to unpack values from arrays and properies from objects into distinct variables which can make your code more readable and easier to understand.
Here's an example of array destruturing:
const arr = ['Apple', 'Banana', 'Carrot'];
const [a, b, c] = arr;
We have an array called 'arr' with three values. You can access the individual values in several ways. The most common way is something like arr[0]
which will give you the value of 'Apple.' You can assign this value to a variable and access it that way. But look at the example above. You can assign the first 3 values of the array (this array just has 3) to three different variables in one line of code. It looks cleaner and it is much simpler to write.
One thing to know about array destructuring is that the position of the variable is associated with the position of the array. So the first variable will always be associated with the first array, second with second array, and so on. And you can name the variables anything you want since they are position-linked and not name-linked.
Now let's look at object destructuring:
const obj = { name: "Nazmus", city: "Boston", title: "Developer" } const {name, city, title: job} = obj;
We have object named obj
with properties name
, city
, and title
. Normally, to access a property in an object, you would do something like obj.name
to get the name. You can assign this to a variable to make it look a little neater. But object destructuring makes it look much simple. With just one line of code, we can assign distinct values to the different properties.
Unlike arrays, objects are associated by the name
of the property. So the name property will always be associated with the name
variable. So for example, if you leave out the variable city
from your list, the following variable title
will always refer to the title
property within the object.
As also shown in the example above, you can assign a different variable name to your object properties as well. Let's say you wanted to use the variable job
instead of title
, then you just do title: job
and now you can access the property with job
.
Check out the video below for a more in-depth explanation. And for the complete code, check out the JS fiddle in the following link or see the embedded version below: https://jsfiddle.net/easyjs/kjtyfp2z/
If you have questions, feel free to ask! Remember to come back for more tutorials.
Remember to checkout the Resources section below for associated downloadable content, JSFiddle links, and other resources. Watch the video and follow along!