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)