Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do these statements work differently in JavaScript?

Tags:

javascript

xor

I was recently checking out sweet little code to swap two variables using XOR function. I used JavaScript for this.

Let x and y be two variables and let x = 4, y = 6.

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

It swaps variables nicely. Notice that I'm keeping x and y different to prevent aliasing which can occur due to first XOR.

Then, observing the statement, I wrote: x = x ^ (y = y ^ (x = x ^ y )); This swaps variable y correctly but makes x always 0.

Also, x ^= y ^= x ^= y; which also seems to be equivalent expression yields the same incorrect result as in second case.

However, all these statements run equivalently on Java and produce the same result consistently.

I also used strict mode with JavaScript.

Are these three statements somehow not equivalent on JavaScript or am I missing something critical here?

like image 495
Ozil Avatar asked Jul 21 '16 17:07

Ozil


People also ask

What are the different statements used in JavaScript?

JavaScript statements are composed of: Values, Operators, Expressions, Keywords, and Comments.

How does JavaScript statements work?

Statements are used in JavaScript to control its program flow. Unlike properties, methods, and events, which are fundamentally tied to the object that owns them, statements are designed to work independently of any JavaScript object.

What are the three types of statements in JavaScript?

The initialization statement is executed before the loop begins. The test statement which will test if the given condition is true or not. If condition is true then code given inside the loop will be executed otherwise loop will come out. The iteration statement where you can increase or decrease your counter.

Why do we use if else statements in JavaScript?

Definition and Usage. The if/else statement executes a block of code if a specified condition is true. If the condition is false, another block of code can be executed. The if/else statement is a part of JavaScript's "Conditional" Statements, which are used to perform different actions based on different conditions.


1 Answers

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

This works because it's like

x_1 = x_0 ^ y_0;
y_1 = y_0 ^ x_1;
x_2 = x_1 ^ y_1;

Then,

x_final = x_2 = x_1 ^ y_1 = x_0 ^ y_0 ^ y_0 ^ x_1 = x_0 ^ y_0 ^ y_0 ^ x_0 ^ y_0
        = y_0
y_final = y_1 = y_0 ^ x_1 = y_0 ^ x_0 ^ y_0
        = x_0;

Your x = x ^ (y = y ^ (x = x ^ y )); is like

x_1 = x_0 ^ y_0;
y_1 = y_0 ^ x_1;
x_2 = x_0 ^ y_1;

Then,

x_final = x_2 = x_0 ^ y_1 = x_0 ^ y_0 ^ x_1 = x_0 ^ y_0 ^ x_0 ^ y_0
        = 0
y_final = y_1 = y_0 ^ x_1 = y_0 ^ x_0 ^ y_0
        = x_0;

It would have worked if you used x = (y = y ^ (x = x ^ y )) ^ x;.

That's because JS parses the expressions from left to right, and you want that x to be the modified value, not the initial one.

like image 58
Oriol Avatar answered Sep 23 '22 16:09

Oriol