Reputation: 859
Can someone explain everything that's happening in a statement like this:
POJO.someProperty = POJO.someProperty || {}
Is this checking for undefined then simply assigning an empty object if undefined = true?
Upvotes: 2
Views: 2162
Reputation: 388316
The logical operators in javasript can return non boolean values. The Logical OR operator will return the first truthy value it finds in the operands. The Logical AND will return the first falsy value, or the last operand if all other operands are truhty.
Logical operators are typically used with Boolean (logical) values. When they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value.
So when your code is evaluated if POJO.someProperty
is undefined then the operator will process the second operator which is an empty object(which is a truthy value) so that value will be returned and assigned back to someProperty
.
Why is it used, it is used normally to escape the property not defined error. Assume you are trying to access a property of POJO.someProperty
, like POJO.someProperty.somekey
but then if POJO.someProperty
is undefined then you will get an error. But here if it is undefined then we are assigning an empty object so POJO.someProperty.somekey
will return undefined not an error.
Upvotes: 3
Reputation: 5164
In JavaScript, as in C, the value of an assignment expression is the value of the right-side operand. In the example you provided, the expression on the right side of the assignment is evaluated before the assignment happens. Because it's a logical OR, it will evaluate to an object literal {}
if POJO.someProperty
is falsy.
You might see assignment expressions used like this in other places too (notice the single equal sign in the if
expression):
var x = 1;
var y = 0;
if (y = x) {
// This block executes because x is 1 (also, y is now 1)
}
Upvotes: 0
Reputation: 28737
This statement is checking to see if POJO.someProperty
has a truthy value. If it does, then nothing happens. If the property is falsy, then the property is assigned an empty object literal.
Falsy means one of several things:
false
literalnull
undefined
If the property has any of these values, it will be reassigned to an empty object.
Upvotes: 1