Essential JavaScript

Going Further

Breaking a Loop

We can break out of a loop while it is running.

The break keyword stops a loop. The rest of the code inside the loop doesn't run. The code keeps running after the loop.

Here's a basic example:

let i = 0; while (i < 10) { console.log(i); if (i === 5) { break; } i++; }

Once i reaches 5, the loop breaks. The value of i will never reach 10.

Break inside a function

Here's an example of breaking out of a loop inside a function:

function getFirstWord(string) { let result = ''; for (let i = 0; i < string.length; i++) { let character = string[i]; if (character === ' ') { break; } result += character; } return result; } getFirstWord('The fox jumped over the lazy dog');

Returning out of a loop

We can also use the return keyword to exit a loop.

Remember that we can only return from inside a function:

function getFirstWord(string) { let result = ''; for (let i = 0; i < string.length; i++) { let character = string[i]; if (character === ' ') { return result; } result += character; } return result; } getFirstWord('The fox jumped over the lazy dog');

Since return stops the rest of the code inside the function from running, it stops the loop as well.

Learning Goals

  • I can break a loop with break

  • I can break a loop with return

Code Editor

Click "Run Code" to execute your JavaScript in a secure sandbox and see the output below.

Console Output

// Console output will appear here...

0 output lines