Member-only story

Swap Values with Destructuring in JavaScript — A Handy Trick for Interviews

Vinodh Thangavel
1 min readJul 11, 2023

--

In JavaScript, swapping values between variables is often a topic that comes up during technical interviews. Using destructuring, you can achieve this in a clean and concise manner. The syntax for swapping values is slightly different from usual destructuring.

Swapping Variables

Consider the following example:

let x = 10; // Use 'let' because the value will be changed later
let y = 20; // Use 'let' for the same reason
[y, x] = [x, y]; // No need to use 'const' or 'let' here
console.log(x, y); // Outputs: 20 10

In this code, we use array destructuring to swap the values of x and y. It’s important to note that let is used instead of const because the values of x and y will be reassigned.

Bonus — Swapping Elements in an Array

You can also use destructuring to swap elements within an array:

const numbers = [1, 2, 3]; // You can use either 'const' or 'let'
[numbers[1], numbers[0]] = [numbers[0], numbers[1]];
console.log(numbers); // Outputs: [2, 1, 3]

In this case, you can use const because the array reference itself isn’t changing; only the elements within the array are being swapped. This flexibility with const and let makes destructuring a powerful tool in JavaScript

--

--

Vinodh Thangavel
Vinodh Thangavel

Written by Vinodh Thangavel

Passionate lifelong learner, coding enthusiast, and dedicated mentor. My journey in tech is driven by curiosity, creativity, and a love for sharing knowledge.

No responses yet