• 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
  • Ruby
  • 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.  JavaScript Coin Flip – How to Simulate Flipping a Coin in JavaScript
  • 2.  JavaScript Random Boolean – How to Generate Random Boolean Values
  • 3.  How to Change the Id of an Element in JavaScript
  • 4.  How to Convert Degrees to Radians Using JavaScript
  • 5.  Using JavaScript to Check if String Contains Letters
  • 6.  Using JavaScript to Get the Current Year
  • 7.  Using JavaScript to Change the href of a Link
  • 8.  Using JavaScript to Add Leading Zeros
  • 9.  Changing the Background Image of a div in JavaScript
  • 10.  Convert an Array to Set 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

Welcome to The Programming Expert. We are a group of US-based programming professionals who have helped companies build, maintain, and improve everything from simple websites to large-scale projects.

We built The Programming Expert to help you solve your programming problems with useful coding methods and functions in various programming languages.

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 © 2023 · The Programming Expert · About · Privacy Policy