DEV Community

Cover image for Swap two variables without a 3rd : JavaScript
shivamkapasia0
shivamkapasia0

Posted on

3 2

Swap two variables without a 3rd : JavaScript

Destructuring assignment

Destructuring assignment (a feature of ES2015) lets you extract items of an array into variables.

let firstName = 'Shivam', secondName = 'Kapasia';
[firstName, secondName] = [secondName, firstName];
console.log('firstName: ' + firstName); // Kapasia
console.log('secondName: ' + secondName); // Shivam
Enter fullscreen mode Exit fullscreen mode

you can also swap two arrays like :

let array1 = [1,2,3], array2 = [3,4,5];
[array1, array2] = [array2, array1];
console.log(`${array1}`); // 3,4,5
console.log(`${array2}`); // 1,2,3
Enter fullscreen mode Exit fullscreen mode

I like the destructuring approach because it’s short and expressive: swapping is performed in just one statement. It works with any data type: numbers, strings, booleans, objects,arryas etc.

I recommend swapping variables using a destructuring assignment for most of the cases.

What’s your preferred way to swap variables?

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series