To exit a for loop in JavaScript we can use the break statement. The break statement will exit a loop when it is called inside of the loop.

for (var i = 0; i < someArray.length; i++) {
  if ( a > b ) {
    break;
  }
}

Let’s take a look at a simple example below.


Let’s say we have a simple array of colors and we want to see if the color blue is included in the array of colors. To do this we will want to iterate through the array and check each color to see if it is “blue”. We can do it easily with a for loop. Once we find the color, we no longer need to check the other colors in the array, so we can end our loop using a break statement.

var colors = ["red","blue","green","yellow","orange","purple","pink","black"];
var colorFound = false;
for (var i = 0; i < colors.length; i++) {
  if (colors[i] == "blue"){
    //The color has been found.
    colorFound = true;
    //We can exit the loop
    break;
  }
}

If at the end of this loop, colorFound is “true”, then blue was in the array of colors. If colorFound is false, then blue is not in the array.

In this example, colorFound would have the value of “true”.

Let’s take a look at an example using HTML.

Exiting a for loop in JavaScript once a Value is Found

In this example, we will have a large array of CSS color names that are supported by all browsers. We will set up some HTML to let the user see all the colors contained in the array. We will also have an input field that will let the user enter a color to see if it is contained in the array. If it is, we will display that it is. Otherwise, we will display that it is not.

Here is the HTML set up:

Check color

In the JavaScript portion of this example, we will first create the HTML span elements that will each contain their own color. We will do this by iterating over the cssColors array using a for loop. The cssColors array will contain 140+ String color names. We will add the colors to div “#colorDiv” using the appendChild() method.

In the next part of this example, we will get the user inputted color from the input field.

We will finally check if the color is contained in the array of colors we have(cssColors) using a for loop. If we find that color, we will note that it has been found and exit the loop with a break statement. We will then display that the color was found. Otherwise we will display that it is not found in the #results div using the textContent property.

Notice we will also use the toLowerCase method to make it so the color is not case sensitive when searching.

Here is the JavaScript code:

var cssColors = ["AliceBlue","AntiqueWhite","Aqua","Aquamarine","Azure","Beige","Bisque","Black","BlanchedAlmond","Blue","BlueViolet","Brown","BurlyWood","CadetBlue","Chartreuse","Chocolate","Coral","CornflowerBlue","Cornsilk","Crimson","Cyan","DarkBlue","DarkCyan","DarkGoldenRod","DarkGray","DarkGrey","DarkGreen","DarkKhaki","DarkMagenta","DarkOliveGreen","DarkOrange","DarkOrchid","DarkRed","DarkSalmon","DarkSeaGreen","DarkSlateBlue","DarkSlateGray","DarkSlateGrey","DarkTurquoise","DarkViolet","DeepPink","DeepSkyBlue","DimGray","DimGrey","DodgerBlue","FireBrick","FloralWhite","ForestGreen","Fuchsia","Gainsboro","GhostWhite","Gold","GoldenRod","Gray","Grey","Green","GreenYellow","HoneyDew","HotPink","IndianRed","Indigo","Ivory","Khaki","Lavender","LavenderBlush","LawnGreen","LemonChiffon","LightBlue","LightCoral","LightCyan","LightGoldenRodYellow","LightGray","LightGrey","LightGreen","LightPink","LightSalmon","LightSeaGreen","LightSkyBlue","LightSlateGray","LightSlateGrey","LightSteelBlue","LightYellow","Lime","LimeGreen","Linen","Magenta","Maroon","MediumAquaMarine","MediumBlue","MediumOrchid","MediumPurple","MediumSeaGreen","MediumSlateBlue","MediumSpringGreen","MediumTurquoise","MediumVioletRed","MidnightBlue","MintCream","MistyRose","Moccasin","NavajoWhite","Navy","OldLace","Olive","OliveDrab","Orange","OrangeRed","Orchid","PaleGoldenRod","PaleGreen","PaleTurquoise","PaleVioletRed","PapayaWhip","PeachPuff","Peru","Pink","Plum","PowderBlue","Purple","RebeccaPurple","Red","RosyBrown","RoyalBlue","SaddleBrown","Salmon","SandyBrown","SeaGreen","SeaShell","Sienna","Silver","SkyBlue","SlateBlue","SlateGray","SlateGrey","Snow","SpringGreen","SteelBlue","Tan","Teal","Thistle","Tomato","Turquoise","Violet","Wheat","White","WhiteSmoke","Yellow","YellowGreen"];

