DEV Community

Cover image for Else Clauses on Loops
Aswin Barath
Aswin Barath

Posted on • Edited 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

Best Resources

Who Am I?

I’m Aswin Barath, a Software Engineering Nerd who loves building Web Applications, now sharing my knowledge through Blogging during the busy time of my freelancing work life. Here’s the link to all of my socials categorized by platforms under one place: https://linktr.ee/AswinBarath

Thank you so much for reading my blog🙂.

Top comments (0)