-3

For example,

x = 1;
y = 2;
swap ('x', 'y');
console.log (x); // 2
console.log (y); // 1

The swapped value may be not a simple variable

How to swap two variables in JavaScript doesn't require to have a calling, so it differs from this question.


Solved. I didn't know that the ref of left of = is evaled before the right is calculated

Community
  • 1
  • 1
l4m2
  • 1,157
  • 5
  • 17

2 Answers2

0

Try this:

function swap(x, y) {
  return [y, x]
}

[x, y] = swap(x, y);
MarmiK
  • 5,639
  • 6
  • 40
  • 49
pcu
  • 1,204
  • 11
  • 27
0

For global variables, you could use the window object with the names as key.

function swap(a, b) {
    var temp = window[a];
    window[a] = window[b];
    window[b] = temp;
}

var x = 1,
    y = 2;

swap ('x', 'y');
console.log (x); // 2
console.log (y); // 1
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • But not for variables in function – l4m2 Jan 11 '17 at 06:04
  • 1
    Its a bad practice polluting window. Why would you suggest it. Also, this is a duplicate. We should not answer duplicates as most of the approaches have been answered and have comments/ explanations for better understanding – Rajesh Jan 11 '17 at 06:04
  • i think the question is for educational purpose, as this answer. in real working environment, the problem is not solvable, because of the limited usage. – Nina Scholz Jan 11 '17 at 06:12