Andrei Oniga
Andrei Oniga

Reputation: 8559

Javascript array literal operation: what does this line of code do?

What is the purpose and result of the following line?

var arr = arr || [];

Upvotes: 3

Views: 103

Answers (3)

Alex
Alex

Reputation: 35399

Instantiates a new instance of Array if arr is falsy.


In C#, this pattern is referred to as a "null coalescing operation." If you're familiar with C# you'd do something like the following:

string foo = bar ?? String.Empty

Here's a thorough post on the topic.

Upvotes: 3

Pointy
Pointy

Reputation: 413702

It declares the variable "arr" and sets its value to be that of another variable already in existance (presumably in some outer scope), unless that variable is not "truthy" in which case "arr" is set to reference a new empty array.

Thus if the already-existing "arr" has the value null, 0, false, or "", or is undefined, then the local "arr" will be an empty array. Otherwise, it will have the same value as the outer "arr".

You'd usually see that in a situation like this:

var arr;

function whatever() {
  var arr = arr || [];
  ...
}

Sometimes people do this:

function questionable( arr ) {
  var arr = arr || [];

In that case, the var is unnecessary.

This all works because the || operator in JavaScript is distinctly different than it's cousins in other C-like languages. In JavaScript, the value of a || expression is not forced to be a boolean. Instead, it's the value of either its left-hand operand or its right-hand operand. It does inspect the values to determine whether they're "truthy", but that boolean coersion is internal. If the left-hand side is "truthy", then the value of the || expression is that value; otherwise, it's the value of the right-hand side. When the left-hand side is "truthy" the right-hand side is not evaluated at all.

Upvotes: 7

NedStarkOfWinterfell
NedStarkOfWinterfell

Reputation: 5153

Basically in Javascript, and other languages (like Perl for instance), the || is often used as a short-circuit operator. If you have a variable that needs to be assigned the value of one of the 5 other variables, whichever is first defined, you can try something like:

a = b || c || d || e || f;

This will evaluate b. If its value is true, then a will be assigned b, and that's it. If b is found to be false, then the search will propagate to c. Often a variable needs to be compared to itself to check whether to assign a new value. This is what the a = a || b does. Were it Perl, you could have shortened it to a ||= b.

Upvotes: 2

Related Questions