-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;
0

3 Answers 3

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}`);

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

Comments

0

Using es2015 you can do

[x,y] = [y,x]

Comments

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);

1 Comment

@anulik this code use the third variable for swap x and y. This code help for solving your problem?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.