Using && e || instead of "if" and "Else"

Asked

Viewed 2,430 times

19

Lately I’ve seen some codes that use && and || to replace if and else , and even to do checks with less code. I’m using this technique quite smoothly so far. Follow an example code:

const bool = true
const foo = 'Abacate'
const bar = 'Maçã'

bool && alert( foo || bar )

Until then I’ve been using this kind of approach to discover her flaws.

My problem is that I don’t know "what is this," if that technique has a name. So I didn’t know how to look on the internet about good practices, about semantics and if it’s worth using. So I’ll ask a few questions.

  • What’s the name of it?
  • Is it worth using?
  • It will make it difficult for others to read?
  • Is there any related good practice or care I should take?
  • I could cite examples of where this technique is good?
  • 2

    Possible duplicate of Difference between operators && e ||

  • 1

    The staff already answered the question very well so I just want to give you a piece of advice: never name a variable with the name "bool". Since "bool" is a type of data in many languages, including c++, naming a variable with that name can create a lot of confusion. I know that in C there is no type "bool" but try to avoid... It is as if I name a variable as "Integer" or "Int" or "Struct"... Avoid naming C variables with the same reserved C++word name... Tip

2 answers

19

bool && alert( foo || bar )

There’s two different things going on there, but come on.

What’s the name of it?

First, the bool &&: That part uses the short-circuit evaluation, present in most modern languages. What it does is, briefly, avoid evaluating more boolean expressions than necessary.

See that in a ||, if we have a true, is enough that we don’t need to evaluate the next expressions (true or anything is always true), and the same thing for a false in a && (false and anything is always false). So we can exchange this:

if (bool) alert(1)

That’s why:

bool && alert(1)

'Cause if bool is fake, the part alert(1) will not be evaluated (executed).

Now, foo || bar: null coalescing. Basically, if foo is any falsely (null, undefined, false, ...), the operator || returns bar in place.

Is it worth using?

Short circuit evaluation, hardly. Readability is terrible, use an if unless extremely necessary.

Null coalescing, yes, is a great alternative to:

let var = foo != null ? foo : bar

Or even for a if (foo == null) .... Overall, null coalescing is quite easy to read.

It will make it difficult for others to read?

^

Is there any related good practice or care I should take?

Good practice, I think it would be not to use the short circuit. If using, make sure you understand the order in which expressions are being evaluated and which operator leads to which execution flow. For any language other than shell script, use an if instead.

I could cite examples of where this technique is good?

Shell script. In shell scripts it is common to see lines of the type:

comando argumento1 argumento2 && echo DEU CERTO

Or

comando argumento1 argumento2 || echo DEU ERRADO

In shell, the && and || give a very direct way to react to command return codes.

Edit: Thinking later, I came to another case in which the short circuit can be used clearly and bring advantages in relation to the if, which is within the if itself, when our object can be null. Suppose we have a variable x which has an object with a method f that returns boolean, and we want to check the return of this method in a condition.

We can do it this way:

if (x.f()) {
  // ...
}

But in many languages, objects can be null. When they are, we cannot call it methods, and so we adjust our condition to avoid errors:

if (x != null && x.f()) // ...

Or:

if (x == null || x.f()) // ...

Depending on what we want when x is null. Note that, in expressions of this form, it is very easy to understand the logic behind what is being done, and the short circuit is very intuitive.


Obs.: These things become more evident if we understand as the "implementation" of || and of && the following functions:

function or(a, b) {
  if (a)
    return a;
  else
    return b;
}

function and(a, b) {
  if (!a)
    return a;
  else
    return b;
}
  • Thanks for the time. If I mean well && can be used short-circuited (Decreasing unnecessary code analysis). || can be used as null coalescing (Facilitating assignments that are Truthy)

  • 2

    Yes. Both can be used as short circuits, actually, but the && functions as a if (bool) and the || functions as a if (!bool). The property of null coalescing || comes from the implementation I passed: if the value on the left is false, it returns the value on the right.

  • 3

    I don’t think it’s null coalescing in that case (and "falsy coalescing")... both are short-Circuit Evaluation used for different purposes...

18


What’s the name of it?

Conditional expression. Just this. It does not replace the if and else since these commands are imperative flow control, they do much more than is occurring there. This same code, without changing a single space, can be used normally within a if, including obviously a else if, or it can be used as a value that assigns a variable, or as an argument in a function call, or anywhere that can use an expression. Of course the most correct is where one would expect a boolean value (false or true) to make sense. The if is a place where you expect this, if you assign to a variable then it will be boolean, and if you pass to a function you expect the parameter to be a boolean.

