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) {
}
The value
undefinedmeans that the variable has not been assigned a value. The valuenullindicates that it has been assigned the valuenull. The===operator (and its negation,!==) prevent type coercion.Which is right? It all depends on what you are trying to accomplish. Both
undefinedandnullare “falsy” values, meaning that each one evaluates tofalsein a boolean context (as dofalse,0, and the empty string).Note that if
objisnull, thentypeof objis not"undefined".