How can I use goto statement in JavaScript?

JavaScript does not have a native goto statement. While goto is a reserved keyword, it cannot be used in standard JavaScript code. However, you can achieve similar control flow using labels with break and continue statements.

Why goto Doesn't Exist in JavaScript

The goto statement was intentionally excluded from JavaScript to promote structured programming and avoid "spaghetti code" that makes programs difficult to understand and maintain.

Alternative: Using Labels with break and continue

JavaScript provides labeled statements that work with break and continue for controlled jumps:

let a = 0;

beginning: while (true) {
    console.log("Demo Text!");
    a++;
    if (a < 3) {
        continue beginning; // Jump to beginning label
    }
    break beginning; // Exit the loop
}

console.log("Loop finished, a =", a);
Demo Text!
Demo Text!
Demo Text!
Loop finished, a = 3

Nested Loop Example

Labels are particularly useful for breaking out of nested loops:

outerLoop: for (let i = 0; i < 3; i++) {
    for (let j = 0; j < 3; j++) {
        console.log(`i=${i}, j=${j}`);
        if (i === 1 && j === 1) {
            break outerLoop; // Break out of both loops
        }
    }
}
console.log("Exited nested loops");
i=0, j=0
i=0, j=1
i=0, j=2
i=1, j=0
i=1, j=1
Exited nested loops

Better Alternatives

Instead of simulating goto behavior, consider these structured approaches:

// Using functions for cleaner control flow
function processItems() {
    let a = 0;
    
    while (a < 3) {
        console.log("Processing item", a + 1);
        a++;
        
        if (someCondition(a)) {
            return; // Clean exit
        }
    }
}

function someCondition(value) {
    return value === 2; // Example condition
}

processItems();
Processing item 1
Processing item 2

Comparison of Control Flow Methods

Method Readability Maintainability Recommended
goto (not available) Poor Poor No
Labeled break/continue Moderate Moderate Limited use
Functions and return Good Good Yes

Conclusion

JavaScript intentionally lacks a goto statement to encourage better code structure. Use labeled statements sparingly, and prefer functions with return statements for cleaner, more maintainable control flow.

Updated on: 2026-03-15T22:01:56+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements