Regardless of the programming language, being able to understanding how to get the computer to move through your logic in the correct way is important. Whether you need the computer to break out of a loop, skip a step, or stop a function and return early due to an error or edge case. In JavaScript, break, continue, and return provide you the tools to accomplish these tasks.
Return
Let's start with the most basic redirection tool, return. Return simply stops the execution of a function and returns any value specified, or it will return "undefined" if no value is specified.
function isThisNumberFive(num) {
let result = false;
if (num === 5) {
result = true;
}
return result;
console.log("This will never print to the console.")
}
console.log(isThisNumberFive(5));
console.log(isThisNumberFive(1));
Output:
> true
> false
Once the program hits that return statement, it will stop the executing the function and return the specified value back to the function caller. In this example, the specified return value was the variable "result," which was returned to the line of code where it was called, and was then printed to the console. We also see that the sentence "This will never print to the console," turned out to be prophetic.
Now you may be thinking what's the point? Why don't all programming languages just have an implicit return at the end of all functions and call it a day? Well, there are situations where we need the program to return early. One example of this is a guard block. A guard block is an if statement that will do a fast return if a certain condition isn't met. Often this is used to throw an error if bad data is pasted to the function. Let's add a guard block to the last example.
function isThisNumberFive(num) {
if (typeof num !== 'number') {
return "The argument passed was not a number";
}
let result = false;
if (num === 5) {
result = true;
}
return result;
console.log("This will never print to the console.")
}
console.log(isThisNumberFive("5"));
console.log(isThisNumberFive(5));
Output:
> "The argument passed was not a number"
> true
By checking the data type of the argument pass to the function, the program was able to return quickly without wasting time trying to run the rest of the function. This can also be used to make an algorithm faster if you know that certain conditions allow you to return a result without running the rest of the algorithm.
Break
Now what if you need to stop a loop under certain conditions but you don't want to stop the function and return a value? In that case, you want a break!
function myFoodOpinions(food) {
let i = 0;
let enhancer = "";
while (i < 5) {
if (food !== 'tacos') {
break;
}
enhancer += 'really, ';
i++;
}
return 'I ' + enhancer + `love ${food}!`;
}
console.log(myFoodOpinions('pizza'));
console.log('But...')
console.log(myFoodOpinions('tacos'));
Output:
> I love pizza!
> But...
> I really, really, really, really, really, love tacos!
Now what if you need to break out of a nested loop, but not out of the outermost loop? JavaScript has a cool option that allows you to do just that, and it does this with labels!
function testBreakLabels() {
let i = 0;
let j = 0;
let k = 0;
outer_loop: while (i < 3) {
middle_loop: while (j < 3) {
inner_loop: while (k < 3) {
if (k === 2) {
break middle_loop;
}
console.log('Inner Loop');
k++;
}
console.log('Middle Loop');
j++;
}
console.log('Outer Loop');
i++;
}
}
testBreakLabels();
Output:
> Inner Loop
> Inner Loop
> Outer Loop
> Outer Loop
> Outer Loop
An important thing to notice is that the label that you specify is the block of code that the break statement will break out of. In this example, we specified the middle_loop, so code broke out to the outer loop and "Middle Loop" is never printed to the console. If we had specified the outer_loop, the program would have broken out of all of the loops.
Two other things to note about break labels.
- The labeled block of code does not have to be a loop. This will work on any block of code that is labeled.
- The break must be nested inside the block of code that the label specifies. If it's not, JavaScript with throw an error.
Continue
Continue is similar to break, but rather than breaking completely out of the loop, continue simply skips over an iteration of the loop.
function testContinue() {
let oddNumbers = [];
for (let i = 0; i < 10; i++) {
if (i%2 === 0) {
continue;
}
oddNumbers.push(i);
}
return oddNumbers;
}
console.log(testContinue());
Output:
> [ 1, 3, 5, 7, 9 ]
In this example we're using continue to only add the odd numbers between 0 and 10 to any array. When the i is equal to an even number, the program enters the if statement and executes the continue. The program is then directed to the next iteration of the for loop without executing the rest of the code in the for loop.
JavaScript gives you option of using labels with continue as well. Let's nest the continue inside blocks for this example.
function testContinue() {
outer_block: {
middle_block: {
inner_block: for (let i = 0; 1 < 10; i++) {
if (i === 3) {
continue middle_block;
}
console.log('Inner Block');
}
console.log('Middle Block');
}
console.log('Outer Block');
}
}
testContinue();
Output:
> SyntaxError: Illegal continue statement: 'middle_block' does not denote an iteration statement
That's not what we wanted. It turns out that unlike break, continue cannot skip to an outer block that is not a loop. This is because where the continue tell the program to skip too.
- If the outer loop is a while loop, continue will skip back to the conditional statement.
- If the outer loop is a for loop, continue will skip back to the update expression.
Since a regular block won't have a conditional statement or an update expression to skip to, JavaScript will throw an error. Let's use the nested while loop example for the section on breaks and see what happens when we use a continue instead.
function testBreakLabels() {
let i = 0;
let j = 0;
let k = 0;
outer_loop: while (i < 3) {
middle_loop: while (j < 3) {
inner_loop: while (k < 3) {
if (k === 2) {
k++;
continue middle_loop;
}
console.log('Inner Loop');
k++;
}
console.log('Middle Loop');
j++;
}
console.log('Outer Loop');
i++;
}
}
testBreakLabels();
Output:
> Inner Loop
> Inner Loop
> Middle Loop
> Middle Loop
> Middle Loop
> Outer Loop
> Outer Loop
> Outer Loop
This output is definitely different from the one we got when using a break. When using a break, the program never executed any of the code in the middle while loop. Continue, on the other hand, directed the program back to the conditional statement of the middle while loop and then re-entered that loop.
As a side note, notice that I had to increment the variable k right before the continue. Without it, the program would be locked in an infinite loop because once k is equal to 2, the program will no longer get to the incrementation of k at the bottom of the inner while loop.
References
MDN Web Docs
Return
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return
Break
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break
Continue
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/continue
Loops and Iteration
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration
Top comments (0)