For Loop in JavaScript - Interview Question...

for loop


For 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


        <script>

            console.log(1)
            console.log(2)
            ...
            console.log(9)
            console.log(10)

        </script>


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
            }


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.


                         // initialize, conditin , increment
            for (var number = 1; number < 11; number++) {
            // code block to be executed
            console.log('Printed number - ', number)
            }