In this article, I'm sharing what I learned with simple examples. This might be helpful for anyone who is just starting with JavaScript.
While Loop
A while loop is used when we want to execute a block of code repeatedly as long as a given condition is true.
Let's start with a simple example.
let count = 0 ;
while ( count < 5 ) { console . log ( 1 ) ; count = count + 1 ; }
Enter fullscreen mode
Exit fullscreen mode
output: 1 1 1 1 1
Enter fullscreen mode
Exit fullscreen mode
Here, the loop starts with count = 0.
It checks whether count < 5.
If the condition is true, it prints 1.
Then the count increases by 1.
This continues until the condition becomes false.
Decrementing a Value
We can also use a while loop to decrease a value.
let count = 4 ;
while ( count >= 0 ) { console .β¦