scott.lee
scott.lee

Reputation: 25

How javascript(ECMAScript) assignment operator works

When I initialize an array, I found a weird situation.

JS code:

var arr = [1, 2, 3, 4, 5];

for(var i=0, arr2=[]; i < 5; arr2[i] = arr[i++])
    console.log(arr2, i);

Output:

[] 0
[1] 1
[1, 2] 2
[1, 2, 3] 3
[1, 2, 3, 4] 4

arr2 initializes to [1, 2, 3, 4, 5] this is what i want

Look at this piece of code :

for(var i=0, arr2=[]; i < 5; arr2[i++] = arr[i])
    console.log(arr2, i);

This code initializes arr2 to [2, 3, 4, 5, undefined]

i thought ++ operator operates before next line and both code will be same.

But, it operates differently. Why does this happen?

add explanation

I thought both for loop operates like this

var i = 0;
var arr2 = [];
check i < 5
console.log(arr2, i);

arr2[i] = arr[i];
i = i + 1;

check i < 5
....skip

is this thought wrong?

what is differance between

'arr2[i] = arr[i++];' and
'arr2[i++] = arr[i];'

Upvotes: 1

Views: 120

Answers (2)

kasoban
kasoban

Reputation: 2167

Edit: removed code snippet because the question code is now fixed

Now, the issue at hand for your question is not the prefix or postfix notation, but the fact that the expression of the for loop (specifically the arr2[i] = arr[i++] part) will be executed AFTER the loop cycle is completed. This is why your arr2 array is empty in the first iteration, the indexes are all fine but the assignment has just not happened yet.

The complete for syntax as decribed per Mozilla Developer Network is

for ([initialization]; [condition]; [final-expression])
    statement

with the note for [final-expression]:

An expression to be evaluated at the end of each loop iteration. This occurs before the next evaluation of condition. Generally used to update or increment the counter variable.

To expand on your edited question regarding postfix position difference:

i++ will increment i after its next usage. So, assuming a starting value of i=3 means

arr[i] = arr2[i++] --> arr[3] = arr2[3]

and after that is done i is incremented to 4.

In the other way around i is incremented after determining the arr index, so it already has the incremented value when accessing arr2:

arr[i++] = arr2[i] --> arr[3] = arr2[4]

Upvotes: 2

GOTO 0
GOTO 0

Reputation: 47682

If your intent is to copy arr to arr2, there is no need to iterate over each element. Use slice instead:

var arr = [1, 2, 3, 4, 5];

var arr2 = arr.slice();

Upvotes: -1

Related Questions