Using the Break Statement in JavaScript Loops
📖 Scenario: You are helping a store manager find the first product that is out of stock from a list of products.
🎯 Goal: Build a program that searches through a list of product stock counts and stops searching as soon as it finds a product with zero stock using the break statement.
📋 What You'll Learn
Create an array called
stockCounts with the exact values: [5, 3, 0, 7, 2].Create a variable called
index and set it to 0.Use a
for loop with variable i to go through stockCounts.Inside the loop, use an
if statement to check if stockCounts[i] is 0.If zero is found, set
index to i and use break to stop the loop.Print the message:
"First out of stock product is at index: " followed by the value of index.💡 Why This Matters
🌍 Real World
Store managers often need to quickly find products that are out of stock to reorder them.
💼 Career
Knowing how to stop loops early with break improves efficiency in many programming tasks like searching and filtering.
Progress0 / 4 steps