Programmers are known to be "lazy" which I do not agree. We like to automate things, and will automate things. Even if the job takes 5 minutes to do, most of us would feel it's necessary to spend countless ours to automate that process.
What are for loops?
Let's imagine we are delivering mail, full truck load. We have 100 packets to deliver, but some reason after each delivery, we need someone to tell us to deliver the next packet. It makes no sense, right? We know that there are 100 packets to be delivered, so we should deliver them one by one to the desired address without our boss telling us to deliver the next box.
-- Hey boss, I just delivered the packet
++ great, now, deliver the next one
-- Okay.
++ ...
-- Hey boss, I just delivered the packet
++ great, now, deliver the next one
-- Okay.
++ ...
You got the idea.
For Loop
is knowing your responsibility and repeating the needed action it as many times as needed. You have 100 mails to deliver? You will deliver 100 mails without someone telling you it second time.
Lets write that as a code.
const numOfMails = 100;
for (let mailsDelivered = 0; mailsDelivered <= numOfMails; mailsDelivered++) {
console.log('mail delivered');
}
Don't worry, the real syntax is way shorter. Same code:
const numOfMails = 100;
for (let i = 0; i <= numOfMails; i++) {
console.log('mail delivered');
}
Try to read the code by your-self and I will explain it word by word.
- We initialize our loop with
for
keyword. let i = 0;
this is our starting point. Mostfor loops
uselet i = 0
---i
is short for index. What we are basically saying is, start the index from 0. You can start it from any number.- While
i
is less than or equal to<=
numOfMails -- run the code between{ }
- After each complete iteration, increase the
i
by one, written like thisi++
for (let i = 0; i <= numOfMails; i++) {}
another example
const num = 5;
for (let i = 0; i < num; i++) {
console.log(i);
}
Can you guess what will be printed on the console? Give it a try.
0
1
2
3
4
The index, i
starts from 0, and runs total of 5 times, and stops when i
is equal to 4. If we used <=
instead of <
, the final number would be 5, the loop would stop once the i
is equal to 5.
i--
to count down, or increase the i
by two like this i+=2
. You can use any number or math equation.
You can use use What would this code do?
for (let i = 0; i <= 100; i += 2) {
console.log(i);
}
and this one? This one can be little trick, but I'm sure you can get it.
for (let i = 99; i > 0; i -= 2) {
console.log(i);
}
On the first one, i
starts from 0, logs the current value of i
and increases it by 2
after each loop. So, it would print 0 2 4 6 8....
. Even numbers between 0 and 100;
Second one, i
starts from 99, and while i
is larger than 0, it will print the current i
and lower it by 2 after each loop. So, it would print 99, 97, 95...
. All the odd numbers between 100 to 0.