I have a simple json parsed object that sometimes has a variable tt defined and sometimes doesn’t.
For some reason jsonobject.tt == null returns correctly 1 or 0 based on whether tt is defined. jasonobject.tt === null just returns 0 regardless. I thought === was the thing to use to avoid issues.
What’s going on here?
===is the strict equality operator, it compares type as well as value. The valuenullis the Null Type that has exactly one value –null.Undefined is the Undefined Type, which also has only one value – ‘undefined’.
When using the strict equality operator, null !== undefined because they are different types (see step 1 of the Strict Equality Comparison Algorithm, ECMA-262 § 11.9.6).
==is the equality operator. Comparisons using==use the Abstract Equality Comparison Algorithm (ECMA-262 § 11.9.3), which includes:So
null == undefinedreturns true by definition. Strictly, testing for the presence of a property (regardless of its value), should use hasOwnProperty:however in practice there isn’t much difference to a strict test for undefined:
because whether the property exists and has a value of undefined or hasn’t been defined at all is usually equivalent. Using
===also means that the above will return false if tt exists but has been assigned a value ofnull.