• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

The Programming Expert

Solving All of Your Programming Headaches

  • HTML
  • JavaScript
  • jQuery
  • PHP
  • Python
  • SAS
  • VBA
  • About
You are here: Home / JavaScript / How to Exit for Loop in JavaScript

How to Exit for Loop in JavaScript

February 23, 2022 Leave a Comment

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:

<style>#colorDiv span { margin-right: 10px; display: inline-block; }</style>
<div id="colorDiv"></div>
<div id="div1">
  <label for="userinput">Check if color is in list above:</label>
  <input type="text" id="new-color" name="userinput">
  <div id="click-me" onclick="checkColor()">Check color</div>
  <div id="results"></div>
</div>

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:

<style>#colorDiv span { margin-right: 10px; display: inline-block; }</style>
<div id="colorDiv"></div>
<div id="div1">
  <label for="userinput">Check if color is in list above:</label>
  <input type="text" id="new-color" name="userinput">
  <div id="click-me" onclick="checkColor()">Check color</div>
  <div id="results"></div>
</div>

<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.

Other Articles You'll Also Like:

  • 1.  Using JavaScript to Remove Trailing Zeros From a Number or String
  • 2.  Using JavaScript to Remove Apostrophe From a String
  • 3.  Remove Braces from String Using JavaScript
  • 4.  Add Years to a Date Using JavaScript
  • 5.  JavaScript sin – Find Sine of Number in Radians Using Math.sin()
  • 6.  JavaScript atanh – Find Hyperbolic Arctangent of Number
  • 7.  Using the getElementsByClassName Method in JavaScript
  • 8.  How to Create a New h1 Element With JavaScript
  • 9.  Remove the First and Last Character From a String in JavaScript
  • 10.  JavaScript isPrime – How to Check if a Number is Prime in JavaScript

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

About The Programming Expert

the programming expert main image

The Programming Expert is a compilation of hundreds of code snippets to help you find solutions to your problems in Python, JavaScript, PHP, HTML, SAS, and more.

Search

Learn Coding from Experts on Udemy

Looking to boost your skills and learn how to become a programming expert?

Check out the links below to view Udemy courses for learning to program in the following languages:

Copyright © 2022 · The Programming Expert · About · Privacy Policy