Ways to check existence of JavaScript object

  é˜®ä¸€å³°        2020-09-12 02:14:02       55,398        1    

The design of JavaScript is not so sophisticated. It's very easy for us to make mistakes if we are not very careful when using JavaScript. For example, to check the existence of JavaScript object.

Now we want to check whether a global object myObj exists or not, if it doesn't exist, we declare it. The pseudo code for this is :

if(myObj not exist){
	declare myObj;
}

You may think it's very easy to write the code. In fact, it is much more difficult than we may think.
Juriy Zaytsev says there are more than 50 ways to check whether a JavaScript object exist or not. Only if you are very clear about the JavaScript realization detail, you can distinguish different methods.

1. We can write it as

if (!myObj) {
	myObj = { };
}

However, the web browser will throw the ReferenceError when executing this code snippet. What goes wrong?

The problem is when the if statement check the existence of myObj, this variable doesn't exist, so it will throw the error. Modify it as :

if (!myObj) {
	var myObj = { };
}

What is the reason for not throwing the error after adding the var keyword? In this situation, when executing the if statement, does myObj variable exist? To answer this question, we need to understand how JavaScript interpreter works. JavaScript will first parse and then execute the code. So the declaration of the variable will be completed when parsing the code. So the above code equals to :

var myObj;
if (!myObj) {
	var myObj = {};
}

Hence when if statement is executed, myObj variable does exist. This is code hoisting of var. The JavaScript interpreter will only only hoist the variable defined with var.

2. Besides var, we can rewrite it as:

if (!window.myObj) {
	myObj = {};
}

window is the top-level object of JavaScript. All global variables are its properties, so to check whether myObj exists, it is the same as checking whether window has the property myObj. This can avoid the problem of ReferenceError because of undefined myObj variable. However, we'd better add a var on the second line of the code:

if (!window.myObj) {
	var myObj = { };
}

or

if (!window.myObj) {
	window.myObj = {};
}

3. The problem of the second method is on some execution environment such as V8 and Rhino, window may not be the top-level object. So we should write the above code as

if (!this.myObj) {
	this.myObj = { };
}

for global variables, this will always point to top-level variables. So it is independent of execution environment.

4. The readability of the third method is not so good, also this can point to different objects, it's easy to make mistakes. So we can rewrite it as

var global = this;
if (!global.myObj) {
	global.myObj = {};
}

5. Also we can use typeof to check whether myObj is defined or not

if (typeof myObj == "undefined") {
	var myObj = {};
}

this is the most widely used method to check whether a JavaScript object exists or not.

6. The initial value of myObj should be undefined if it is not initialized. So we can simplify the method 5 as

if (myObj == undefined) {
	var myObj = {};
}

here we need to take care of two points. One is the keyword var cannot be omitted, otherwise it will incur the ReferenceError; the other one is we cannot add single quote or double quote to the undefined keyword because here we compared the undefined datatype, not the "undefined" string.

7. Use strict equal(===) to compare, it is also working

if (myObj === undefined) {
	var myObj = {};
}

8. According to the design of JavaScript, undefined==null, so we can check whether myObj==null.

if (myObj == null) {
	var myObj = {};
}

the result is correct, but semantically, this method is wrong, we should avoid it. Since null refers to the empty object which is assigned with null, i.e, this object does exist, while undefined referes to the object which doesn't exist or is not assigned. Hence, here we can only use "==" instead of "===".

9. We can use in operator

if (!('myObj' in window)) {
	window.myObj = { };
}

10. Use hasOwnProperty method

if (!this.hasOwnProperty('myObj')) {
	this.myObj = { };
}

Conclusion

  1. If we only need to check whether an object exist, we recommend method 5
  2. If we still need to check whether the object is null except check the existence of the objec, we recommend method 1
  3. All variables should be declared using var keyword
  4. For cross-browser compatibility, avoid using window to refer to the top-level object
  5. In JavaScript, null and undefined are easy to be mixed up. When dealing with these two, we recommend to use === operator

Reference : http://www.ruanyifeng.com/blog/2011/05/how_to_judge_the_existence_of_a_global_object_in_javascript.html

EXISTENCE  OBJECT  JAVASCRIPT 

       

  RELATED


  1 COMMENT


Carl [Reply]@ 2018-02-20 14:19:12

Just thought I'd say thanks: this article clarified the point beautifully for a JS beginner.



  RANDOM FUN

It still works