Skip to content
Home » Program to Iterate Over an Array and Break at a Specified Value

Program to Iterate Over an Array and Break at a Specified Value

In this blog post, we will discuss a simple program that demonstrates how to iterate over an array in JavaScript and break the loop when a specified value is encountered. The program will help you understand the concept of looping and conditional statements in JavaScript.

Code

const xArray = ["1' 2", "3", "4", "5"];

for (let i = 0; i < xArray.length; i++){
  console.log(xArray[i]);
  if (xArray[i] === '4'){
    break;
  }
}

console.log("Sample code");

Code Explanation

The provided code snippet consists of an array named xArray, which contains a series of elements. The program uses a for loop to iterate over each element of the array. Within the loop, each element is printed to the console using the console.log() method.

The program also includes a conditional statement that checks if the current element is equal to the value ‘4’. If the condition is met, the loop breaks using the break statement. This means that the loop will stop iterating further and move on to the next line of code outside the loop.

To provide a better understanding, let’s consider an example. Suppose we have the following array:

javascript
const xArray = ["1' 2", "3", "4", "5"];

When we run the program, it will iterate over each element of the array and print it to the console. The output will be as follows:

1' 2
3
4

After printing the element ‘4’, the condition is satisfied, and the loop breaks. The line of code console.log("Sample code"); will be executed, resulting in the output:

1' 2
3
4
Sample code

Conclusion

In this blog post, we have discussed a simple program that demonstrates how to iterate over an array and break the loop at a specified value using JavaScript. The program showcased the usage of for loop, conditional statements, and the break statement. By understanding these concepts, you can effectively control the flow of your programs and make them more efficient.

We hope this tutorial has been helpful in expanding your knowledge of JavaScript programming. Practice writing similar programs to strengthen your understanding. Happy coding!

Also checkout the following codes.


How to Convert Vowels in a Text to Double Letters using JavaScript
“Program to Retrieve Information from an Object in JavaScript”