Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is this in javascript: "var var1 = var1 || []"

Tags:

javascript

I just want to increase my core javascript knowledge.

Sometimes I see this statement but I don't know what it does:

var var1 = var1 || [];

What does it means and/or what's it for, and how do you use it?

Thank you.

like image 550
Shaoz Avatar asked Nov 26 '10 00:11

Shaoz


2 Answers

Basically, it looks to see if a variable var1 already exists and is "truthy". If it is, it assigns the local var1 variable its value; if not, it gets assigned an empty array.

This works because the JavaScript || operator returns the value of the first truthy operand, or the last one, if none are truthy. var1 || var2 returns var1 if it's truthy, or var2 otherwise.

Here are some examples:

var somevar;
somevar = 5 || 2; // 5
somevar = 0 || 2; // 2
somevar = 0 || null; // null

Values that aren't "truthy": false, 0, undefined, null, "" (empty string), and NaN. Empty arrays and objects are considered truthy in JavaScript, unlike in some other languages.

like image 146
Sasha Chedygov Avatar answered Oct 04 '22 14:10

Sasha Chedygov


It assigns an empty array to var1, if the boolean representation of it is false (for example it hasn't been initialized).

like image 40
cambraca Avatar answered Oct 04 '22 14:10

cambraca