Search code examples
javascriptecmascript-6for-of-loop

How does for..of loop get values from Array


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?


Solution

  • 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)
    })