Destructuring in JavaScript

By Dillon Smart · · · 0 Comments

Destructuring In JavaScript

Introduced in ES6, Destructuring in JavaScript is a way to unpack values from arrays, or properties from objects, into distinct variables.

What is a use-case of Destructuring in JavaScript?

Until ES6, if we wanted to extract data from an array we would have to do something similar to:

let message = ["Hello", "Dillon"];
let greeting = message[0];
let name = message[1];

console.log(greeting); // Output: "Hello"
console.log(name); // Output: "Dillon" 

How to use Destructuring in JavaScript

If we want to extract data from an array, using Destructuring in JavaScript we can do it a lot easier.

Using the same example as above, but this time we will use the Destructuring Assignment.

let message = ["Hello", "Dillon"];
let [greeting, name] = message;

console.log(greeting); // Output: "Hello"
console.log(name); // Output: "Dillon" 

Declaring variables before assignment

With the destructuring assignment, we can also declare the variables before they are assigned.

let greeting, name;
let [greeting, name] = ["Hello", "Dillon"];

console.log(greeting); // Output: "Hello"
console.log(name); // Output: "Dillon" 

We can also skip items in the array like so:

let [greeting,,msg] = ["Hello", "Dillon", "Welcome"];

console.log(greeting); // Output: "Hello" 
console.log(msg); // Output: "Welcome" 

Conclusion

Many features introduced in ES6 can be overlooked.

Learn about Spread & Rest Operators in JavaScript.

JavaScript

0 Comment

Was this helpful? Leave a comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.

What is a front-end application?

Updated 16th August 2022

What is a front-end application? If you’re new to Web Development, there may be many terms you hear that you’re unsure what they mean. Don’t worry, this is all part of the learning experience and you will pick these terms up as you progress in your journey to becoming a web developer. In this post,

Angular Material Dialog

Updated 16th August 2022

Angular is an awesome framework, yet it does have a steep learning curve for many developers. This post is aimed at those with experience using Angular 2/4/5 who want to use the Angular Material Dialog. This post will assume you have already installed the @angular/material library. If you have I would refer you to take

Angular: Call a Parent method in Child Component using @Output

Updated 16th August 2022

In JavaScript frameworks, such as Angular, it’s common for components to communicate with each other and send data back and forth. In this post, I will show you how to call a parent method from a child component in Angular with the @Output decorator using EventEmitters. In all JavaScript frameworks, it’s common for child components