Tetraodon
Tetraodon

Reputation: 128

behavior of undefined with respect to objects

So I was playing around with objects and I noticed that for object a = {}

a.b == undefined is true

a.b === undefined is also true

however a.b === (undefined || 'c') is false

Does anyone knows what is the reason for that behavior?

Upvotes: 2

Views: 51

Answers (2)

jsantell
jsantell

Reputation: 1268

a.b === (undefined || 'c')

a.b is undefined like you mentioned.

The || or operator will return its left side if it's true; otherwise it'll return its' right side.

In this case, (undefined || 'c') evaluates to 'c', leaving you with a.b === 'c', which is false.

Upvotes: 2

Andrew Clark
Andrew Clark

Reputation: 208475

undefined || 'c' evaluates to 'c', so a.b === (undefined || 'c') is equivalent to running a.b === 'c', which is clearly false.

Here is the MDN documentation on logical operators for reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators

In particular:

Operator: Logical OR (||)
Usage: expr1 || expr2
Description: Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand is true; if both are false, returns false.

In the case of undefined || 'c', undefined cannot be converted to true so 'c' is returned by the || operator.

Upvotes: 9

Related Questions