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.
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.
It assigns an empty array to var1
, if the boolean representation of it is false (for example it hasn't been initialized).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With