I am new to javascript and I keep seeing the following code (or variations of this) used for looping through arrays.
I have made an example array called fruits to explain
var fruits = ["Apple","Pear","Peach"]
for(var i = 0, j = fruits.length; i < j; i++) {
console.log(fruits[i])
}
I am trying to understand exactly what is happening here.
i = 0
— This creates a variable. It will be used to select the first object in the array'fruits'
j = fruits.length
- This determines how many objects there are in the arrayfruits
i < j;
— I think this evaluates if 0 is less than the number of objects in the array. I'm not sure why this would be done though, as 0 should always be less than the number of objects in the array.i++
- this increments through all the objects in the array running the function, but how does it know when to stop, or do thisj
number of times?
Furthermore, I have seen a much simpler method used to do this:
for(var i in fruits) {
console.log(fruits[i])
}
How does this differ from the above and what is the best one to use? Is one faster or better recommended for web development?