Hi all! Today I am going to write about a part of loops which is very interesting. So today we talk about Entry check and Exit check in Loops.
What Is a Loop?
A loop is a structure that repeats a block of code as long as a condition is true.
But when the condition is checked, before or after the loop body, makes the difference between entry check and exit check.
Entry Check Loop (Condition is checked before the loop runs):
-> The loop only runs if the condition is true.
-> If the condition is false at the beginning, the loop won’t run at all.
-> Also called pre-test loop.
Examples:
- for loop
- while loop
a) while loop (entry check)
let i = 0;
while (i < 3) {
console.log(i);
i++;
}
Output:
0
1
2
If the condition is false:
let i = 5;
while (i < 3) {
console.log(i); // This will NOT run
i++;
}
Output:
(nothing happens, because the condition is false at start)
Real-Life Example (Entry Check):
Imagine you’re entering a movie theater. The security guard checks your ticket before you go in.
✅ If you have a ticket → you can enter.
❌ If you don’t → you can’t enter at all.
Same way, if the condition fails at the beginning, the loop won’t start.
Exit Check Loop (Condition is checked after the loop runs):
-> The loop body always runs once, even if the condition is false.
-> Condition is checked after one execution.
-> Also called post-test loop.
Example:
- do...while loop
do...while loop
let i = 0;
do {
console.log(i);
i++;
} while (i < 3);
Output:
0
1
2
Even if the condition is false at the start, the loop runs once:
let i = 5;
do {
console.log(i); // This still runs once
i++;
} while (i < 3);
Output:
5
Real-Life Example (Exit Check):
Think of a restaurant where you can eat first and pay after.
✅ You eat → then they check if you can pay.
If you can’t pay, they stop you from eating again.
But you already ate once!
This is like an exit-check loop: one-time execution guaranteed.
So that's it for today. I hope I gave a clear explanation. Thank you reading my blog. Will see in my next blog.
Top comments (0)