Loops or Iterators allow you to perform an operation for a number of times. If you want to run a code over and over again for a number of times or even infinitely, you’ll be using loops.
Remember how Dr Strange bargained with Dormammu? He bound Dormammu in an infinite time loop to save the world right? So that’s how loop works, you repeat a task over and over again. (So the creator of time stone used computer and coding science behind it to add features? 🤔🤔🤔)
(Source: Google)
There are three types of loops:
for loop
while loop
do-while loop
In this article we will be discussing about for
loop.
Syntax, Example, Explanation:
Syntax:
for (initialization; condition; afterThought) {
// code
}
Example:
for (let i = 0; i < 10; i++) {
console.log(i);
}
// output: 0 1 2 3 4 5 6 7 8 9
Here
let i = 0
isinitialization
of the variable and setting it’s initial value0
.i < 10
is thecondition
orlimit
as I mentioned, you use loop to run a code a number of times,initialization
determines, how many times you’ll repeat the code.i++
is theafterThought
better putincrement
. It increases the value of the variable until it reaches meets the limiti < 10
.i
is known as index
Explanation:
Here we initiated a variable and set value 0, let i = 0
and set a limit for i, with i < 10
. It says i will always be less than 10.
So i = 0; i < 10;
says the value of i can be anywhere from 0 to 9 (below 10).
Then we introduced increment i++
which is the short form of i += 1
or i = i+1
which suggests that the value of i
will be increased by 1 with every iteration.
This is how loop works:
i ≤ 10:
If we set i≤10
instead of i<10
then i
will be increased till 10 and not 9
for (let i = 0; i <= 10; i++) {
console.log(i);
}
// output: 0 1 2 3 4 5 6 7 8 9 10
Not starting form 0:
NOTE: Starting a value from 0 and setting it up to a certain value was just for example. If you want to start from any other value, you can do it
for (let i = m; i < n; i++) {
console.log(i);
}
//example
for (let i = 10; i < 20; i++) {
console.log(i);
}
// output: 10 11 12 13 14 15 16 17 18 19
Say sorry to your Girlfriend 100times:
Imagine you have a girlfriend (Yeah just imagine coz I know you don’t have any 😏) and for no particular reason she’s mad at you and the only way she’ll forgive you is if you send her “I am sorry dear” for 100 times.
But since you are an Engineer you’ll not write the message 100 times formally but use your Coding skills to do it without working so hard.
How you ask? 🤔 Well this is how:
for (let i = 0; i < 100; i++) {
console.log(`${i + 1}. I am sorry, dear!`);
}
// output:
/*
1. I am sorry, dear!
2. I am sorry, dear!
3. I am sorry, dear!
4. I am sorry, dear!
5. I am sorry, dear!
6. I am sorry, dear!
.
.
.
100. I am sorry, dear!
*/
This is how it works:
With loop you can not only print the index number but also print anything. For example string in this scenario.
NOTE: Since I started from 0 I added 1 with the variablei+1
to go from 1 to 100 instead of 0 to 99.
Your task: Use i = 1; i <= 100;
this condition and see If the result stays same (Tip: avoid i+1
and use i
in this case.)
Increment 2 instead of 1.
Till now we have been incrementing 1 value at a time using i++. But we can increment 2 or
as many values as we want.
for (let i = 0; i < 20; i += 2) {
console.log(i);
}
//output: 0 2 4 6 8 10 12 14 16 18
As you can observe, this time instead of printing every elements in the range (0 to 19) the loop is printing every other element. In other words it’s skipping an element.
Ask why? Because of i += 2
Which indicates instead of 1 increment the value of i
by 2.
This is how it works:
Using for loop on String:
You can use for loop on String to print characters separately .
let name = "Tony Stark";
for (let i = 0; i < name.length; i++) {
console.log(name[i]);
}
// output: T o n y S t a r k
Here name.length
is the length of the string which is 10
. The loop iterates over the string and each time it prints a character from the string.
Using for loop on array:
You can use for loop on arrays as well to print array elements and perform many operations.
let a = [1, 2, 3, 4, 5, 6, 7, 8];
for (let i = 0; i < a.length; i++) {
console.log(a[i]);
}
// output: 1 2 3 4 5 6 7 8
Here a.length
is the limit of this for loop. The value of a.length
is 8. The loop iterates over the array and each time it prints an element from the string.
How for loop on array works:
break:
break is a statement that, once executed, terminates an iteration and breaks the entire loop.
In other words, if break statement is executed then the loop is broken. Rest of the iterations are not executed.
Here’s an example:
let array1 = ["a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a10"];
for (let i = 0; i < array1.length; i++) {
if (array1[i] == "a5") {
break;
}
console.log(`${array1[i]}`);
}
Here in this example, we ran a for loop on an array and set a condition that if “a5” element appears then break the loop.
And as you can see once “a5” appeared the condition ran and break
statement got executed which broke the loop.
“search for soulmate” journey:
Imagine you are trying to find your soulmate. So you start your “search for soulmate” journey. Here you go and meet people and If you meet someone who is not your soulmate, you politely say “sorry” and move on. And once you successfully find your soul mate, you stop your “search for soulmate” journey. (Remember it’s just an imagination 😁)
let person_list = ["p1", "p2", "p3", "soul mate", "p5", "p6", "p7", "p8", "p9", "p10"];
for (let i = 0; i < person_list.length; i++) {
if (person_list[i] == "soul mate") {
console.log("Yay I found my soulmate 😃");
break;
}
console.log(`Sorry ${person_list[i]} 😔`);
}
As you can see Once the condition met, the loop broke. But before that console.log("Yay I found my soulmate 😃");
was printed. AS I wrote it before break
statement.
This is how it works:
Continue:
Continue is a statement that terminates the execution of the statements in the current iteration of the current loop, and continues execution of the loop with the next iteration.
In simple terms in a for
loop, if the continue
statement is used with a condition, when the condition is met, that particular iteration will be skipped, and the loop will move to the next iteration.
here’s an example:
for (let i = 0; i < 10; i++) {
if (i == 5) {
continue;
}
console.log(i);
}
//output: 0 1 2 3 4 6 7 8 9
Here:
I printed a series of numbers from 0 to 9
I set a condition if the number is 5 then continue.
In the result every other number got printed except 5.
As you can observe when the value of i
increased to 5, it got skipped from being printed.
Here is a practical example of how continue can be used in for loop and array.
Give everyone Water bottle except your EX
Let’s assume you are a volunteer in college function. And your job is to give water bottle to everyone in audience. While giving water bottle you discover that your EX is there in the audience. So you decide to simply ignore him / her and continue giving the water bottle to everyone else
let audience = ["a1", "a2", "a3", "EX", "a5", "a6", "a7", "a8", "a9", "a10"];
for (let i = 0; i < audience.length; i++) {
if (audience[i] == "EX") {
console.log("Huh!!! 😤");
continue;
}
console.log(`Take the water😊 ${audience[i]}`);
}
// output:
/*
Take the water😊 a1
Take the water😊 a2
Take the water😊 a3
Huh!!! 😤
.
.
.
Take the water😊 a10
*/
As you can see, console.log(
Take the water😊 ${audience[i]});
got skipped once audience[i] == "EX"
condition matched and console.log("Huh!!! 😤");
got printed because the line was written before the continue
statement.
Conclusion
For loop is widely used in not only JS but in programming as a whole. It can be used to iterate over arrays and strings, generate sequence of numbers, repeat an operation over and over again and many more. In this article we discussed about the basic syntax of for loop, how for loop can be used on array and how to break or continue a loop.
Your task is to read the article, practice everything and for further information visit MDN.
Happy Coding 🚀.
(Cover Image source: google)
(Display Image source: google)