Skip to content

JavaScript break for loop | Stop example code

  • by

To stop a for-loop early in JavaScript, you have to use a break statement. JavaScript break statement “jumps out” of a loop.

JavaScript break for loop example code

A simple example code ends the loop (“breaks” the loop) when the loop counter (i) is 3.

<!DOCTYPE html>
<html>
<head>

  <script>
    for (let i = 0; i < 10; i++) {
      if (i === 3) { 
        console.log("Break")
        break; 
      }
      console.log(i)
    } 
  </script>

</head>
<body>

</body>
</html>

Output:

JavaScript break for loop

Another example

We can break at any point in time the execution using the break keyword:

const list = ['a', 'b', 'c']
for (let i = 0; i < list.length; i++) {
  if (list[i] === 'b') break
  console.log(list[i])
}

break also works in for..of loops:

const list = ['a', 'b', 'c']
for (const item of list) {
  if (item === 'b') break
  console.log(item)
}

Do comment if you have any doubts or suggestions on this JS for loop topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading