What if you could tell the computer to do boring tasks for you, over and over, without lifting a finger?
Why While loop in Javascript? - Purpose & Use Cases
Imagine you want to count from 1 to 10 and write each number down one by one by hand.
Doing this for just 10 numbers is okay, but what if you need to count to 100 or 1000?
Writing each number manually takes a lot of time and is boring.
It's easy to make mistakes, like skipping a number or writing the wrong one.
Doing repetitive tasks by hand is slow and frustrating.
A while loop lets the computer repeat a task automatically as long as a condition is true.
This means you write the instructions once, and the computer does the counting for you without errors.
console.log(1); console.log(2); console.log(3); // ... keep writing each number
let i = 1; while (i <= 10) { console.log(i); i++; }
With while loops, you can easily repeat tasks many times without extra work or mistakes.
Imagine a game where you want to keep asking the player if they want to play again until they say no.
A while loop can keep asking the question automatically until the player decides to stop.
Manual repetition is slow and error-prone.
While loops automate repeated tasks based on a condition.
This saves time and reduces mistakes in your code.