VOOZH about

URL: https://www.geeksforgeeks.org/javascript/how-to-swap-variables-using-destructuring-assignment-in-javascript/

⇱ How to Swap Variables using Destructuring Assignment in JavaScript? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Swap Variables using Destructuring Assignment in JavaScript?

Last Updated : 23 Jul, 2025

Destructuring assignment in JavaScript allows us to unpack the values from arrays or objects and assign them to multiple variables.

Syntax

// Destructuring from Array, arr = [ 10, 15 ]
let [ a, b ] = arr; // a=> 10, b => 15

// Destructuring from Array, obj = { n1: 10, n2: 15 ]
let [ n1, n2 ] = obj;

JavaScript destructing assignment is used to swap the elements by swapping the variable positions in the destructuring array.

Syntax

// Swaping the values of a and b
[ a, b] = [ b, a ]

Example: This example uses the JavaScript destructuring assignment to swap the values of two variables.


Output
Updated Values= a: 25 b: 10

Example 2: This example swaps the values of 3 variables using destructuring assignment in JavaScript.


Output
Updated Values= a: 40 b: 50 c: 30
Comment