Use of 'break' in Javascript

Asked

Viewed 964 times

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 interrupts the loop of the j 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’s any kind of break that would interrupt the j and the i so that the result was:

The number is 1
The number is 2

I did, with a if and a variable, get around this problem. However, if there is a command like break, would be better.

3 answers

8


You can use a label on for external and use the break with that 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 on the blue "Run" button above to test this.

5

You can use what you call labeled break. Deep down it’s a drop a little more restricted. It tells you where the code should go when it breaks, and it 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 drop):

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());

I put in the Github for future reference.

Related: Why the use of GOTO is considered bad? (defend the drop in the right place and many people think that I love drop, I really hate him, I just don’t think that the hatred of the majority is rational, since people accept the break tagged that is a drop).

4

I don’t think there’s a "break everything", but you can play this loop in a function and finish it, it would circumvent 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>";
        }
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.