I always wondered why we use i in Javascript loops couldn't it be any letter? Just wondering why i seems to be the default one.
for (i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}
I always wondered why we use i in Javascript loops couldn't it be any letter? Just wondering why i seems to be the default one.
for (i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}
There are several variable names that are commonly used in loops:
i is probably the most common since it is only one letter and stands for index.
Your code example should define i like this:
for (let i = 0; i < 5; i++) {
text += `The number is ${i}<br>`;
}
Otherwise it is created on the global scope and that just shouldn't happen.
It's an historical artifact from Fortran, which originally made all variables beginning with i, j, ... n implicitly integer (a convention common to mathematical notation as well, at least for i, j and k), and all other names (a-h, o-z) implicitly real. A lot of code ended up borrowing that convention for throwaway integer variable names, using i for the outer loop, j for the next loop in, and so on.
There's no real rhyme or reason to it (aside from i often being used to mean "index" or "integer"), just a common convention. The convention makes it okay to use i (because we all know what you mean); if you didn't use it, you'd probably want a spelled out name, not some other random single letter name that fails to describe what the variable represents.
It's no reason whatsoever - it's just a naming convention that signifies an index (letter i) or loop counter (iteration). You can use whichever variable name you like:
let text = "";
for (anExtremelyLongCounterName = 0; anExtremelyLongCounterName < 5; anExtremelyLongCounterName++) {
text += "The number is " + anExtremelyLongCounterName + "<br>";
}
document.write(text);
Also note that currently your code is implicitly declaring a global variable. Use let or var to make it better.
You could use any letter or any valid variable name for that matter. When I first learned to program my teacher instructed us to use lcv for loop control variable.
However to answer your original question, i is very often used to control loop iteration in most languages that have a similar for loop construct, and I believe it derives from the first letter of the word increment. Then by convention if you have nested loops the next loop control variable will be letters following i in the alphabet: j, then k, etc.
As I mentioned before, though, it can be any variable name you choose. But who wants to do that much typing for a throwaway variable?