DEV Community

Marco Pestrin
Marco Pestrin

Posted on • Edited on

4 1

How to swap 2 variables in javascript

Normally to swap two variables you need a temporary variable because when the first variable is reassigned you lose the value.

let a = 'apple';
let b = 'orange';

let tmp = a;
a = b;
b = temp;
Enter fullscreen mode Exit fullscreen mode

We have the syntax available to perform a swap without need an intermediate variable.

let a = 'apple';
let b = 'orange';

[a, b] = [b, a];

console.log(a); // orange
console.log(b); // apple
Enter fullscreen mode Exit fullscreen mode

Javascript destructuring enable variable swapping without need an intermediate variable.

Cheers mates!

Top comments (0)

SurveyJS custom survey software

JavaScript UI Library for Surveys and Forms

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

View demo

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay