How to Exit and Stop a for Loop in JavaScript and Node.js

Sometimes you need to break out of a loop in JavaScript. For example, you may want to stop iterating through an array of items as soon as you find a specific element.

TL;DR: use break to exit a loop in JavaScript.

This tutorial shows you how to terminate the current loop in JavaScript and transfer control back to the code following the loop.

Node.js Series Overview

Early Exit a for Loop in JavaScript

The break statement terminates an active loop and proceeds your code with statements following the loop:

const users = [  
  { id: 1, name: 'Marcus' },
  { id: 2, name: 'Norman' },
  { id: 3, name: 'Christian' }
]

for (const user of users) {  
  if (user.id === 2) {
    break            // exits the loop early
  }

  console.log(user)
}

// log output:
// { id: 1, name: 'Marcus' }

Supported Loops

The good thing: break works for all JavaScript loops:

  • for..of
  • for..in
  • for(i; i<length; i++)
  • while

Enjoy!

Explore the Library

Find interesting tutorials and solutions for your problems.