简体   繁体   中英

What if we use only “else” block for “if…else” statement in javascript

I know that "if" statement can be used without the "else" block in javascript. But what if I need an "else" block only? What syntax should be in this case?

    if (req.body[data].length <= maxlength[indx]); // <===== semicolon
    else {
      req.body[data] = 'ERROR: too long';
      status = 404;
    }

or

    if (req.body[data].length <= maxlength[indx]) {} // <===== empty block
    else {
      req.body[data] = 'ERROR: too long';
      status = 404;
    }

ECMA stanadrt says nothing about this case ( https://262.ecma-international.org/5.1/#sec-12.5 )

Inverting the logic seems like the most plausible option here. Actually inverting logic is also related to code readability, if you invert the logic and place them at the beginning they are often referred to as Guard Clauses which improves readability a lot. You can check that topic out.

To clarify what others have answered:

In your specific case, you can just invert the operant so <= would become > .

In other cases, you can use ! to achieve what you are trying to do.


    if (req.body[data].length <= maxlength[indx]); // <===== semicolon
    else {
      req.body[data] = 'ERROR: too long';
      status = 404;
    }

should become


    if (req.body[data].length > maxlength[indx]) {
      req.body[data] = 'ERROR: too long';
      status = 404;
    }

The idea is to do the opposite of the condition in your original post which achieves the same purpose of having only an else statement. This way the code remains easier to read and reason about.

In this case, how can I do?

if (!address.street && !address.postcode && !address.city && !address.country)
 {    } 
else {result = await geocode(address)}

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