Back to Course

Introduction to JavaScript

0% Complete
0/0 Steps
  1. JavaScript: Basics
    9Topics
    |
    10 Quizzes
  2. JavaScript: Variables
    9Topics
    |
    10 Quizzes
  3. JavaScript: Conditional Statements
    10Topics
    |
    11 Quizzes
  4. JavaScript: Functions
    10Topics
    |
    11 Quizzes
  5. JavaScript: Scope
    6Topics
    |
    7 Quizzes
  6. JavaScript: Arrays
    11Topics
    |
    12 Quizzes
  7. JavaScript: Loops
    8Topics
    |
    9 Quizzes
  8. JavaScript: High Order Functions
    3Topics
    |
    4 Quizzes
  9. JavaScript: Iterators
    6Topics
    |
    6 Quizzes
Lesson 7, Topic 8
In Progress

JavaScript: break Keyword

Yasin Cakal 23 Nov 2021
Lesson Progress
0% Complete

Assume we’re looking for a pet to adopt. We intend to visit the shelter every day for a week before stopping. What if, on day 3, we meet our ideal pet? We don’t want to go to the shelter for the next 4 days just to fulfill our original plan. We can use the keyword break in our code to stop a loop from continuing to execute even if the original stopping condition we wrote for our loop hasn’t been met.

The break keyword allows programs to “break” out of a loop while still inside its block.

Let’s take a look at the break keyword’s syntax:

for (let i = 0; i < 7; i++) {
  if (i > 7 ) {
     break;
  }
  console.log('Finding.');
} 
console.log('Yayaya found my pet!');


This is the output for the above code:

Finding.
Finding.
Finding.
Yayaya found my pet!

When looping through large data structures, break statements can be especially useful! We can use breaks to add test conditions in addition to the stopping condition and exit the loop when they are satisfied.

Responses

Leave a Reply

%d bloggers like this: