Operator "||" in JavaScript variables


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

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

I've never seen the || operator be used outside a if() , so 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 provide details that are complete. Since only one can be chosen as "correct" I have chosen the one that brought, in addition to the explanation, a list of what is considered false or true by the || operator, but I strongly recommend reading the other answers.

asked by anonymous 24.10.2014 / 14:57

5 answers


On a similar answer , I explained what this operation means. It is called colscence . Here is an excerpt from 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 be treated logical form, that is, converted to true or false. As for the operation above, when the valorA value is treated as true, the result of the expression is its own value. When it is treated as false, the result of expression is the valorB value.

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

What's fake:

  • empty string: ""
  • number 0 (zero)
  • false
  • null
  • undefined
  • NaN

What's true:

  • everything that is not false ... including the following
  • Non-empty strings: "0", "true", "false"
  • all different numbers than 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
24.10.2014 / 17:38

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

Then 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 rather attachEvent. Often, it is done:

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

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

24.10.2014 / 15:00

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

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

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

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

    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
    24.10.2014 / 21:19

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

    • Rate% with%; if it is not evaluated as one of the "false" logical values, return a ;
    • Otherwise, return a .

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

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

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

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

    The interpreter will generally understand how:

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

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

    Something similar happens with the || "estranho" operator. The difference is that the logical "e" returns the first element that is logically false, or the last one to the right if they are all logically true. It is the inverse of the "or".

    24.10.2014 / 21:39

    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, return 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" .

    24.10.2014 / 21:30