javascript

Jump Statements

Learn about JavaScript jump statements: `break`, `continue`, `return`, and `throw`. Understand how they control program flow, exit loops or functions, and handle errors effectively.

10 min read 8 sections Tutorial
Share

Jump statements change the normal order of how your code runs. Normally, your code runs line by line, from top to bottom. Jump statements let you "jump" to a different part of your code or stop a process early. This is useful when you need to stop a loop, skip some code in a loop, send a result from a function, or signal that something went wrong. Learning these helps you write more flexible and powerful programs.

JavaScript Jump Statements

JavaScript Jump Statements

Jump statements are special keywords that change the normal flow of your program. They let your code move from one part to another without running every line in between.

Imagine your code as a path. Jump statements are like shortcuts or exits on that path. They help you control exactly when and where your program should go next.

In JavaScript, the main jump statements are break, continue, return, and throw.

What are Jump Statements?

Jump statements are keywords in programming that immediately transfer control of the program to another location or terminate the current execution block.

break

Stops a loop or a switch statement immediately. Your code continues after the loop or switch.

continue

Skips the rest of the current loop turn. Your code goes to the next turn of the loop.

return

Exits a function and can send a value back to where the function was called.

throw

Creates an error and stops the program. Used to signal something went wrong.

Understanding Program Flow

Getting Started

Understanding Program Flow

When you write code, it usually runs from the first line to the last line. If you have a loop, it runs all the way through for every item. This is the normal program flow.

Jump statements let you change this normal flow. They give you control to decide when to stop, skip, or exit a block of code.

Let's see a simple loop without any jump statements first.

javascript
1// This loop will print numbers from 0 to 4
2for (let i = 0; i < 5; i++) {
3 // This line runs for every number (0, 1, 2, 3, 4)
4 console.log('Current number:', i);
5}
6// After the loop finishes all 5 turns, this line runs
7console.log('Loop finished.');

Use jump statements wisely

Jump statements are powerful tools, but using too many can make your code harder to read and understand. Always think if there is a clearer way to write your code before adding a jump statement.

The `break` Statement

The `break` Statement

The break statement is used to stop a loop or a switch statement immediately. When JavaScript sees break, it completely exits the current loop or switch block.

The program then continues running any code that comes after the loop or switch. It's like pressing an emergency stop button for that specific block of code.

This is useful when you have found what you are looking for and do not need to check any more items.

javascript
1const numbers = [10, 20, 30, 40, 50];
2let foundNumber = false;
3
4// Loop through the numbers
5for (let i = 0; i < numbers.length; i++) {
6 const currentNumber = numbers[i];
7 console.log('Checking:', currentNumber);
8
9 // If the current number is 30, we found it!
10 if (currentNumber === 30) {
11 console.log('Found 30! Stopping the search.');
12 foundNumber = true;
13 break; // This stops the loop right here
14 }
15}
16
17// This line runs after the loop has stopped
18if (foundNumber) {
19 console.log('Search completed successfully.');
20} else {
21 console.log('Number not found.');
22}
✗ BadLess efficient (no break)
const items = ['apple', 'banana', 'orange'];
let found = false;
for (let i = 0; i < items.length; i++) {
console.log('Checking: ' + items[i]);
if (items[i] === 'banana') {
found = true;
}
}
if (found) {
console.log('Banana was found.');
}
✓ GoodMore efficient (with break)
const items = ['apple', 'banana', 'orange'];
let found = false;
for (let i = 0; i < items.length; i++) {
console.log('Checking: ' + items[i]);
if (items[i] === 'banana') {
found = true;
break; // Stop once found
}
}
if (found) {
console.log('Banana was found.');
}

The `continue` Statement

The `continue` Statement

The continue statement is also used inside loops. But instead of stopping the loop completely like break, continue skips only the current turn (or iteration) of the loop.

When JavaScript sees continue, it stops running the rest of the code for that particular turn. Then, it immediately jumps to the next turn of the loop.

This is helpful when you want to skip certain items in a list but still process the others.

Using `if` to skip
const scores = [10, -5, 20, -1, 30];
let total = 0;
for (let i = 0; i < scores.length; i++) {
if (scores[i] >= 0) { // Only add positive scores
total += scores[i];
}
}
console.log('Total positive scores:', total);
VS
Using `continue` to skip
const scores = [10, -5, 20, -1, 30];
let total = 0;
for (let i = 0; i < scores.length; i++) {
if (scores[i] < 0) { // If score is negative, skip this turn
continue;
}
// This code only runs for positive scores
total += scores[i];
}
console.log('Total positive scores:', total);

