Difference between && and ||

6

I would like to know the difference between:

window.RM = window.RM || {};

E:

window.RM = window.RM && {};

Maybe the examples are not correct, but I would like to know the difference between the && and || operators in examples similar to those quoted above.

Note: I already know how to use them in conditions and similar, but I do not know how to differentiate them in cases like the ones above.

    
asked by anonymous 04.02.2018 / 01:54

4 answers

6

This is called Short-circuit evaluation .

When you use the && (AND) operator, only the value of the second argument will be assumed if the first argument is true :

window.RM = window.RM && {};
// resultado: "undefined", porque window.RM não tem valor.

What is it to be true?

Other than empty, null , 0 and false .

window.RM = 0;
window.RM = window.RM && {};
// resultado: "0", porque window.RM é igual a zero.

Another example:

window.RM = '0';
window.RM = window.RM && {};
// resultado: "{}", porque window.RM é igual a zero, mas zero é uma string e não um número.

In the || (OR) operator, it is the opposite, where the first argument must be false to assume the value of the second:

window.RM = 0;
window.RM = window.RM || {};
// resultado: "{}", porque window.RM é igual a zero.

Another example:

window.RM = window.RM || {};
// resultado: "{}", porque window.RM não possui valor, é "undefined".

And one more:

window.RM = true;
window.RM = window.RM || {};
// resultado: "true", porque window.RM é true, contrário de false.

In short, && asks for the argument to the left if it is true, if it says yes, it takes the one from the right. The || asks left if it is false, if it answers yes, get the one from the right.

    
04.02.2018 / 02:35
8
  

My searches for an answer to this question were unsuccessful, you should be using the wrong words. So there goes an answer

These operators you refer to are boolean operators. This means that they operate within the mathematical universe called "Boolean Algebra". This algebra differs from our traditional algebra because it does not work with numbers, but only with two values.

This algebra works on 3 axioms:

  • identity law ( a == a always)
  • law of non-contradiction (nothing can be and not be at the same time)
  • Third party's deleted law (either you are truthful or false, can not be something in between, a third value)

Read more here .

The used operators are && "E" and "%" of% "OU".

They work in a certain way, which can be seen in truth tables . Note how the result depends on the first variable.

  • If the first variable is false, the "E" will be false as a whole; otherwise it will be the value of the second variable
  • If the first variable is false, the "OU" will have the value of the second variable; otherwise, just know that the first variable is true

So JavaScript works like this for your Boolean operators. Even if it can already determine the value of the Boolean expression by looking only at the first operand, it does not even go beyond calculating the value of the second operand. The name of this strategy of not computing unnecessary things is "short circuit."

But in case you are not working with true values. Or is? See, in JavaScript, they get more light on the type of the object. You may not be dealing with Booleans, but your values may be "true-malformed" or "falsiform." (Not to be confused with "sickle-cell").

One thing with "true form" is called truthy in JavaScript, and for everything involving Boolean expressions, they are considered to be true.

You can find out more about these terms in answers .

So what's going on?

In case of "E", if || is truthy , the expression will return window.RM , otherwise it will return {} itself. Since this is being assigned to the variable window.RM , this seems to be a way to "zero" the object if it has any value.

In the case of "OU", it seems like a kind of initialization of the object window.RM , since its value is only overwritten with window.RM if it already falsy , otherwise is truthy ) it does not have its value changed.

    
04.02.2018 / 02:38
2

These operators are used in comparisons, the value on the right will be used:

  • (case || ) when the boolean value of the comparator on the left gives false
  • (case && ) when the boolean value of the comparator on the left gives true

It can also be said:

  • (case || ) the first value to validate as true its Boolean value will be returned (evaluating from left to right), or false if both fail

  • >
  • (case && ) the value of the second operand (right) will be returned if the Boolean value of the first operand is true , even if the boolean value of the right operand is false , it will be returned. (That is: true && '' returns '' and not false )

In the specific case of the examples you display:

  • || functions as fallback , ie if the value on the left does not exist (validate as false ) the result of this assignment will be an empty object.

  • && will be used and assigned window.RM if the value to the left of && resolves to true . If the value to the left does not validate the assignment will be with the value of the first operand (which has the Boolean value false ).

Examples:

false || 25 // 25 (o primeiro falha, o segundo é usado pois valida como 'true', o valor final é 25)
true  || false // true (o primeiro é usado, o segundo é ignorado, o valor final é 25)
false || false // false (o primeiro falha, o segundo falha)

false && true // true (o primeiro falha, o segundo é ignorado pois o primeiro já falhou)
true  && 25 // 25 (o primeiro valida, o segundo é retornado, o valor final é 25)
true  && false // false (o primeiro passa, o segundo falha, o resultado é 'false')
null  && true // null (note-se que retorna 'null' e não 'false')
    
04.02.2018 / 15:28
0

Logical operators

Logical operators return true (V) or false (F) according to their operands.

Logicaloperatorsarealsoknownasconnectives,astheyareusedtoformnewpropositionsfromthejunctionoftwoothers.Inordertounderstandtheoperationoflogicaloperators,wewillusetheourexampleoftheintegervariables,AandBwhereA=5andB=8.Thetablebelowdisplaysexamplesofexpressionsthatuselogicaloperators.

You may have noticed from previous examples:

  • When we use the logical operator E ( & & ), the result will only be true if the two related conditions are true;
  • for the OR operator ( || ), it is enough that one of the conditions is true for that the result is true;
  • Consequently: with the OR ( || ) operator, so that the result is false two conditions must be false.
05.02.2018 / 11:00