Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Demonstrate nested loops with return statements in JavaScript?
In JavaScript, you can use return statements inside nested loops to exit from functions early. When a return statement is executed inside nested loops, it immediately exits the entire function, not just the current loop.
Example
let demoForLoop = () => {
for(var outer = 1; outer < 100; outer++){
for(var inner = 1; inner <= 5; inner++){
if(outer == 3){
return 'THE OUTER VALUE IS EQUAL TO 3 INSIDE THE LOOP';
}
}
}
return 'OUT OF THE LOOP';
}
console.log(demoForLoop());
THE OUTER VALUE IS EQUAL TO 3 INSIDE THE LOOP
How It Works
When the outer loop reaches the value 3, the condition outer == 3 becomes true. The return statement executes immediately, terminating the function and returning the specified value. The inner loop iterations and remaining outer loop iterations are skipped entirely.
Example with Multiple Return Points
let findValue = (target) => {
for(let i = 1; i <= 3; i++){
for(let j = 1; j <= 3; j++){
console.log(`Checking i=${i}, j=${j}`);
if(i * j === target){
return `Found target ${target} at i=${i}, j=${j}`;
}
}
}
return `Target ${target} not found`;
}
console.log(findValue(6));
Checking i=1, j=1 Checking i=1, j=2 Checking i=1, j=3 Checking i=2, j=1 Checking i=2, j=2 Checking i=2, j=3 Found target 6 at i=2, j=3
Key Points
- Return statements in nested loops exit the entire function, not just the current loop
- Use return for early function termination when a condition is met
- Any code after the return statement in nested loops won't execute
- If you need to exit only the current loop, use break or continue instead
Conclusion
Return statements in nested loops provide a clean way to exit functions early when specific conditions are met. This approach is useful for search operations or when you need to stop processing once a target value is found.