//Populate HTML with colors in cssColors array
for (var i = 0; i < cssColors.length; i++) {
  var newColor = document.createElement('span');
  newColor.textContent = cssColors[i];
  document.getElementById("colorDiv").appendChild(newColor);
}

//Next get the user input, and check if the color is in our array
function checkColor() {
  var colorFound = false;
  var uInput = document.getElementById("new-color").value;
  var userInput = uInput.toLowerCase();
  //iterate over array and check for the user color
  for (var i = 0; i < cssColors.length; i++) {
    if( cssColors[i].toLowerCase() == userInput ){
      colorFound = true;
      break;
    }
  }
  if( colorFound == true ){
    document.getElementById("results").textContent = uInput + " IS in the array";
  } else {
    document.getElementById("results").textContent = uInput + " is NOT in the array";
  }
}

The final code and output for this example is below:

Code Output:


Check color

Full Code:

Check color


<script>

var cssColors = ["AliceBlue","AntiqueWhite","Aqua","Aquamarine","Azure","Beige","Bisque","Black","BlanchedAlmond","Blue","BlueViolet","Brown","BurlyWood","CadetBlue","Chartreuse","Chocolate","Coral","CornflowerBlue","Cornsilk","Crimson","Cyan","DarkBlue","DarkCyan","DarkGoldenRod","DarkGray","DarkGrey","DarkGreen","DarkKhaki","DarkMagenta","DarkOliveGreen","DarkOrange","DarkOrchid","DarkRed","DarkSalmon","DarkSeaGreen","DarkSlateBlue","DarkSlateGray","DarkSlateGrey","DarkTurquoise","DarkViolet","DeepPink","DeepSkyBlue","DimGray","DimGrey","DodgerBlue","FireBrick","FloralWhite","ForestGreen","Fuchsia","Gainsboro","GhostWhite","Gold","GoldenRod","Gray","Grey","Green","GreenYellow","HoneyDew","HotPink","IndianRed","Indigo","Ivory","Khaki","Lavender","LavenderBlush","LawnGreen","LemonChiffon","LightBlue","LightCoral","LightCyan","LightGoldenRodYellow","LightGray","LightGrey","LightGreen","LightPink","LightSalmon","LightSeaGreen","LightSkyBlue","LightSlateGray","LightSlateGrey","LightSteelBlue","LightYellow","Lime","LimeGreen","Linen","Magenta","Maroon","MediumAquaMarine","MediumBlue","MediumOrchid","MediumPurple","MediumSeaGreen","MediumSlateBlue","MediumSpringGreen","MediumTurquoise","MediumVioletRed","MidnightBlue","MintCream","MistyRose","Moccasin","NavajoWhite","Navy","OldLace","Olive","OliveDrab","Orange","OrangeRed","Orchid","PaleGoldenRod","PaleGreen","PaleTurquoise","PaleVioletRed","PapayaWhip","PeachPuff","Peru","Pink","Plum","PowderBlue","Purple","RebeccaPurple","Red","RosyBrown","RoyalBlue","SaddleBrown","Salmon","SandyBrown","SeaGreen","SeaShell","Sienna","Silver","SkyBlue","SlateBlue","SlateGray","SlateGrey","Snow","SpringGreen","SteelBlue","Tan","Teal","Thistle","Tomato","Turquoise","Violet","Wheat","White","WhiteSmoke","Yellow","YellowGreen"];

//Populate HTML with colors in cssColors array
for (var i = 0; i < cssColors.length; i++) {
  var newColor = document.createElement('span');
  newColor.textContent = cssColors[i];
  document.getElementById("colorDiv").appendChild(newColor);
}

//Next get the user input, and check if the color is in our array
function checkColor() {
  var colorFound = false;
  var uInput = document.getElementById("new-color").value;
  var userInput = uInput.toLowerCase();
  //iterate over array and check for the user color
  for (var i = 0; i < cssColors.length; i++) {
    if( cssColors[i].toLowerCase() == userInput ){
      colorFound = true;
      break;
    }
  }
  if( colorFound == true ){
    document.getElementById("results").textContent = uInput + " IS in the array";
  } else {
    document.getElementById("results").textContent = uInput + " is NOT in the array";
  }
}

</script>

Hopefully this article has been useful for you to understand how to exit a for loop in JavaScript.

Categorized in:

JavaScript,

Last Update: May 3, 2024