Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

What is i in JavaScript

The Curious Case of 'i' in JavaScript

If you're new to the world of programming, you might look at a piece of JavaScript code and wonder, "What on earth is this 'i' doing here?" Don't worry, you aren't alone. In this article, we'll unravel the mystery of 'i' in JavaScript and get comfortable with this seemingly cryptic character.

The 'i' in Basic Terms

In JavaScript, 'i' is typically used as a variable in loops. It's like a counter that keeps track of how many times the loop has run. Imagine you're at a track field running laps. Each time you complete a lap, you add one to your lap counter. That lap counter is like 'i' in JavaScript.

Let's look at a code example:

for (let i = 0; i < 5; i++) {

In this basic for loop, 'i' starts at 0 (let i = 0). The loop will keep running as long as 'i' is less than 5 (i < 5). After each loop, 'i' increases by 1 (i++).

But Why 'i'?

You might be wondering why we use 'i' specifically. Why not 'x' or 'y' or 'loopCounter'? Well, 'i' stands for 'index'. In computer programming, an index refers to a position within an ordered list, like an array. However, you can actually use any variable name you like. 'i' is just a convention that many programmers follow.

'i' in Action: Working with Arrays

Here's an example where 'i' is used to access elements in an array:

let fruits = ["apple", "banana", "cherry"];
for (let i = 0; i < fruits.length; i++) {

In this loop, 'i' starts at 0 and increases by 1 each time until it's no longer less than the length of the fruits array. 'i' is used to access each element in the array, printing every fruit to the console.

'i' Beyond the Basics: Nested Loops

Sometimes, you'll see 'i' used in more complex ways, like in nested loops. A nested loop is like a race within a race. Imagine you're running laps again, but this time, after each lap, you have to do ten jumping jacks. You'd need a second counter for your jumping jacks.

Here's a code example of nested loops:

for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 10; j++) {
    console.log("i: " + i + ", j: " + j);

In this example, 'i' is our lap counter and 'j' is our jumping jack counter. Notice how we used 'j' for the inner loop. This is another convention - 'i', 'j', and 'k' are often used for nested loops.

Conclusion: The Power of 'i'

So there you have it - the secret of 'i' in JavaScript. It might seem insignificant, just a single letter among lines of code. But much like the pawn in a game of chess, it plays a vital role in the grand scheme of things. It's the silent marker, the tireless counter, the unassuming navigator guiding us through loops and arrays.

Remember, 'i' is nothing to be afraid of. It's just a tool in your JavaScript toolbox. So the next time you see 'i' in a piece of code, give a nod of recognition to our humble friend. You now know its secret. Happy coding!