Search code examples
javascriptoopprototype-programmingobject-detection

JavaScript object detection


I am currently practicing javascript and I'm currently having trouble with object detection. I want to create an object and detect whether it exists. Below is some example code I am currently using.

The code sample below is how I am creating my object.

var obj = obj || {};

Should I be using this?

if (typeof obj !== "undefined") {
   // code
}

Or this?

if (obj !== null) {

}

Solution

  • The value undefined means that the variable has not been assigned a value. The value null indicates that it has been assigned the value null. The === operator (and its negation, !==) prevent type coercion.

    Which is right? It all depends on what you are trying to accomplish. Both undefined and null are "falsy" values, meaning that each one evaluates to false in a boolean context (as do false, 0, and the empty string).

    Note that if obj is null, then typeof obj is not "undefined".