Understanding what a piece of java code means

Tell us what’s happening:
So I’ve been able to make it through about half of the java course so far and keep coming across a piece of code that I’ve used many times. I don’t know exactly what it does and I cannot find the lesson that initially explains it.

(let i = 0; i < arr.length; i++)

Before actually answering your question a little nit to pick: the language we are working on here is “JavaScript.” “Java” Is actually another completely different language. Actually that might be a bit bigger than a nit if you were to attempt to google answers and inadvertently got advice for Java rather than JavaScript. :smile:

Anyhow, on to your actual question:

The snippet that you have here, (let i = 0; i < arr.length; i++) is part of a larger unit called a for loop:

for (let i = 0; i < arr.length; i++) {
    // do stuff here
}

in it, you are telling the for loop you want to use the variable i (let i) and starting at 0 (let i = 0) repeat the logic inside the for loop (// do stuff here) as long as i is less than the length of some variable named arr (i < arr.length), incrementing i by one each repetition (i++).

You could just as easily have used the variable “bob”, started at 5, counted down to -100, and decremented by 10’s:

for (let bob = 5; bob > -100; bob -= 10) {
    // do something
}

As a bonus, the variable you declare here is available inside the for loop, appropriately changing value each repetition. That is why you will often see it used as the index to access each element of an array (arr[i]), but use your imagination! There are plenty of other ways you could put i to work.

Another note just cause I can’t leave well enough alone:

The use of i as the counting variable is traditional. I learned “for…next” loops in BASIC back in the 80’s and we were already using i then. Along with i in a for loop, j is traditional for a nested for loop (a loop within a loop):

for (let i = 0; i < 10; i++) {
    for (let j = 0; j < 10; j++) {
        // in here i will go up once for every 10 times j goes up
    }
}

Since these are just traditions, you are in no way bound to use i and j for your loops, but pretty much every coder will expect to be in a loop if they see those variable names being used, so I’d avoid using them in other circumstances.

2 Likes

To add to that, the for loop block is broken into three parts:

for(initializer; condition; incrementer)

The initializer gives an initial value that can used for the loop. The condition tells JavaScript “hey, only do this stuff while this condition is true” and the incrementer is used to perform some action once at the end of every loop. Typically it is used to increment or decrement a counting variable initialized in the initializer.

Just a few things to say further, the initializer can have any number of variables declared in it. I’ve done it with two, though there’s really no limit to how many you want, except common sense and readability:

function binary(binstring) {
    // converts a string of binary to a decimal number
    // 0101 => 3
    let result = 0;
    for(let i = binstring.length - 1, j = 0; i >= 0, j < binstring.length; i--, j++) {
        result += parseInt(binstring[i]) * (2 ** j);
    }
    return result;
}

To get the above code to work, I needed one counter to go up, and another to go down. So I was able to initialize two variables, and use both of them in the incrementer.

In fact, there’s no rule stating the incrementer even has to increment, it’s just a statement that gets run every time the loop progresses:

for(let j = 'cat', k = ''; true; console.log(k)) {
    k += j;
    if(k === 'catcatcat') {
        break;
    }
}

This absurd example will log:

cat
catcat

And break when it gets to catcatcat, so it won’t ever print that.

Not that I’d advise doing this, by the way, just showing an example of how it works.

Finally, all three blocks are optional, but the semicolons are not.

for(;;) {}

The above is an infinite loop that will never break. If you don’t need one or more of the blocks, you don’t have to use it.

In the end go to the MDN for more information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for

1 Like

This lesson Basic JavaScript: Iterate with JavaScript For Loops explains it.

1 Like