DEV Community

Cover image for For Loop – JavaScript Series – Part 14
Muhammad Ali (Nerdjfpb)
Muhammad Ali (Nerdjfpb)

Posted on • Originally published at blog.nerdjfpb.com

For Loop – JavaScript Series – Part 14

In last lesson we learn about the while loop, but there is a another loop which is really popular and people use this. So we’re going to learn it too.

Suppose we are going to print 1 to 10 on the console. But how we can do it ? We can do it easily

console.log(1)
console.log(2)
...
console.log(9)
console.log(10)
Enter fullscreen mode Exit fullscreen mode

But this is not a good way to do it. Currently we can do it because it’s only ten times. But suppose we need to print 1 – 100. How to do it ?

This is where we use loops. We’re going to use For loop today!

For is easy. Just remember what we learned in our last tutorial. For loop syntax is –

for (initial, condition, increment/decrement/rulesBreaking) {
  // code block to be executed
}
Enter fullscreen mode Exit fullscreen mode

Let’s write some real codes now. If we wants to print 1 – 10 then we are going to store the values in variable and we are going to start from 1. We can directly do this part in for first part!

Now we are going to start our for. For then first part will be initial of the number, then condition for breaking the loop and final part will be how we can break the loop.

for (var number = 1; number < 11; number++) {
  // code block to be executed
  console.log('Printed number - ', number)
}
Enter fullscreen mode Exit fullscreen mode

Alt Text

By the way did you notice that I used number++ ? What that’s mean ?
number++ = (number = number + 1) same thing. number++ is just a shortcut way to write it.

See the result in browser.

Alt Text

Do you understand the For loop ?

You can see the graphical version here

Source Codes - { Check commits }

GitHub logo nerdjfpb / javaScript-Series

A tutorial for JavaScript Beginners

javaScript-Series

A tutorial for Absolute Beginners of JavaScript.

You can find the total pdf in - Here

You can check the commits to find the part by part codes.

Blogs

Day 1
  • Day 1 - What is JavaScript?
Day 2
  • Day 2 - JavaScript Types?
Day 3
  • Day 3 - Javascript Types Cont.
Day 4
  • Day 4 - Javascript Types Cont.
Day 5
  • Day 5 - Javascript Comparisons
Day 6
  • Day 6 - Javascript Variables
Day 7
  • Day 7 - More About Variables
Day 8
  • Day 8 - Conditional Statement
Day 9
  • Day 9 - More Conditional Statement
Day 10
Day 11
Day 12
Day 13
Day 14
Day 15
Day 16
Day 17

Originally it published on nerdjfpbblog. You can connect with me in twitter or linkedin!

Top comments (0)