DEV Community

Cover image for Else Clauses on Loops
Aswin Barath
Aswin Barath

Posted on • Edited on

2 2 1 1 1

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🙂.

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay