Operator "||" in Javascript variables

Asked

Viewed 910 times

24

Recently reading the plugin code, I noticed the definition of variables and objects using the operator || of Javascript. Example:

function ola(nome){
    nome = nome || "estranho";
    return "Olá, " + nome;
}

I’ve never seen the operator || be used outside a if(), then my question is, under what circumstances does the "or" operator work when defining variables? How do I know what would return after the "or"?

Note: Most of the answers below are correct and bring details that complement each other. As only one can be chosen as "correct" I chose the one that brought, in addition to the explanation, a list with what is considered false or true by the operator ||, but I highly recommend reading the other answers.

5 answers

20

This is common in functions (and not only) for cases where the function is called without arguments being passed. That is if nome der false (ie not closed), so it takes the value it is after ||. The second value can be said to be a default value that is taken if the previous value(s) (s) are not closed or have a boolean value false. This way ensures that the code does not give error.

So nome = nome || "estranho"; is the same as:

if (nome) nome = nome;
else nome = "estranho"

A good example is how to listen to the mousewheel Event

Another example: in older versions of IE there was no addeventlistener, but attachEvent. Often it is done:

var addEvent = document.addEventListener || document.attachEvent;

Thus our new variable, which is a reference to a native function, assumes the attachEvent if the addEventListener does not exist in that browser.

  • It’s almost a if ternary then? How variavel == null ? doSomething() : doSomethingElse()?

  • 2

    @Gustavocinque: exactly. valorA || valorB is exactly the same as valorA ? valorA : valorB.

17


In a similar response, I explained what this operation means. It is called colescence. There goes an excerpt of this answer that answers your question (your question, however, is not a duplicate):

The code below:

var resultado = valorA || valorB;

is exactly the same as:

var resultado = valorA ? valorA : valorB;

It turns out that in javascript, virtually all values can treated logical form, ie converted to true or false. As for the operation previous, when the value valorA is treated as true, the result of expression is its own value. When it is treated as false, the result of expression is the value valorB.

We must then understand what is treated as true and as false.

What is false:

  • empty string: ""
  • number 0 (zero)
  • false
  • null
  • Undefined
  • Nan

What is true:

  • all that is not false... including the following
  • empty strings: "0", "true", "false" (it is important to remember this)
  • all numbers different from 0: 1, -1, -1000, 1/10
  • true

Some examples

false || "texto qualquer"     // "texto qualquer"
"" || "texto qualquer"        // "texto qualquer"
0 || "texto qualquer"         // "texto qualquer"
null || "texto qualquer"      // "texto qualquer"
undefined || "texto qualquer" // "texto qualquer"

"algum texto" || "texto qualquer" // "algum texto"
1 || "texto qualquer"             // 1

5

This is used to assign standard values to variables. There are 3 contributing factors to this:

  1. Javascript expressions always return a value. So nome || "estranho", being an expression, returns something - which in your example will be used as the value assigned to a variable.

  2. A characteristic of the logical operator || in the language is what he does short-circuiting, that is, it abandons the interpretation of what is to the right of the operator if the left part is already true.

  3. Empty strings are considered Truthy, that is, they act as true in logical/boolean operations.

See the consequences of all this in the following two code blocks:

var x = "um nome" || "estranho"; 
// "estranho" é ignorado via short-circuiting pois "um nome" é truthy
// equivale a var x = "um nome"
var x = "" || "estranho"; 
// x = "estranho"
// "" é falsey, então || retorna o valor à direita

4

In Javascript, an expression like a || b is interpreted as follows::

  • Evaluate a; if not evaluated as one of the "false" logical values, return a;
  • If not, come back b.

The values that are considered false for this type of logic are: null (null), undefined (undefined), explicit false (false), empty string (""), zero and Not a Number (NaN).

This code in the question serves to ensure that the variable nome will be filled. Assuming it is initialized with the value null - without this treatment, you could return Olá, null. Try running the code without the part || "estranho". ;)

Note that expressions with or logical can be chained together. When you have something like:

a || b || c || d || e;

The interpreter, in general, will understand how:

a || (b || (c || (d || e)));

This will return the first element of the series that is not evaluated as a logical false. But if they are all false logic, the last element will be returned.

Something similar occurs with the operator &&. The difference is that the logical "e" returns the first element that is logically false, or the last one right if they are all logically true. It’s the reverse of "or".

2

In javascript the operator || will evaluate the expression and return the first value that is not evaluated as false. If you do not find any returns the rightmost element.

Values that are considered false in javascript: "", false, 0, undefined, null, NaN In the expression: nome || "estranho" the logic is as follows: if nome is different from the values listed above, it will return nome. Otherwise it will evaluate the next value in this case, "estranho".

Browser other questions tagged

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