Eug
Eug

Reputation: 185

For Loop iteration < vs <= JavaScript fundamentals

I'm having trouble figuring out why this block of code is giving me

TypeError: Cannot read property '0' of undefined

function fromListToObject(array) {
  // make new empty object to store key:value in
  var obj = {};
  // loop over the given array
  for (var i = 0; i <= arr.length; i++){
    //every iteration keys gets stored with new key
    var keys = arr[i][0];
    // same here
    var values = arr[i][1];
    //pushing new key:value into obj
    obj[keys] = values;
  }
  return obj;
}
var arr= [['1', 'One'], ['2', 'Two'], ['3', 'Three'], ['4', 'Four'], ['5', '5']];
var result = fromListToObject(arr);

console.log(result);

What I've tried: When I run the for loop inside the fromListToObject() function with just i < arr.length it works. I've tried looking for answers but I might be asking in the wrong way. Shouldn't the loop work with the "=" operator too?

Upvotes: 1

Views: 52

Answers (1)

Dekel
Dekel

Reputation: 62626

If you have an array with 10 elements, and you start counting with 1 - the last element will be placed at the 10th place.

However - if you start your count with 0 (which is the way arrays work), the last position will be length - 1 (which is 9 in this example).

In your example - the for loop starts with 0 and should count to the last element in your array, which is placed in the length - 1 position.
That place is also <length (because when we get to =length - this is "out of the array" - you are trying to access an element in a place that doesn't exist):

for (var i = 0; i < arr.length; i++) {
    ...
}

Note that exactly the same way, you can do:

for (var i = 1; i <= arr.length; i++) {
    // Note that here you would want to access the elements
    // in the array using arr[i-1]
    ...
}

But this is less common.

Another option you have is to use the forEach method of the array:

arr.forEach(function(element) {
    ...
});

Upvotes: 5

Related Questions