How to Break If-clause in JavaScript

People often don't think of using this break statement inside if-clause, but it's sometimes very useful.

For example, without break, another code indentation depth to be added

if (cond1){
    do1();

    if (cond2) {
        do2();
    }
}

But if with 'break' statement, it's neat:

if (cond1){
    do1();
    if (!cond2) break;
    do2();
}

However, break inside if-clause is illegal, a trick with 'for' loop should work:

for (let _ of [1])
if (cond1){
    do1();
    if (!cond2) break;
    do2();
}

You'll only receive email when they publish something new.

More from 19411
All posts