0

I have this piece of code,

let array = ["cj1rdd9fc00013f69ccln57g0", "cj1rdda8x00023f69g9281ay8"];
for (let [key, value] of array) {
  console.log(key, value);
}
I expect, 0 cj1rdd9fc00013f69ccln57g0 and 1 cj1rdda8x00023f69g9281ay8 as the output. what am I missing here? How can I get the desired output?

8
  • What are you getting? Some errors or current results would help please. Commented Apr 21, 2017 at 5:18
  • @ChrisWatts OP expects key to be indexes and value to be element of array Commented Apr 21, 2017 at 5:19
  • Refer developer.mozilla.org/en/docs/Web/JavaScript/Reference/… Commented Apr 21, 2017 at 5:20
  • I found that adding array.entries() in the loop body makes it work fine. Commented Apr 21, 2017 at 5:22
  • @AkhileshBhushan, see my answer for in-depth explanation. Commented Apr 21, 2017 at 5:52

6 Answers 6

4

Here is a bit of under the hood explanation.

for..of loop works on iterables. On each iteration it calls iterator.next().value to get values. Standard Array implementation has two kinds of iterators - the one that returns only values and the other that returns [key, value] pairs. If you need to get the second type of iterator, use array.entries().

let array = ["cj1rdd9fc00013f69ccln57g0", "cj1rdda8x00023f69g9281ay8"];
for (let [key, value] of array.entries()) {
  console.log(key, value);
}

Here is the demo of two types of iterators:

var arr = ['a','b'];
var valueIterator = arr[Symbol.iterator]();
valueIterator.next().value; // returns a
valueIterator.next().value; // returns b

var arr = ['a','b'];
var valueKeyIterator = arr.entries();
valueKeyIterator.next().value; // returns [0, a]
valueKeyIterator.next().value; // returns [1, b]
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much for the explanation :)
2

Let try to understand whats happening here:

As per MDN-Docs, for..of provides value of each iteration to the assignment.

So when you do for(var v of array), v will hold value.

Now when you do let [key, value], you are using something thats called as Destructuring Assignment.

What it does is, for given list of variables, it will assign values at corresponding index value.

So, in let [a,b] = [10, 20], a=10 and b=20.

Coming back to your example,

let [key, value] of array,

is evaluated as let [key, value] = "cj1rdd9fc00013f69ccln57g0", so key holds value at 0th index, a.k.a c and value holds j.


How can I get the desired output

You can use other looping mechanisms like for, array.forEach etc.

There are other mechanisms like .map, .filter, .some, .every, .reduce but they have their own usecase, and can be suggested based on the processing logic.

Array.forEach

let array = ["cj1rdd9fc00013f69ccln57g0", "cj1rdda8x00023f69g9281ay8"];

array.forEach(function(value, index){
  console.log(index, value)
})

4 Comments

Thank you so much for the explanation, well my use case was not that simple, as I had to use async and await in the loop.
I know that. Hence have mentioned other options. Read about them and choose based on your requirement. Also do check their browser compatibility.
I have edited my query with the answer and actual async function, thank you.
@Rajesh, you may find my answer interesting
0

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for...of

The way for of works is each time it will grab just the value, not the index.

let array = ["cj1rdd9fc00013f69ccln57g0", "cj1rdda8x00023f69g9281ay8"];
for (let item of array) {
  console.log(item);
}

If you want to include the index, see this question:

How do you get the loop counter/index using a for-in syntax in JavaScript?

Comments

0

This is a destructuring assignment . This will work for es6 Maps and not for Arrays . For arrays you can just use a for of loop .

1 Comment

I found that adding array.entries() in the loop body makes it work fine.
0

This Code, Console.log Array

 let array = ["cj1rdd9fc00013f69ccln57g0", "cj1rdda8x00023f69g9281ay8"];
 var i,j,tempstring;
    for (i=0,j=array.length; i<j; i++) {
        tempstring = array[i];
        console.log(tempstring);
    }

Comments

-1

If you want to get the value and index of an array in every iteration using some fancy iteration, try this.

let array = ["cj1rdd9fc00013f69ccln57g0", "cj1rdda8x00023f69g9281ay8"];
array.map((value, index) => {
    console.log(index, key);
});

5 Comments

array.map without return statement and assignment is just bad coding. You are wasting a feature. Use .forEach instead
I would respectfully disagree. Even in strong typed languages such as Java, you are not bound to use a value returned by a function.
I'm sorry if I was not clear enough. Every function has its own purpose. Array.map maps certain property or mutates value of every iteration. But if you are not returning value, it will return undefined manually. Then you are not assigning it to something, but .map will return an array created internally with undefined values. So you are asking engine to do extra work for no reason. Using .forEach is the right approach here.
It also reduces the readability of code as .map is expected to return something and final value is assigned to something, but you are doing none and adds a gap in understanding.
I agree, now :) Thanks

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.