Saturday, December 1, 2018

Destructuring in JavaScript & ES6

This tutorial explains how to implement destructuring in javascript programming language. Destructuring is a powerful way to create variables from values in arrays and objects, and It will make your code simpler.

What is destructuring?

Destructuring was introduced in ES6. It’s a JavaScript feature that allows us to extract multiple pieces of data from an array or object and assign them to their own variables.

Destructuring in JavaScript


Array destructuring :

If you want to assign the values of an array to separate variables, you can take advantage of destructuring to achieve your goal in a simple, clean way. Lets see the below simple example for array destructuring.

Example :-1
Lets see the simple example for array destructuring.
const arr = ['skptricks', 'sumit', 'amit', 'ram'];
const [getA, getB, getC, getD] = arr;

console.log(getA); 
console.log(getB); 
console.log(getC); 
console.log(getD); 

Output :-
--------------------------
> "skptricks"
> "sumit"
> "amit"
> "ram"

Example :-2
Lets see the below example, where we need first 2 values as variables, and the rest as an array.
const arr = ['skptricks', 'sumit', 'amit', 'ram'];
const [getA, getB, ...theRest] = arr;

console.log(getA); 
console.log(getB); 
console.log(theRest); 

Output :-
--------------------------
> "skptricks"
> "sumit"
> Array ["amit", "ram"]

Example :-3 
lets see the default values example using array destructuring
const arr = ['skptricks', 'sumit',];
const [getA = 'sumit', getB = 'skps', getC = 'NA', getD ='NA'] = arr;

console.log(getA); 
console.log(getB); 
console.log(getC); 
console.log(getD); 
  
Output :-
-----------------------------------------------
> "skptricks"
> "sumit"
> "NA"
> "NA"

Object destructuring :

We can also use the destructuring assignment syntax to assign object values to variables.

Example :-1 
This is a simple example for Object destructuring.
const emplyoee = {
  name: 'sumit kumar pradhan',
  age: 23,
  salary: 465
};
const { name, age, salary } = emplyoee;

console.log(name); 
console.log(age); 
console.log(salary); 

Output :-
--------------------------
> "sumit kumar pradhan"
> 23
> 465

Example :-2 
lets see the default values example using object destructuring
const employee = {
  name: 'sumit kumar pradhan',
  
};
const { name, age = 0 , salary = 0  } = employee;

console.log(name); 
console.log(age); 
console.log(salary);

Output :-
--------------------------
> "sumit kumar pradhan"
> 0
> 0

This is all about array and object destructuring in javascript. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.


No comments:

Post a Comment