azmul hossain
azmul hossain

Reputation: 1351

Swap multiple variables in ECMAScript 6

Suppose three variables are

let x = 10, y = 20, z = 30;

and another three variables are

let a = 1, b = 2, c = 3;

I want to swap these variable's value

Input is:

let x = 10, y = 20, z = 30;
let a = 1, b = 2, c = 3;

output is:

let x = 1, y = 2, z = 3;
let a = 10, b = 20, c = 30;

Upvotes: 0

Views: 327

Answers (1)

Michał Perłakowski
Michał Perłakowski

Reputation: 92501

You can use destructuring assignment to swap variables:

let x = 10, y = 20, z = 30
let a = 1, b = 2, c = 3

;[x, y, z, a, b, c] = [a, b, c, x, y, z]

console.log(`x: ${x}, y: ${y}, z: ${z}, a: ${a}, b: ${b}, c: ${c}`)

Upvotes: 3

Related Questions