Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the construct x = x || y mean?

People also ask

What does X || Y mean?

Now, when you know how || operator works, you can probably make out by yourself what does x = x || y mean. If x is truthy, x is assigned to x , so actually nothing happens; otherwise y is assigned to x . It is commonly used to define default parameters in functions.

What does || mean in JS?

The logical OR ( || ) operator (logical disjunction) for a set of operands is true if and only if one or more of its operands is true. It is typically used with boolean (logical) values. When it is, it returns a Boolean value.

What does options mean in JavaScript?

An options object is a normal JavaScript object that contains a set of named parameters that are passed into a function. For example, the jQuery. ajax function uses an options object. This function can take up to 34 parameters, all of which are optional.

What does the operator do in JavaScript?

The JavaScript in operator is used to check if a specified property exists in an object or in its inherited properties (in other words, its prototype chain). The in operator returns true if the specified property exists. Anatomy of a simple JavaScript object.


It means the title argument is optional. So if you call the method with no arguments it will use a default value of "Error".

It's shorthand for writing:

if (!title) {
  title = "Error";
}

This kind of shorthand trick with boolean expressions is common in Perl too. With the expression:

a OR b

it evaluates to true if either a or b is true. So if a is true you don't need to check b at all. This is called short-circuit boolean evaluation so:

var title = title || "Error";

basically checks if title evaluates to false. If it does, it "returns" "Error", otherwise it returns title.


What is the double pipe operator (||)?

The double pipe operator (||) is the logical OR operator . In most languages it works the following way:

  • If the first value is false, it checks the second value. If that's true, it returns true and if the second value is false, it returns false.
  • If the first value is true, it always returns true, no matter what the second value is.

So basically it works like this function:

function or(x, y) {
  if (x) {
    return true;
  } else if (y) {
    return true;
  } else {
    return false;
  }
}

If you still don't understand, look at this table:

      | true   false  
------+---------------
true  | true   true   
false | true   false  

In other words, it's only false when both values are false.

How is it different in JavaScript?

JavaScript is a bit different, because it's a loosely typed language. In this case it means that you can use || operator with values that are not booleans. Though it makes no sense, you can use this operator with for example a function and an object:

(function(){}) || {}

What happens there?

If values are not boolean, JavaScript makes implicit conversion to boolean. It means that if the value is falsey (e.g. 0, "", null, undefined (see also All falsey values in JavaScript)), it will be treated as false; otherwise it's treated as true.

So the above example should give true, because empty function is truthy. Well, it doesn't. It returns the empty function. That's because JavaScript's || operator doesn't work as I wrote at the beginning. It works the following way:

  • If the first value is falsey, it returns the second value.
  • If the first value is truthy, it returns the first value.

Surprised? Actually, it's "compatible" with the traditional || operator. It could be written as following function:

function or(x, y) {
  if (x) {
    return x;
  } else {
    return y;
  }
}

If you pass a truthy value as x, it returns x, that is, a truthy value. So if you use it later in if clause:

(function(x, y) {
  var eitherXorY = x || y;
  if (eitherXorY) {
    console.log("Either x or y is truthy.");
  } else {
    console.log("Neither x nor y is truthy");
  }
}(true/*, undefined*/));

you get "Either x or y is truthy.".

If x was falsey, eitherXorY would be y. In this case you would get the "Either x or y is truthy." if y was truthy; otherwise you'd get "Neither x nor y is truthy".

The actual question

Now, when you know how || operator works, you can probably make out by yourself what does x = x || y mean. If x is truthy, x is assigned to x, so actually nothing happens; otherwise y is assigned to x. It is commonly used to define default parameters in functions. However, it is often considered a bad programming practice, because it prevents you from passing a falsey value (which is not necessarily undefined or null) as a parameter. Consider following example:

function badFunction(/* boolean */flagA) {
  flagA = flagA || true;
  console.log("flagA is set to " + (flagA ? "true" : "false"));
}

It looks valid at the first sight. However, what would happen if you passed false as flagA parameter (since it's boolean, i.e. can be true or false)? It would become true. In this example, there is no way to set flagA to false.

It would be a better idea to explicitly check whether flagA is undefined, like that:

function goodFunction(/* boolean */flagA) {
  flagA = typeof flagA !== "undefined" ? flagA : true;
  console.log("flagA is set to " + (flagA ? "true" : "false"));
}

Though it's longer, it always works and it's easier to understand.


You can also use the ES6 syntax for default function parameters, but note that it doesn't work in older browsers (like IE). If you want to support these browsers, you should transpile your code with Babel.

See also Logical Operators on MDN.


If title is not set, use 'ERROR' as default value.

More generic:

var foobar = foo || default;

Reads: Set foobar to foo or default. You could even chain this up many times:

var foobar = foo || bar || something || 42;

Explaining this a little more...

The || operator is the logical-or operator. The result is true if the first part is true and it is true if the second part is true and it is true if both parts are true. For clarity, here it is in a table:

 X | Y | X || Y 
---+---+--------
 F | F |   F    
---+---+--------
 F | T |   T    
---+---+--------
 T | F |   T    
---+---+--------
 T | T |   T    
---+---+--------

Now notice something here? If X is true, the result is always true. So if we know that X is true we don't have to check Y at all. Many languages thus implement "short circuit" evaluators for logical-or (and logical-and coming from the other direction). They check the first element and if that's true they don't bother checking the second at all. The result (in logical terms) is the same, but in terms of execution there's potentially a huge difference if the second element is expensive to calculate.

So what does this have to do with your example?

var title   = title || 'Error';

Let's look at that. The title element is passed in to your function. In JavaScript if you don't pass in a parameter, it defaults to a null value. Also in JavaScript if your variable is a null value it is considered to be false by the logical operators. So if this function is called with a title given, it is a non-false value and thus assigned to the local variable. If, however, it is not given a value, it is a null value and thus false. The logical-or operator then evaluates the second expression and returns 'Error' instead. So now the local variable is given the value 'Error'.

This works because of the implementation of logical expressions in JavaScript. It doesn't return a proper boolean value (true or false) but instead returns the value it was given under some rules as to what's considered equivalent to true and what's considered equivalent to false. Look up your JavaScript reference to learn what JavaScript considers to be true or false in boolean contexts.