What is the advantage of using Javascript?

Asked

Viewed 52 times

-1

Using label in for

let str = '';

loop1:
for (let i = 0; i < 5; i ++) {
    if (i === 1) {
        continue loop1;
    }

    str = str + i;
}

console.log(str);

Not using label on for

let str = '';

for (let i = 0; i < 5; i ++) {
    if (i != 1) {
        str = str + i;
    }
}

console.log(str);

In the two examples both codes do the same thing use one or the other will return the same result, in this example there is some advantage in usinglo, because in my view when making use of it the code gets longer and if the program is extended it will make it difficult to read the code. Not only in these simple examples, but in other cases what are the advantages in using it. I know other languages that have in their entrails the label and goto inplementados and they are the same as Javascript? (since Javascript does not have the command goto, but the command continue kind of "replaces" him).

1 answer

0

Labels are not unique to Javascript, they are common to languages with procedural features such as C, Java, etc.

When applied to a single loop (a for or a while for example) it is not advantageous, but when you have two or more nested loops, that is, with one inside the other, it serves to differentiate for which of the loops he wants to jump with one break, continue or similar command.

Example: if you give the most external loop the label primeiro_loop, may within the call loops break primeiro_loop; to jump out of all the loops at once (if not indicating the label, it exits only the innermost loop and falls into the next loop).

Browser other questions tagged

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