By chance there is still another thing called short circuit that has been widely answered about even why it is so useful that it exists in virtually every language:

Note that those who have short-circuit action are the specific relational operators, it is not the expression as a whole, even some relational operators do not have this characteristic, are specific to two of them.

So because of this the evaluation of a second operand in a || will only be executed if the first operand is false, since if it is true all the expression is already considered true, no matter "look" the other, and by not even executing what has in the other you end up having a conditional execution. With the operator && Otherwise, if the first operand is false the second will not be executed because it no longer has the whole expression to be considered true and it does not even try. Already with | or & the second operand would normally run always, and you could use it the same way you used it in your code with very different results and not reaching the expected goal.

Is it worth using?

It depends on the context, but I see no problem in using this, it exists in the language to be used. People who know how to program, even, use all the time in all kinds of code, is a fantastic programming technique to simplify code. There will always be those who abuse it or never use it.

There are some people who think you should do this:

if (status == true)

The argument is that it is more readable. But it is only readable for those who do not know how to program. Anyone can use this for any reason they want, but taking a value that is already a boolean and making a comparison to generate the same boolean doesn’t make sense, it only does it who is obliged or doesn’t understand what it serves a if (many people don’t understand even using every day). This is so much more readable than this:

return x + 0;

So it becomes more readable that is returning an integer</ironia>

It will make it difficult for others to read?

No, unless the person doesn’t know what this does, then they’ll ask someone, they’ll learn, and they’ll use it normally. You have zero readability problems, if you use it properly it will be readable. It is obvious that it is possible to write this illegible, but it is specific case and it is not because it used the short circuit and it is not because it used the conditional expression outside the if.

If the person does not know this and does not understand, it is not that it was unreadable, it is that the person still does not know how to program. I usually say "If you don’t know what each character of your code does, even the white space, you still don’t know how to program". People can produce applications even without being able to program, but they only master what they’re doing when they understand everything that’s going on there. Even if she had never seen this before in her life if she mastered the process she would know what it is, since she learned the fundamentals. Today people no longer learn the basics, they just decorate cake recipes and this is a problem because they can’t make good codes for the situation.

As I said before, there is no special language mechanism going on there, just something standard being used wisely to achieve a result. Those who understand all aspects of programming read this with extreme ease. Those who have not learned should learn, not run away from it.

Functional style

Some teams may prefer the more imperative style and require the use of the command (if), then it should follow what the team says. Other teams follow the most functional style and then it makes much more sense. Today a lot of people are adopting the most functional style in Javascript and other languages.

Is there any related good practice or care I should take?

Forget about this good practice business. I even have a talk about this. Good practice is cake recipe for those who don’t want to learn how to do it right. Learn the foundation, understand why everything you use, and you won’t need good practices other than as an auxiliary guide. So never ask for good practice, ask for a foundation for something.

Don’t make too complex code, don’t create a logic with multiple nested conditional expressions or even too many comparisons. If you have a very long total expression who knows is the case of breaking in part and storing variables or having functions that make each part. This applies to any conditional expression and not only when using it directly in an expression where one usually expects statement (which is what you did). Mainly take care of parentheses, in some cases put up where you don’t need to make it clearer what will be executed first. This also holds true for any conditional expression anywhere, it is not specific to this use.

I could cite examples of where this technique is good?

I don’t think it’s necessary if you understand what was said above. If you need to perform something conditionally, this form meets what you want, like short codes, or the functional style you can use. Just don’t push it, like everything in programming.

An example I see a lot of people doing:

if (status == true && valor > 10) {
    return true;
} else {
    return false;
}

All this could be just:

return status && valor > 10;

I put in the Github for future reference.

More code to read more illegible becomes. Less code can make it illegible too, but only applies to cases where information relevant to your code is missing, this case lacks something of the language, the if, and readability has to do with the ease of the person who has never seen that code understanding it. The person never having seen something of the language that is her primary tool only indicates that she has not yet learned everything she needed to program, what she should do is not avoid this, is prepare to know what it is next, including because it will pass programming better in general because it understands what a conditional expression is as it was conceived and not by a pre-conceived wrong understanding without foundation.

Browser other questions tagged

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