DEV Community

Cover image for How Loops Work in JavaScript😭🤔
Sai gowtham
Sai gowtham

Posted on • Edited on

How Loops Work in JavaScript😭🤔

Have you Ever Confused about Using a Different kind of loops in JavaScript

No Problem Today we clearing the confusion

Let's Print 1-100 numbers using a different Kind of loops.

First We Print 100 numbers using For Loop.

for(let i=0; i<=100;i=i+1){
  console.log(i)
}
Enter fullscreen mode Exit fullscreen mode

Let's talk about what is the use of above code.

for loop takes three optional expressions

1) Initialization: we are initializing our value - (let i=0);

2) Condition: On which condition iteration if the condition is true
then the loop continues otherwise loop stop running.(i<=100);

3) Final expression: How loop increments or decrements on each iteration (i=i+1)

Inside the for loop, we are logging the value on each iteration.

Without for loop, we need to write 100 numbers manually 1 by 1 using
for loop, it only takes 2 lines of code.

Lets Solve the same problem using While loop.

let n=1
while(n<=100){
 console.log(n);
 n=n+1;
}
Enter fullscreen mode Exit fullscreen mode

while loop runs only if something is true.Otherwise it doesn't enters
inside the loop.

  • We first initialized a value to the variable n with 1.

  • while loop only takes a single expression which is a condition(n<=100).

  • It only runs up to n value is equal to the 100.

  • On line 2 we are incrementing n on each iteration.

Now let's solve the same problem using if and while loop.

let enter=true;
let n=1;
if(enter){
while(n<=100){
 console.log(n);
 n=n+1;
}
}
Enter fullscreen mode Exit fullscreen mode

if condition also runs on the basis of the truthy values.

  • In our above problem enter is true so it enters the loop.
  • Inside the if condition we placed a while loop.

How if condition works in daily life. In our day to day life,
we are making decisions like if time is 9 am I need to eat breakfast.
if time is 12 am I need to eat lunch.

Have you thinking about if-else. if time is 9 am I need to eat breakfast
else I need to do some other things(brush, bathing,etc..).

Hope you guys love these
👍👍👍👍👍👍👍👍

Check out my other Interesting posts

Top comments (0)