user1243746
user1243746

Reputation:

swapping values of two variables, order of precedence?

var a = 1, b = 9;
a, b = b, a;
console.log(a,b)

1 9

Is possible that the assignments were carried out in left-to-right order? So, "a" would take the value of "b" and and "b" the value of "a".

Upvotes: 0

Views: 181

Answers (1)

Tengiz
Tengiz

Reputation: 8409

Swapping values should be pretty simple:

var temp = b;
b = a;
a = temp;

EDIT: if it's all about integers, swapping can happen even without additional variable:

b = b - a;
a = a + b;
b = a - b;

Upvotes: 1

Related Questions