When to use `continue`

Use continue when you want to filter items inside a loop. If a condition is met, continue lets you quickly move to the next item without doing extra work for the current one. It can make your loop's main logic clearer.

The `return` Statement

The `return` Statement

The return statement is used inside functions. Its main job is to stop the function from running and send a value back to the part of the code that called the function.

When a function executes a return statement, it immediately stops. No more code inside that function will run. The value specified after return is then sent back as the function's result.

If you use return without a value, the function sends back undefined.

1

Define a function that returns a value

Create a simple function that adds two numbers and uses return to send the sum back.

javascript
1function addNumbers(a, b) {
2 const sum = a + b;
3 return sum; // Send the sum back as the function's result
4}
5
6let result = addNumbers(5, 3);
7console.log('The sum is:', result); // Output: The sum is: 8
2

Return based on a condition

Functions can use return inside if statements to exit early if a condition is not met.

javascript
1function checkAge(age) {
2 if (age < 18) {
3 return 'Too young'; // Exit early if age is less than 18
4 }
5 return 'Adult'; // Only runs if age is 18 or more
6}
7
8console.log(checkAge(15)); // Output: Too young
9console.log(checkAge(20)); // Output: Adult
3

Return without a value

If a function does not need to send back a specific value, you can use return by itself to just stop the function. It sends back undefined by default.

javascript
1function greet(name) {
2 console.log('Hello, ' + name + '!');
3 return; // Stop the function, sends back undefined
4 console.log('This line never runs'); // This line is ignored
5}
6
7let greetingResult = greet('Bob');
8console.log('Function returned:', greetingResult); // Output: Function returned: undefined

Forgetting `return` for expected values

If your function is supposed to calculate something and send it back, but you forget the return statement, the function will implicitly return undefined. This can lead to unexpected undefined values in your calculations or logic.

function multiply(x, y) {
  const product = x * y; 
  // Missing 'return product;' here
}
let val = multiply(2, 4); // val will be undefined
console.log(val);        // undefined

The `throw` Statement

The `throw` Statement

The throw statement is used to create a custom error. When JavaScript sees throw, it immediately stops the current function and tries to find a special try...catch block to handle the error.

If no try...catch block is found, the program will crash and stop running. You can throw any JavaScript value, but it's best practice to throw an Error object.

This is very important for telling other parts of your program when something unexpected or wrong has happened.

StatementPurposeWhere it worksSends back a value?
breakExit loop/switchLoops (`for`, `while`, `do...while`), `switch`No
continueSkip current loop iterationLoops (`for`, `while`, `do...while`)No
returnExit functionFunctionsYes (or `undefined`)
throwSignal an errorAnywhereNo (creates an error object)

Test Your Knowledge

Test Your Knowledge

Test Your Knowledge

Quick Check

Which statement would you use to immediately stop a for loop and continue execution after the loop?

Quick Check

What does the continue statement do inside a while loop?

Quick Check

If a function is defined as function calculate() { let x = 10; } and then called, what value will calculate() return?

Quick Check

When you throw an error in JavaScript, what is the immediate effect if there is no try...catch block to handle it?

Quick Reference

Quick Reference

Quick Reference

Pro Tips
  • 1break — immediately exits the current loop or switch statement.
  • 2continue — skips the rest of the current loop iteration and moves to the next one.
  • 3return — exits a function and sends a value back to the caller.
  • 4throw — creates and signals an error, stopping execution unless caught.
  • 5Loopsbreak and continue are used only inside loops (for, while, do...while).
  • 6Functionsreturn is used only inside functions to provide a result.
  • 7Error Handlingthrow is fundamental for error handling, often paired with try...catch.
  • 8Default Return — functions without an explicit return statement return undefined.
  • 9Readability — use jump statements carefully; too many can make code hard to follow.
  • 10Efficiencybreak can make loops more efficient by stopping early when a condition is met.

Loops

Deepen your understanding of for, while, and do...while loops, where break and continue are used.

Functions

Explore how functions work, how to pass arguments, and how return statements are crucial for their output.

Error Handling

Learn about try...catch blocks to gracefully manage errors created by the throw statement.

Switch Statements

Understand how switch statements work for multiple conditions and how break is essential within them.

You now understand JavaScript Jump Statements!

You've learned how break, continue, return, and throw control your program's flow. You know when to stop loops, skip iterations, send values from functions, and signal errors. These tools are vital for writing dynamic and robust JavaScript applications.

Try it in the Javascript Compiler

Run and experiment with Javascript code right in your browser — no setup needed.

Continue Learning