1

recently I have read tutorial from some of the web page about Javascript function that shuffles array. but some portion of the code I didn't understood completely. for ex:here is js fiddle

here i dont understand this code part

this[i] = this[j] + (this[j] = this[i],0);

what does it means (this[j] = this[i],0); ? Thanks in advance

1
  • 1
    This is a kinda "clever" way to exchange two array elements. Don't use this. Commented Feb 24, 2016 at 6:55

2 Answers 2

3

The code is just doing a 1-line swap.

You're familiar with the standard swap, correct?

A = 6, B = 10

X = A

A = B

B = X

now B = 6, and A = 10

Take a look at your tutorial code

this[i] = this[j] + (...) means that the assignment will not take place right away. Instead, the parenthetical must be calculated first. However, the browser will temporarily make a note of the value of this[j], essentially copying it to X.

(this[j] = this[i],0) can now be calculated, but what does the parenthesis return to be added to the outside this[j]? The 0! So inside the parenthesis, the second step of the swap took place, and 0 is added to the temporary X!

Now the calculation becomes this[i] = this[j] + 0. The third step of swap!

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

Comments

2

For any expression with commas, all expressions are executed and the last expression is returned.

var a = (1+1, 2+2, 3+3);
// a = 6

For the case above:

this[i] = this[j] + (this[j] = this[i], 0);

is equivalent to:

var temp = this[j];
this[j] = this[i];
this[i] = temp + 0;

The temp is automatically handled, because left-side (this[j]) is evaluated first.

More details

3 Comments

Thanks for reply, but i did't understand the meaning of 'temp + 0;'
(this[j] = this[i], 0) expression evaluates this[j] = this[i] and 0, and returns only the right-most expression (0). The 0 comes from there, and temp comes from this[j].
Thanks very much. Now i understood!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.