Open In App

How to swap variables using destructuring assignment in JavaScript ?

Last Updated : 05 Nov, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Destructuring assignment is a feature introduces in EcmaScript2015 which lets you extract the contents of array, properties of object into distinct variables without writing repetitive code.

Example 1: Here in this example we declared two variables a and b unassigned and an array with two strings “First” and “Second” int it. On line 5 we used destructuring assignment to assign values of array to and b respectively.

Javascript




<script>
  let a;
  let b;
  let array = ["First", "Second"];
  
  [a, b] = array;
  console.log("a:", a);
  console.log("b:", b);
</script>


Output:

a: First 
b: Second

As you can see variable a has string “First” assigned and variable b has string “Second” assigned.

Example 2: Here we declared two variables a and b having values “First” and “Second” respectively. In the next line we swapped variables using destructuring assignment.

Javascript




<script>
  let a = "First";
  let b = "Second";
  [a, b] = [b, a];
  
  console.log("a:", a);
  console.log("b:", b);
</script>


Output:

a: Second
b: First

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads