Open In App

How to Swap Variables using Destructuring Assignment in JavaScript?

Last Updated : 12 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

JavaScript
// Given variables
let a = 10;
let b = 25;

// Swap values using Destructuring Assignment
[a, b] = [b, a];

// Display updated values
console.log("Updated Values= a:",a, "b:",b );

Output
Updated Values= a: 25 b: 10

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

JavaScript
// Given values
// Assign values from array using Destructuring Assignment
let [a, b, c] = [ 30, 40, 50 ];

// Swap values using Destructuring Assignment
[a, b, c] = [b, c, a];

// Display updated values
console.log("Updated Values= a:",a, "b:", b,"c:", c );

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


Similar Reads