-1

If I have a

x = 5;
y = 6;

how can I set result like this, without having a middle, additional variable.

x = 6;
y = 5;
Anna Gabrielyan
  • 2,120
  • 3
  • 28
  • 48

3 Answers3

2

1) Only using math operations you can do like this. Keep the sum into the first variable. Then in the second keep the difference of the sum and the current's value, which will give the first value. After this in the first variable keep the difference of the sum and the seconds value, which will give you the first value.

let x = 5;
let y = 6;

console.log(`x is ${x}, y is ${y}`);

x = x + y;
y = x - y;
x = x - y;

console.log(`x is ${x}, y is ${y}`);

2) With using language features you can do it via Array Destructuring.

let x = 5;
let y = 6;

console.log(`x is ${x}, y is ${y}`);

[x, y] = [y, x];

console.log(`x is ${x}, y is ${y}`);

3) Using famous XOR swap algorithm if the numbers are integers.

let x = 5;
let y = 6;

console.log(`x is ${x}, y is ${y}`);

x = x ^ y;
y = x ^ y;
x = x ^ y;

console.log(`x is ${x}, y is ${y}`);
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
0

Using es2015 you can do

[x,y] = [y,x]

Vijay
  • 286
  • 1
  • 9
0

1) you can use a third variable for swap for x and y value. So, if the third variable is temp.

1 st step temp = x

2 nd step x = y

3 rd step y = temp

 var x = 5;
 var y = 6;
 var temp = 0;

  temp = x;
  x = y;
  y = temp;

  console.log('x =',x);
  console.log('y =',y);

2) ES6

var x = 5,
    y = 6;

[x, y] = [y, x];

console.log('x =', x, 'y =', y);
sameera lakshitha
  • 1,925
  • 4
  • 21
  • 29