JavaScript Destructuring Explained with Example

JavaScript Destructuring Explained with Example.

Javascript destructuring is a special syntax that was introduced in ES6. In this article, we will be discussing javascript destructuring, let’s get started.

javaScript-destructuring

What is Javascript Destructuring?

Javascript destructuring is a special syntax that allows assigning values from an object property or an array straight into a variable.

JavaScript Code Runner on: destructuring

Related: Javascript Closures Explained

Example 1:

In this example, we will see how to write a code using javascript destructuring with a simple example.

const indgeek = ["technology", "finance"];
 
const article1 = indgeek[0];
const article2 = indgeek[1];

In this code snippet, we have just assigned two values from an array into a variable without using javascript destructuring. Now we will write the same code using the javascript destructuring method.

// with destructuring
const indgeek = ["technology", "finance"];
 
const [article1, article2] = indgeek; // used javascript destructuring
 
console.log(article1); // technology
console.log(article2); // finance

Here we write the same code but have used javascript destructuring instead of writing the first method.

Example 2:

In this example, we will work with an object. First, we will create an object and then assign values.

const YouTubeChannel = {
  // object
  name: "indgeek",
  sub: 500,
  type: "technology"
};
 
const { name, sub, type } = YouTubeChannel; // assigning values into variable
 
console.log(name); // indgeek
console.log(sub); // 500
console.log(type); // technology

In this example, we have assigned all values to different variables and then printed them.

const YouTubeChannel = {
  // object
  name: "indgeek",
  sub: 500,
  type: "technology"
};
 
const { name, sub, type } = YouTubeChannel; // assigning values into variable
 
console.log(name); // indgeek
console.log(sub); // 500
console.log(type); // technology

For that example, we have assigned the name value of the object to the name variable and then assigned all the values to the other variable.

Example 3:

const YouTubeChannel = {
  name: "indgeek",
  sub: 500,
  type: "technology"
};
 
const { name, ...other } = YouTubeChannel;
 
console.log(name); // indgeek
console.log(other); // { sub: 500, type: 'technology' }

Here we changed the name of the variable and also change their position. To do that we specify all the variables with all values name.

Summing Up:

In this article, we have learned javascript destructuring with some examples. But if you want to learn more (opens in a new tab) about javascript then subscribe here. I hope you like the post. If you do, please share it with your friend.

IndGeek provides solutions in the software field, and is a hub for ultimate Tech Knowledge.