JS 10 ways to determine whether an object exists or not

  • 2020-03-30 01:02:58
  • OfStack

Javascript language design is not rigorous enough, a lot of things can go wrong.
For example, consider the following.
Now, we need to determine whether a global object, myObj, exists, and if it does not, declare it. The algorithm described in natural language is as follows:


if (myObj There is no ){ 

 The statement myObj; 

  }

You might think it's easy to write this code. But in reality, the syntax is much more complicated than we think. Juriy Zaytsev points out that there are more than 50 ways to tell if a Javascript object exists. It is only possible to tell the difference if you are very clear about the implementation details of the Javascript language.

The first way to write it
Intuitively, you might want to write something like this:


if (!myObj) { 

    myObj = { }; 

  }

However, running this code, the browser throws a ReferenceError directly, causing an outage. What's wrong, please?
By the way, when the if statement determines whether myObj is null, the variable doesn't exist yet, so it reports an error. I'm going to go down here and I'm going to do it right.

if (!myObj) { 

    var myObj = { }; 

  }

Why don't you report an error after adding a var? Does myObj already exist when the if statement makes a judgment in this case?
To answer this question, you must know how the Javascript interpreter works. The Javascript language is "parse first, run later", and the variable declaration is already done when parsing, so the above code is actually equivalent to:

var myObj; 

  if (!myObj) { 

    var myObj = { }; 

  }

Therefore, myObj does exist when the if statement makes its judgment, so it does not report an error. This is the "promotion code" var command (hoisting). The Javascript interpreter only "promotes" the variables defined by the var command. It does not affect the variables that are directly assigned without the var command, which is why the error is reported without var.

The second way
In addition to the var command, there is another rewrite that can also get the correct result:


if (!window.myObj) { 

    myObj = { }; 

  }

Window is the top-level object in javascript, and all global variables are its properties. Therefore, determining whether myobj is null is equivalent to determining whether the window object has a myobj attribute, so as to avoid ReferenceError because myobj is not defined. However, for normative reasons, it is best to add var to the second line:

    if (!window.myObj) { 

        var myObj = { }; 

      } 

 Or write it like this:  

      if (!window.myObj) { 

        window.myObj = { }; 

      }

The third way
The disadvantage of this approach is that in some runtime environments (such as V8 and Rhino), a window is not necessarily a top-level object. So, consider rewriting it as:

if (!this.myObj) { 

    this.myObj = { }; 

  }

At the global variable level, this keyword always points to the top-level variable, so it can be independent of the different runtime environments.

The fourth way
However, the above is not readable, and the point of this is variable and prone to errors, so rewrite it further:

var global = this; 

  if (!global.myObj) { 

    global.myObj = { }; 

  }

Using the custom variable global to represent the top-level object is much clearer.

Number five
You can also use the typeof operator to determine whether myObj is defined.


if (typeof myObj == "undefined") { 

    var myObj = { }; 

  }

This is the most widely used method to determine the existence of javascript objects.

The sixth way
Since the value of myObj is directly equal to undefined in defined but unassigned cases, the above notation can be simplified:


if (myObj == undefined) { 

    var myObj = { }; 

  }

There are two things to note here. First, the var keyword in the second line should not be too small, otherwise there will be a ReferenceError. Second, undefined should not be quoted in single or double quotes, because the data type undefined is compared here, not the string "undefined".

The seventh way
The above formula is still true in the case of "exact comparison" (===) :


if (myObj === undefined) { 

    var myObj = { }; 

  }

The eighth way
According to the javascript language design, undefined == null, so the correct result can be obtained by comparing whether myObj is equal to null:

if (myObj == null) { 

    var myObj = { }; 

  }

However, while the results are correct, this is semantically wrong and should be avoided. Since null refers to an empty object that has been assigned a value of null, that is, the object actually has a value, undefined refers to an object that does not exist or has no value assigned. Therefore, you can only use the "comparison operator" (==). If you use the "exact comparison operator" (===), you will make an error.

Number nine
You can also use the in operator to determine whether myObj is an attribute of the top-level object:


if (!('myObj' in window)) { 

    window.myObj = { }; 

  }

Number ten
Finally, the hasOwnProperty method is used to determine whether myObj is a property of the top-level object:

if (!this.hasOwnProperty('myObj')) { 

    this.myObj = { }; 

  }

conclusion
1. If you only determine the existence of an object, the fifth method is recommended.

2. The first method is recommended to determine whether an object has a null value in addition to its existence.

3. All variables should be declared using the var command except in special cases.

4. In order to cross platforms, it is recommended to avoid using window to represent top-level objects.

5. In the Javascript language, null and undefined are easily confused. Where both may be involved, the "exact comparison" operator (===) is recommended.


Related articles: