If I have a variable called foo
set to the object: {example: '2', anotherExample: '1'}
and another variable called anotherFoo
set to 'orange'
how would I swap the values of foo
and anotherFoo
? This would mean that foo = 'orange'
and anotherFoo = {example: '2', anotherExample: '1'}
.
Asked
Active
Viewed 3,065 times
1

urwoi
- 61
- 2
- 5
-
2Please show what you have tried that didn't work. – charlietfl Jun 25 '17 at 19:53
-
3Possible duplicate of [How to swap two variables in JavaScript](https://stackoverflow.com/questions/16201656/how-to-swap-two-variables-in-javascript) – Omri Luzon Jun 25 '17 at 20:03
3 Answers
4
You can use an intermediate variable to hold the value of one.
var a = 1
var b = 2
var c = a
a = b
b = c
You can use a method shown in this link here but in my opinion is not very readable.

Justin Waite
- 835
- 2
- 8
- 16
-
2The big plus for this method is that it works in other languages, and it's very clear to new comers how it's done. – Omri Luzon Jun 25 '17 at 20:05
-
Agreed. At my company we focus on making sure our code is easy to "reason about" because scaling your software is not just about growing your user base but growing your team as well. The less kludgy the better. Thought as a developer, the cool shortcuts are very fun to use :) – Justin Waite Jun 25 '17 at 20:08
-
It's also markedly more efficient than using structuring/desctructuring. See [which way to swap two variable values is more optimised?](https://stackoverflow.com/q/55257300/5217142) – traktor Sep 03 '22 at 01:05
4
If you are using ES6+ try this:
[a, b] = [b, a];
Otherwise:
b = [a, a = b][0];

Vitaliy Vinnychenko
- 158
- 1
- 9
0
let foo = {
example: '2',
anotherExample: '1'
};
let anotherFoo = 'orange';
First, use a dummy variable to store the original value of one variable:
const dummy = anotherFoo;
Then, overwrite that variable with the original value of the second variable:
anotherFoo = Object.assign({}, foo);
Finally, overwrite the second variable with the original value of the first variable, which happens to be stored in the dummy variable:
foo = dummy;

elqueso101
- 84
- 3