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'}
.
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'}
.
- 2 Please show what you have tried that didn't work. – charlietfl Commented Jun 25, 2017 at 19:53
- 3 Possible duplicate of How to swap two variables in JavaScript – Omri Luzon Commented Jun 25, 2017 at 20:03
3 Answers
Reset to default 4You 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.
If you are using ES6+ try this:
[a, b] = [b, a];
Otherwise:
b = [a, a = b][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;