Matthew Pitts
Matthew Pitts

Reputation: 859

Javascript Logical OR and Objects

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

Answers (3)

Arun P Johny
Arun P Johny

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.

  • 1 || 0 -> 1
  • 1 && '' -> ''

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

Rob Johansen
Rob Johansen

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

Andrew Eisenberg
Andrew Eisenberg

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:

  1. A false literal
  2. The number 0
  3. null
  4. undefined
  5. An empty string

If the property has any of these values, it will be reassigned to an empty object.

Upvotes: 1

Related Questions