Enough JavaScript to get you Started : #8 Loops

Subscribe to my newsletter and never miss my upcoming articles

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)

πŸ‘‰ 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
}

Refactoring our old code

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

πŸ‘‰ 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

Comments (2)

Edidiong Asikpo's photo

I love how you started with the mistakes you made when you started learning how to code. I can totally relate because I made similar mistakes as well.

The truth is, the more you code, the more you realize that there are better and faster ways of solving problems.

I really enjoyed reading this article. Adarsh pandya

Adarsh pandya's photo

Hey Edidiong Asikpo ,I'm both touched and overwhelmed by your response towards my work. Thank you so very much for making my day.

and yes mistakes are important. cause this is responsibility of devs to make beginners realize that "it's not always sunshine and rainbows" even though you really enjoy it. the best you can do is to accept mistakes and make it fuel for your next learnings :)