Operator "||" in JavaScript variables

Question:

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

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

I had never seen the operator || be used outside of an 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 complete 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 || , but I strongly recommend reading the rest of the answers.

Answer:

This is common in functions (and not only) for cases where the function is called without passing any arguments. That is, if nome false (ie it 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 one(s) are not defined or have a boolean value of false . This way it guarantees that the code does not give an error.

So nome = nome || "estranho"; it 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;

That way our new variable, which is a reference to a native function, takes the attachEvent if the addEventListener doesn't exist in this browser.

Scroll to Top