Sunday, December 29, 2024
Google search engine
HomeLanguagesJavascriptHow to swap variables using destructuring assignment in JavaScript ?

How to swap variables using destructuring assignment in JavaScript ?

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
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments