-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

6
  • 1
    And what have you tried so far? Commented Jan 11, 2017 at 5:57
  • The problem is that javascript can't use pointers and can't modify the variable by a reference to it. Commented Jan 11, 2017 at 6:01
  • +David Archibald So I made the arguments in string Commented Jan 11, 2017 at 6:03
  • @l4m2 please use @ to tag someone. Commented Jan 11, 2017 at 6:05
  • I don't quite understand how using a string would help, but as it is now closed, I will drop it. Commented Jan 11, 2017 at 6:06

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

But not for variables in function
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
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.
0

Try this:

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

[x, y] = swap(x, y);

1 Comment

It changes the calling of swap

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.