Using 'break' in JavaScript

4

For example, if I have the following code:

var i, j;
for (i = 1; i <= 3; i++) {
    for (j = 1; j <= 3; j++) {
        if (j === 3) { break; }
        text += "The number is " + j + "<br>";
    }
}

When using break, it breaks the j loop and the result is:

The number is 1
The number is 2
The number is 1
The number is 2
The number is 1
The number is 2

I want to know if there is any kind of break that would break j and i so the result would be:

The number is 1
The number is 2

I was able to get around this problem with a if and a variable. However, if a command such as break exists, it would be better.

    
asked by anonymous 01.02.2018 / 17:09

3 answers

9

You can use a label on the% external% and use for with this label:

var i, j, text = "";
a: for (i = 1; i <= 3; i++) {
    for (j = 1; j <= 3; j++) {
        if (j === 3) { break a; }
        text += "The number is " + j + "<br>";
    }
}
document.write(text);

Click the blue "Run" button above to test this.

    
01.02.2018 / 17:15
6

You can use what is called labeled break . In the background is goto a little more restricted. It says where the code should go when it breaks, and obviously needs a "tag" in the code telling you where the location is:

var text = "";
fim: for (var i = 1; i <= 3; i++) {
    for (var j = 1; j <= 3; j++) {
        if (j === 3) break fim;
        text += "The number is " + j + "<br>";
    }
}
console.log(text);

You can also terminate the execution of the algorithm completely, this is possible within a function (I prefer this solution without any kind of goto ):

function Finaliza() {
    var text = "";
    for (var i = 1; i <= 3; i++) {
        for (var j = 1; j <= 3; j++) {
            if (j === 3) return text;
            text += "The number is " + j + "<br>";
        }
    }
    return text;
}

console.log(Finaliza());

Related: Why is GOTO used bad? (I defend goto in> the right place and a lot of people think I love goto , in fact I hate it, I just do not think majority hate is rational, since people accept break in> tagging which is a goto ).

    
01.02.2018 / 17:15
5

I think there is no " break all" but you can throw that loop into a function and end it, this would bypass the problem:

function ExibirNum(){
    var i, j;
    for (i = 1; i <= 3; i++) {
        for (j = 1; j <= 3; j++) {
            if (j === 3) 
                return;
            text += "The number is " + j + "<br>";
        }
    }
}
    
01.02.2018 / 17:14