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 || [];
The logical operators in JavaScript actually evaluate to one of the two objects. When you use a || b
it evaluates to b
if a
is false, or to a
if a
is true. Thus a || []
will be a
if a
is any value that is true, or []
if a
is any value that is false.
It's much more obvious to use if (!a) { a = [] };
Javascript or (||) works a bit differently to some other languages, it returns the first "truthy" value instead of a boolean. This is being used in this case to say "Set the value of var1 to var1
, but if that value is "falsey" set it to []
".
This is often used to set a "default" value to a variable that may or may not be set already, such as an argument to a function.
The ||
operator evaluates the first of its operands that is "truthy".
[]
is an empty array. ([ "Hi!" ]
is an array of one string)
Therefore, the expression x || []
evaluates to x
if it's "truthy" or an empty array if it isn't.
This allows the var1
parameter to be optional.
While this has been pointed out as 'being a silly statement', I present the following two counters:
(Just to keep people on their toes and reinforce some of the "finer details" of JavaScript.)
1)
var
is the variable is already local
. E.g.
function x (y) {
var y = y || 42 // redeclaration warning in FF, however it's "valid"
return y
}
x(true) // true
x() // 42
2)
var
is function-wide annotation (it is "hoisted" to the top) and not a declaration at the point of use.
function x () {
y = true
var y = y || 42
}
x() // true
I do not like code like either of the preceding, but...
Because of the hoisting, and allowed re-declarations, the code in the post has these semantics:
var var1
if (!var1) {
var1 = []
}
Edit I am not aware of how "strict mode" in Ed.5 influences the above.
Basically if var1
is NULL
or false
, var1
will be set to an empty array
.
The statement assigns an empty array to var1.
longer answer and explanation:
This happens because var1 is not initialized at that time. Non-initialized is a falsy value.
take this statement:
var1 = var1 || [];
If var1 is not initialized it becomes an empty array, it if is an empty array nothing happens as its assigned to an empty array, if var1 is false
, null
, or any other value that javascript things of as false, it becomes an empty array, if var1 is anything other value, nothing happens as it is assigned to itself. (thanks pst for the link).
In short, its a stupid statement that's neither readable nor useful, but you're smart for wanting to know what it means. :)