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.

List of programming languages used for Web Development

Updated 16th August 2022

There are a wide variety of programming languages that can be used for web development. Which one you choose depends on your preferences and needs. Some languages are better suited for certain tasks than others. In this post, we’ll take a look at some of the most popular languages used for web development. JavaScript PHP

JavaScript Spread & Rest Operators

Updated 28th July 2022

In JavaScript, three dots ( … ) are used for both the Spread and Rest operators. Spread and Rest perform different actions. Let’s learn what the JavaScript Spread & Rest Operators do. JavaScript Spread Operator The JavaScript Spread Operator ( … ) allows us to copy and split an Array or Object into another Array

Vue 3 Popup Modal Component – Create a Modal

Updated 23rd August 2022

In this post, I’m going to show you how to create a Popup Modal Component in Vue 3. This Popup Modal will use the built-in transition component. The Modal we will create looks a lot like the Modal Dialogs used by Apple in iOS. We will use Tailwind CSS for styling. What is Vue?  Vue