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
- For loop (we'll be learning this β )
- While Loop
- Do...while Loop
Logical flow of Loops
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 β€
Top comments (0)