Back to JavaScript
2025-12-086 min read

Labeled function declarations (JavaScript)

Learn Labeled function declarations (JavaScript) step by step with clear examples and exercises.

Why This Matters

Understanding labeled function declarations is crucial for writing efficient and readable JavaScript code. They provide a way to create functions with labels that can be used with break or continue statements within loops, making it easier to navigate complex loop structures and break out of nested loops when specific conditions are met. This feature becomes essential in real-world applications where error handling and debugging might require jumping between different parts of the code.

Labeled function declarations also offer a powerful tool for structured error handling and exception management, allowing developers to gracefully handle errors and exit from multiple nested loops or functions when needed.

Prerequisites

To fully grasp this lesson, you should have a solid understanding of the following topics:

  1. Basic JavaScript syntax (variables, data types, operators)
  2. Control structures (if-else statements, switch cases, loops)
  3. Function declarations and expressions
  4. Block scoping and hoisting in JavaScript
  5. Understanding how break and continue statements work within loops
  6. Familiarity with error handling concepts such as exceptions and try/catch blocks

Core Concept

A labeled function declaration consists of a label followed by the function keyword, a name, and a set of parameters enclosed within parentheses. The label is an identifier that can be used to control the flow of the program using break or continue statements.

labelName: function functionName(parameters) {
// function body
}

To call a labeled function, simply use its name without the label, just like you would with any other function. Here's an example of a labeled function declaration and its usage:

outerLoop:
for (let i = 0; i < 5; i++) {
for (let j = 0; j < 3; j++) {
if (i === 2 && j === 1) {
break outerLoop; // exits the outer loop when specific conditions are met
}
console.log(`i = ${i}, j = ${j}`);
}
}

// defined but not called labeled function
myFunction: function() {
console.log('This is a labeled function!');
}

// calling the labeled function
myFunction();

In this example, we have defined a labeled function myFunction, which simply logs a message to the console. We also have an outer loop and an inner loop that iterate over two variables, i and j. When both i and j reach specific values (2 and 1, respectively), the break statement is executed, causing the program to exit the outer loop.

Example with a labeled function used for error handling

outerLoop:
for (let i = 0; i < 5; i++) {
innerLoop:
for (let j = 0; j < 3; j++) {
if (i === 2 && j === 1) {
// Simulating an error by dividing by zero
const result = someFunction(j, 0);
console.log(`Result: ${result}`);
break outerLoop; // exits the outer loop when specific conditions are met
} else if (i === 3 && j === 2) {
throw new Error('An error occurred!');
}
console.log(`i = ${i}, j = ${j}`);
}
}

// defined but not called labeled function
myFunction: function() {
console.log('This is a labeled function!');
}

In this example, we have added an error-handling scenario where the function someFunction(j, 0) simulates an error by dividing by zero when i equals 2 and j equals 1. The throw statement is used to create an exception, which can be caught and handled if necessary. In this case, we use a labeled function declaration to break out of the nested loops once the error occurs, preventing further execution of the code.

Worked Example

Let's consider a more practical example of labeled function declarations. Suppose we have an array of objects representing employees, each with properties like name, age, and department. We want to find all employees who work in the IT department and are older than 30 years. To do this, we can use a labeled function declaration to break out of nested loops when we encounter an employee that meets our criteria.

const employees = [
{ name: 'John', age: 28, department: 'IT' },
{ name: 'Alice', age: 35, department: 'HR' },
{ name: 'Bob', age: 40, department: 'IT' },
{ name: 'Charlie', age: 22, department: 'Finance' }
];

outerLoop:
for (let i = 0; i < employees.length; i++) {
const employee = employees[i];
innerLoop:
for (const department of Object.values(employees)) { // iterate over all objects in the array
if (department.department === 'IT' && department.age > 30) {
console.log(`Found employee: ${department.name}`);
break outerLoop; // exit the outer loop when an eligible employee is found
}
}
}

In this example, we have an array of employees with their respective ages and departments. We use a labeled function declaration to find all employees who work in the IT department and are older than 30 years. The break statement inside the inner loop allows us to exit the outer loop once we've found an eligible employee.

Common Mistakes

  1. Forgetting to define the label: Remember that a labeled function declaration requires a label before the function keyword. If you forget to include the label, your code will throw a syntax error.
  1. Using the wrong control structure (continue instead of break): When working with labeled function declarations, it's essential to use the break statement to exit the loop containing the labeled function. Using continue will skip the current iteration but won't affect the loop's overall execution.
  1. Misunderstanding the scope of labels: Labels are only valid within the function in which they are defined. If you try to use a label from an outer function inside a nested function, you will encounter a reference error.

Common Mistakes - Subheadings

  • Label Naming Conventions
  • Choosing meaningful and descriptive labels
  • Avoiding reserved keywords as labels
  • Label Scope and Function Hoisting
  • Understanding the relationship between labeled function declarations and hoisting
  • Labels are only accessible within their containing function

Practice Questions

  1. Write a labeled function declaration that calculates the factorial of a number using a while loop and breaks out of the loop when the result is found.
  1. Given an array of numbers, write a labeled function that finds the smallest positive integer that is missing from the array. The function should use a for...of loop and break out of the loop once the missing number is found.
  1. Write a labeled function that simulates a game where the user has to guess a secret number between 1 and 100. The function should use a while loop, and the user should be able to exit the game by using the label "exit".
  1. Implement a labeled function that finds the maximum value in an array using a recursive approach and breaks out of the recursion when the base case is met.

FAQ

  1. Can I label a variable or constant in JavaScript?

No, you cannot label variables or constants in JavaScript. Labels are used exclusively for functions.

  1. What happens if I try to use a labeled function outside its containing scope?

If you try to use a labeled function from an outer scope, you will encounter a reference error because labels are only valid within the function in which they are defined.

  1. Can I label a function expression instead of a declaration?

No, labeled function expressions are not supported in JavaScript. You can only label function declarations.

  1. What happens if I use an undefined label in my code?

Using an undefined label will result in a syntax error and prevent your code from running correctly. Make sure to define all labels before using them in your functions.

  1. Is it possible to label multiple functions within the same scope with the same name?

No, you cannot have multiple labeled functions with the same name within the same scope because labels are unique identifiers for each function. If you try to do so, you will encounter a syntax error.

Labeled function declarations (JavaScript) | JavaScript | XQA Learn