Understanding ‘for’ Loop in JavaScript
Navigating JavaScript's 'for' Loop: A Comprehensive Guide to Iteration
When going through the journey of learning JavaScript, you will surely come across the ‘for’ loop. The ‘for’ loop is the most used method of looping in JavaScript; hence, it is very essential for every programmer to gain mastery of it in order to effectively implement your code when trying to carry out an iteration.
Prerequisites
- A basic understanding of JavaScript
What Exactly Is A ‘for’ Loop?
A ‘for’ loop is simply a block of code that runs repeatedly in order to carry out a particular task until a specified condition is met. Sounds simple, right? Oh yes, it is. The majority of programming languages use a ‘for’ loop, but since we’re talking about JavaScript, let’s delve a little deeper into how the 'for' loop is used, particularly in JavaScript, and in what particular cases you’ll need to bring it into your code in order to achieve your desired output.
When Is It Used?
There are different case scenarios where a ‘for' loop can be used. For better understanding, let me give you this real-world scenario to make it relatable to you. Let’s say you’re trying to get the names of students from a class. A ‘for’ loop can be used to iterate over the list of students and return an output of student names. Typically in JavaScript, it is used to loop through arrays, which helps to keep your code DRY (Don’t Repeat Yourself), which is a standard amongst developers, and it also maintains simplicity and readability of code.
'for' loop Syntax in JavaScript
'for' loop in JavaScript takes this structure:
for (initialization; condition; update) {
// code to be repeated
}
Now let’s get to understand each section of the syntax above
Initialization: This is the stage where you carry out variable initialization; it determines the beginning point of your loop. It simply sets the value of a variable when the loop starts. When running a loop, it typically starts from zero (0) because arrays are zero-based, i.e., index zero means the first item in an array.
Condition: This part of the code determines the condition necessary for the execution of the loop. As long as the condition is true, the code runs, and as soon as the condition becomes false, the loop ends.
Update: This part of the code determines what action takes place each time a loop is executed.
Now let’s dive into a few examples to give you more understanding and expand on what I’ve explained so far. We’ll start with a very simple example and then build up to more complex ones.
'for' loop Example
These are a few scenarios where the ‘for’ loop can be used.
When the number of iterations to be made is known,
Take a look at the code below:
for (let i = 0; i < 10; i++) { console.log(i); } //The output will be 0,1,2,3,4,5,6,7,8,9
Here’s what will happen when this code runs. The variable ‘i’ is initialized to the value 0 (zero). The value 0 is the beginning of the loop, and numerically, 0 is less than 10, so the loop will run successively for 10 times, and immediately ‘i’ becomes 10. The program recognizes that 10 isn’t less than 10, but they are both equal, so at that point the loop stops immediately.
i++ simply means incrementing i by one at every point the loop runs. If we were to say i+2, the loop would increment i by 2 every time it ran. So the output of the code will be 0, 2, 4, 6, 8.
When the length of the array is dynamic:
const dynamicArray = [1, 2, 3, 4, 5,6,7,8,9]; for (let i = 0; i < dynamicArray.length; i++) { console.log(dynamicArray[i]); }
In this case, the length of the array wasn’t known before runtime, but the ‘for’ loop makes it possible for the loop to iterate over each element of the array.
Dynamic condition-based iteration:
for (let i = 0; i < 10 ; i++) { if (i === 5) { break; } console.log(i); }
Using the ‘for’ loop this way makes it easy to control what will lead to the stop of iterations if the condition is met along the line while the loop is running. The code above simply breaks the iterations as soon as the loop gets to 5. Take this, for instance. You ask someone to go through some files (maybe 10 files), and you tell the person to stop as soon as they see a particular file bearing a specific name. At first, the person wouldn't know how many files they would go through before they got to that specific file, but once they got to that file, they stopped searching. That’s exactly how condition-based iteration works while using the ‘for’ loop.
You can also do something else called ‘continue’ in JavaScript. Continue does the opposite of break. In the case of continue, once the loop gets to 5, it jumps over it and prints out the other values.
Check out the code below:
for (let i = 0; i < 10; i++) { if (i === 5) { continue; } console.log(i); }
This will print out 0 to 4, jump over 5, then print out 6 to 9 on the console.
Conclusion
The use of the ‘for’ loop is crucial and cannot be overemphasized when coding in JavaScript; it doesn’t only make your code readable, but it also makes it efficient. You’ll definitely encounter a lot of scenarios where it’ll be used on your projects, so ensure you practice its use cases and gain mastery of them.
Thank you so much for stopping by! I hope this was insightful. Don’t forget to share your thoughts with me by leaving a comment below.
Happy Coding!