-2

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.

  1. i = 0 — This creates a variable. It will be used to select the first object in the array 'fruits'
  2. j = fruits.length - This determines how many objects there are in the array fruits
  3. 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.
  4. i++ - this increments through all the objects in the array running the function, but how does it know when to stop, or do this j 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?

Adam Scot
  • 1,371
  • 4
  • 21
  • 41
  • 6
    I think you need to read a tutorial on JavaScript control statements. SO is not a tutoring service on language basics. – Barmar May 25 '21 at 18:19
  • 2
    `but how does it know when to stop` - because it will stop when `i < j` is not longer true – slebetman May 25 '21 at 18:20
  • 2
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration – derpirscher May 25 '21 at 18:20
  • 2
    What you're missing is that `i < j` is tested each time through the loop. So while it always be true the first time (unless the array is empty), it won't be true after you loop through all the elements. – Barmar May 25 '21 at 18:23
  • 1
    Regarding your last question, see https://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea?lq=1 – Barmar May 25 '21 at 18:23

1 Answers1

1

You are almost on the right path bur a few corrections

i = 0 — This creates empty variable with 0 in it. This will act as a counter to compare with the next steps to come

j = fruits.length - This determines how much is the length of array store under the name fruits

i < j; — this is where the 2 values are checked if i ends up begin greater than j then the loop stops else it continues... this will go on until the i is less than j

i++ - if i is found to be smaller than j we add + 1 to the value of i and run the loop again.. this step is more of responsible / important to ensure we stop the loop at correct position..

Nishant S Vispute
  • 713
  • 1
  • 7
  • 21