DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for Else Clauses on Loops
Aswin Barath
Aswin Barath

Posted on • Updated on

Else Clauses on Loops

Did you know that loop statements may have an else clause?
Well, it turns out that they can be used!

  • else clause will be executed when the loop completes through all of the iterations with for loop and when the condition becomes false with while loop.

Example:
Alt Text

Output:

Searching...
Searching...
Searching...
Searching...
Searching...
Searching...
Searching...
Searching...
Treasure not found :(
Enter fullscreen mode Exit fullscreen mode
  • But else clause will not be executed when the loop is terminated by a break statement.

Example:
Alt Text

Output:

Searching...
Searching...
Searching...
Searching...
Found the treasure
Enter fullscreen mode Exit fullscreen mode

Code along and have fun.

Top comments (0)

50 CLI Tools You Can't Live Without

>> Check out this classic DEV post <<