简体   繁体   中英

Why doesn't this break work within inline if?

I'm wondering why this while loop breaks at first run when using an inline if with two actions (with break; being the second):

var list = [4, 2, 1, 3];

while (list.length) {
    list.splice(0, 1);
    console.log("length is now: " + list.length);

    if (list.length === 2) console.log("break!"); break;
}

Changing the last line to this works fine:

if (list.length === 2) break;

...and so does this:

if (list.length === 2) {
    console.log("break!");
    break;
}

AFAIK it's okay to have more than one action inside of an inline if, just like:

if (true) console.log("true"); console.log("still true");

AFAIK it's okay to have more than one action inside of an inline if, just like:

No, it isn't. To do that, you need a block ( {...} ):

if (list.length === 2) {
    console.log("break!");
    break;
}

Control-flow statements like if accept a single statement as the body. That statement can be a block if you need to make the body multiple statements long.

Doesn't matter how you write it (except as a matter of style, readability, and maintainability):

if (list.length === 2) { console.log("break!"); break; }

Linebreaks are almost entirely ignored by the JavaScript parser ( almost because of Automatic Semicolon Insertion, which is where the parser is expected to correct code with missing semicolons if it finds line breaks where they should be).

The inline if statement stops executing after the first statement if there are no curly braces present.

Example:

if (list.length === 2) console.log("break!"); break;

This will make the console.log run as the only statement and will not be able to reach the other break; statement.

It's almost never a good thing to use an inline if statement WITHOUT curly braces

if (list.length === 2) {console.log("break!"); break;}

Get into the habit of writing your if-statements with curly braces. You won't regret it!

Writing inline if statements without curly braces can give some unwanted behavior and is hard to maintain. Also, it's not fun to read. We need curly braces.

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM