Repeating Actions with Loops
Sometimes In our program we want to repeat some action multiple times.
for-ex I want to console.log("Hello world") 4 times.
The hard way to do that would be to wrote code again and again. this code
works but the idea of programming is to make things easy not hard.
cosole.log("Hello world")
cosole.log("Hello world")
cosole.log("Hello world")
cosole.log("Hello world")
so In J.S loops comes.
Defination of loop
To Repeate a task we can use loops
There are multiple loops in J.S for repeating task multiple time.
- For loop
- While loop
For loop
For loop take 3 statement
- First statement is used for initialization.we initilize a value by defining a variable and
iniatilizing the value to Zero(0).
for(let i = 0)
- Second statement is condition it helps the loop.
In deciding when to to stop the loop. whenever this condition return false it will stop the loop.
for(let i=0 ; i<5) when i is less than 5 loop keeps going otherwise stop
- Third statement expalin what to do after every itration.
for(let i=0; i<5 ;i = i+1 or (i++)){
console.log("Hello world")
}
Output - 5 Hello world
Hello world Printed % times
- after every itration the value of i should go up by 1
How the value of i is changing after every itration??
for(let i=0; i<5 ;i++){
console.log(i);
}
0 -(starts with 0(zero) that is the job of first statement)
1
2
3
4
While loop
- While loop takes a condition and when the condition is true it execute the body.
- When the condition is false the loop breaks.
let i=0
while(i<10){
if( i% 2 ==0){
console.log(i)
}
}
Output
0
2
4
6
8
When to use which loop ?