📖 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
1
Create the stock counts array
Create an array called stockCounts with these exact values: [5, 3, 0, 7, 2].
Javascript
Hint
Use const to create the array named stockCounts.
2
Create the index variable
Create a variable called index and set it to 0.
Javascript
Hint
Use let to create a variable named index and assign it 0.
3
Use a for loop with break to find zero stock
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.
Javascript
Hint
Use a for loop with i from 0 to stockCounts.length. Inside, check if stockCounts[i] equals 0. If yes, assign i to index and use break.
4
Print the result
Write a console.log statement to print the message: "First out of stock product is at index: " followed by the value of index.
Javascript
Hint
Use console.log to print the message and the index variable.
Practice
(1/5)
1. What does the break statement do inside a loop in JavaScript?
easy
A. Pauses the loop for a moment
B. Stops the loop immediately and exits it
C. Restarts the loop from the beginning
D. Skips the current iteration and continues with the next
Solution
Step 1: Understand the purpose of break
The break statement is used to stop a loop or switch case immediately.
Step 2: Compare with other loop controls
Unlike continue which skips to the next iteration, break exits the loop fully.
Final Answer:
Stops the loop immediately and exits it -> Option B