I have downloaded a javascript script and one of the first line is :
qq = qq || {};
What does it mean?
It checks qq
for a pre-existing truthy value or else (||
) sets it as an empty object ({}
).
In essence, it's purpose is to quickly ensure that any further references to qq will not be undefined, so you can check for properties of the object without your script breaking due to the fact that the variable isn't even a valid object in the first place.
In JavaScript the ||
(logical-or) operator has this logic-table:
A | B | A || B Truthy | Don't care | A (guaranteed to be Truthy) Falsy | Don't care | B (may be Truthy or Falsy)
(See Truthy and Falsy in JavaScript for what the terms mean.)
Therefor, in the case of qq = qq || {}
:
If qq
initially evaluates to a Falsy value then the result of qq || {}
is {}
and thus ({}
, a Truthy value) is assigned to qq
. Otherwise, qq
was initially a Truthy value and the result of qq || {}
(which is the result of evaluating qq
) is assigned to qq
.
This is an idiomatic guard used to easily protect against "undefined" arguments, properties, and similar.
Some people may prefer to use the following near-equivalent construct instead:
if (!qq) {
qq = {}
}
This latter case, however, will only assign to qq
if qq
was initially Falsy; the form qq = qq || {}
always makes the assignment, but such "overhead" is so trite it should not be used as justification to not use the approach.
Happy coding.
Explanation:
qq = qq || {};
// ^^ is equal to iself, but if it does not exist,
// then it is equal to an empty object
For example:
for(var i = 0; i < 5; i++){
qq = qq || {};
qq[i] = 'something!';
}
Fiddle: http://jsfiddle.net/maniator/dr5Ra/
The answers here so far miss out an important point. The OP says that the script starts with
qq = qq || {};
If so, and if qq
hasn't been declared anywhere (no var qq
at global scope, no window.qq = ...
), that code will throw a ReferenceError
. It will not just default qq
.
In contrast, if the code were:
var qq = qq || {};
That would be very different indeed. It would do this:
The
var qq
part would be processed prior to any step-by-step code in the script. If there is already a globalqq
variable, it will be a no-op. If there isn't, it create a globalqq
variable with the initial valueundefined
.When step-by-step execution reaches that line, the right-hand side of the assignment is evaluated like this:
If
qq
has a "falsey" value (0
,""
,undefined
,false
,NaN
, ornull
), the expressionqq || {}
evalutes to{}
.If
qq
has a "truthy" value (anything not falsey), the expression evalutes toqq
.
(For more details: JavaScript's Curiously-Powerful
||
Operator.)The result of the right-hand-side is assigned to
qq
.
The var
makes a big difference.
qq will receive qq or will be a new object ({}
) if it didn't exist.
精彩评论