DEV Community

Cover image for Enough JavaScript to get you Started : #8 Loops
Adarsh Pandya
Adarsh Pandya

Posted on

Enough JavaScript to get you Started : #8 Loops

how to not write your code πŸŽƒ

πŸ‘‰ okay ! this is going to be a funny story , when i started programming someone challenged me to print 1 to 20 on console. i laughed because it was too easy

πŸ‘‰ completely out of logic i started typing console.log() for 20 times and yelled i'm done

πŸ‘‰ this is how i wrote progam

console.log(1)
console.log(2)
console.log(3)
console.log(4)
console.log(5)
console.log(6)
console.log(7)
console.log(8)
console.log(9)
console.log(10)
console.log(11)
console.log(12)
console.log(13)
console.log(14)
console.log(15)
console.log(16)
console.log(17)
console.log(18)
console.log(19)
console.log(20)
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ this looks stupid right? πŸ˜‚ there's a principle in coding world known as DRY (don't repeat your self) and what i did was exact opposite of it πŸ˜‚

Concept of Loops came in picture

πŸ‘‰ After i showed code to my colleagues they said there's something known as loop

πŸ‘‰ Loops are condition based iterative blocks which repeats themselves n number of time based on condition

Types of loop

  1. For loop (we'll be learning this βœ…)
  2. While Loop
  3. Do...while Loop

Logical flow of Loops

Artboard – 6.png

For Loop Syntax

for(intial value;exit condition;update statement)
{
    // loop body | block
}
Enter fullscreen mode Exit fullscreen mode

Refactoring our old code

for(var i=1;i<20;i++)
{
      console.log(i);
}
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ This syntax makes much more sense then previous one , and follows DRY principle

πŸ‘‰ meaning of this code : "start from 1 , increase by 1 every time and exit from loop when it becomes greather than 20"

Let me know in comment section if you have any doubt or feedback. it's always worth to give time to thriving developer community :)

Keep Coding ❀

Hey , Let' ConnectπŸ‘‹

Twitter / Github

Top comments (0)