TIL: Basics of For Loop in JS

How to print 1-1000 in javascript.

Suppose you want to print numbers from 1 -10. We can use

console.log(1)
// 1
console.log(2)
// 1
console.log(3)
// 1
console.log(4)
// 1
console.log(5)
// 1
console.log(6)
// 1
console.log(7)
// 1
console.log(8)
// 1
console.log(9)
// 1
console.log(10)
// 1

Here we are writing every single line. If we write every single line like above then it will be more time consuming and hard code.

Whenever we have to do same thing again and again we can use for loop.

for (initializer; condition; final-expression) {
//some code
}

With the help of for loop we can print 1-10 like below

for (let i = 1; i <= 10; i++){
console.log(i)
}

Here, we are initializing the variable i with the starting value 1, then after we are giving the condition until 10 and last it will add to the i until it fulfills the condition. for-loop-output.png

If we change the the condition, let say i<=100 or i<=1000 it will print till that number also.