Identify If A Variable Is An Array Or Object In JavaScript

Introduction

 
Hi! Fellow developers, once again, here is another JavaScript article. I often hang out at C# Corner to contribute and read articles. While browsing, I saw this post: “How to check if a JavaScript variable is an array or an object?”. As a result, I decided to create an article regarding it and expand a bit more.
 

Background

 
In this article, as a beginner, you’ll be comfortable as long as you are familiar with objects in JavaScript. However, if you have advanced experience dealing with arrays or objects in JavaScript, you’ll quickly grasp this concept, and I hope you can give some comments below.
 

How to Check If a Variable is an Array?

 
Why is an Array a Special Type of Object?
 
Suppose you have been using JavaScript for a while now. You’ll probably agree that a JavaScript array is a container of any type and numerically indexed. These can be any type, such as boolean, number, string, object, or even an array called a multidimensional array.
 
JavaScript arrays are objects. If you execute the code below, it will return an object as its type.
  1. const pizza = [];  
  2. //output: object  
  3. console.log(typeof(pizza));  
OK, that’s weird. If an array is an object; therefore, JavaScript arrays can have string keys/properties added to them. The answer is yes. However, the string keys/properties don’t add up to the length property of the array. Let’s see an example below.
  1. const pizza = ['pepperoni','double cheese pizza''hawaiian'];  
  2.   
  3. //output: Array of pizza has a length of 3  
  4. console.log('Array of pizza has a length of ' + pizza.length);  
  5.   
  6. //add a new string property to the array  
  7. pizza["hasOnions"] = true;  
  8.   
  9. //output: Array of pizza has a length of 3 after adding a new string property  
  10. console.log('Array of pizza has a length of '+ pizza.length + ' after adding a new string property');  
  11.   
  12. //output: undefined  
  13. console.log(pizza[3]);  
  14.   
  15. //output: [ 'pepperoni', 'double cheese pizza', 'hawaiian', hasOnions: true ]  
  16. console.log(pizza);  
Another confusing feature about array. If a string value is equivalent to an integer/standard base-10 number, then JavaScript assumes that you wanted to use it as a number index rather than a string key/property.
  1. techWriters["10"] = "Mr. Jin Vincent Necesario";  
  2.   
  3. //output: (11) [empty × 10, "Mr. Jin Vincent Necesario"]  
  4. console.log(techWriters);  
  5.   
  6. //output: 11  
If you have seen the sample code above, it is tricky. Hence, this practice isn’t advisable.
 
Two Ways to Check If a Variables is an Array.
 
Using the Object.prototype.toString.call().
  1. /* Start */  
  2. /* Using Object.prototype.toString.call() */  
  3.   
  4. // evaluation: [object Array] is equal to [object Array]  
  5. //output: true  
  6. console.log(Object.prototype.toString.call([]) === '[object Array]');  
  7.   
  8. // evaluation: [object Array] is equal to [object Array]  
  9. //output: true  
  10. console.log(Object.prototype.toString.call(new Array()) === '[object Array]');  
  11.   
  12. // evaluation: [object Object] is not equal to [object Array]  
  13. // output: false  
  14. console.log(Object.prototype.toString.call({}) === '[object Array]');   
  15.   
  16. //evaluation: [object Number] is not equal to [object Array]  
  17. //output: false  
  18. console.log(Object.prototype.toString.call(123) === '[object Array]');   
  19.   
  20. //evaluation: [object Boolean] is not equal to [object Array]  
  21. //output: false  
  22. console.log(Object.prototype.toString.call(true) === '[object Array]');   
  23.   
  24. //evaluation: [object String] is not equal to [object Array]  
  25. //output: false  
  26. console.log(Object.prototype.toString.call('javascript') === '[object Array]');   
  27.   
  28. //evaluation: [object Null] is not equal to [object Array]  
  29. //output: false  
  30. console.log(Object.prototype.toString.call(null) === '[object Array]');   
  31.   
  32. //evaluation: [object Undefined] is not equal to [object Array]  
  33. //output: false  
  34. console.log(Object.prototype.toString.call(undefined) === '[object Array]');  
  35.   
  36. //evaluation: [object Number] is not equal to [object Array]  
  37. //output: false  
  38. console.log(Object.prototype.toString.call(NaN) === '[object Array]');    
  39.   
  40. /* End */  
Using the Array.isArray().
  1. /* Start */  
  2. /*Using Array.isArray()*/  
  3.   
  4. //output:true  
  5. console.log(Array.isArray([]));  
  6.   
  7. //output:true  
  8. console.log(Array.isArray(new Array()));  
  9.   
  10. //output: false  
  11. console.log(Array.isArray({}));   
  12.   
  13. //output: false  
  14. console.log(Array.isArray(123));   
  15.   
  16. //output: false  
  17. console.log(Array.isArray(true)) ;   
  18.   
  19. //output: false  
  20. console.log(Array.isArray('javascript'));   
  21.   
  22. //output: false  
  23. console.log(Array.isArray(null));   
  24.   
  25. //output: false  
  26. console.log(Array.isArray(undefined)) ;  
  27.   
  28. //output: false  
  29. console.log(Array.isArray(NaN)) ;    
  30.   
  31. /* End */  
Before going to the next section, you can quickly check a variable of an array with another code sample below.
  1. function checkIfArray(array){  
  2.       
  3.     return (Array.isArray(array) === true && !array.length);  
  4. }  
  5.   
  6. //output:true  
  7. console.log(Array.isArray([]));  
  8.   
  9. //output:true  
  10. console.log(checkIfArray(new Array()));  
  11.   
  12. //output: false  
  13. console.log(checkIfArray({}));   
  14.   
  15. //output: false  
  16. console.log(checkIfArray(123));   
  17.   
  18. //output: false  
  19. console.log(checkIfArray(true)) ;   
  20.   
  21. //output: false  
  22. console.log(checkIfArray('javascript'));   
  23.   
  24. //output: false  
  25. console.log(checkIfArray(null));   
  26.   
  27. //output: false  
  28. console.log(checkIfArray(undefined)) ;  
  29.   
  30. //output: false  
  31. console.log(checkIfArray(NaN)) ;    

Gotchas of Using instanceof operator

 
I know what you are thinking; why not use instanceof? You are right; instanceof is another good choice when checking if a variable is an array. However, let us see what Mozilla Developer Network has to say about this.
 
 
If you need further reading, you can go here.
 
OK, here we go. The tricky part when using the instanceof operator doesn’t work with multiple contexts like frames or windows. It is because each frame has its execution environment. Thus, each frame has a different global object and different constructors.
 
Let us see an example below. 
  1. const pizza = document.createElement('iframe');  
  2.   
  3. document.body.appendChild(pizza);  
  4.   
  5. const iframeArray = window.frames[window.frames.length-1].Array;  
  6.   
  7. const newPizza = new iframeArray('pizza1','pizza2');  
  8.   
  9. //output: ["pizza1", "pizza2"]  
  10. console.log(newPizza);  
  11.   
  12. //output: false (this is what we are talking about!)  
  13. console.log(newPizza instanceof Array);  
  14.   
  15. //output: true (therefore is much more safer to use Array.isArray() compare to instanceof)  
  16. console.log(Array.isArray(newPizza));  
Now that we have seen the behavior and the decision is for you to decide if the instanceof operator is suitable for your current situation.
 

How to Check If a Variable is an Object?

 
Using the typeof operator
  • To check if a variable is an object, we can use the typeof operator and check if it is not equal to null.
  • The reason for checking if it is null is that it returns an object when passing null into the typeof operator.
Let us see the behavior of the datatype null. See the code sample below.
  1. //output: object  
  2. console.log(typeof(computer));  
  3. //output: true  
  4. console.log(computer === null);  
Now that we understand the null data type. Let us see how to check a variable if it is an object.
  1. const customer = {};  
  2. //output: object;   
  3. console.log(typeof(customer));   
  4.   
  5. //Note: it is better to check if typeof object and not null   
  6. //output: true  
  7. console.log(typeof(customer) === "object" && customer !== null);   
  8.   
  9. const product = null;  
  10. //Note: it is better to check if typeof object and not null   
  11. //output: false  
  12. console.log(typeof(product) === "object" && product !==null);   
Using the Object.prototype.toString.call
  • Another alternative to typeof operator is Object.prototype.toString.call() method.
  • This method returns a string that represents the current object, e.g., Function, Array, etc.
  • However, let’s not forget to use the expression !==null, as discussed in the previous example.
Let us see the examples below.
  1. const customer = {};  
  2.   
  3. //checking customer variable if it is an Object  
  4. //output: true  
  5. console.log(Object.prototype.toString.call(customer) === '[object Object]');  
  6.   
  7. //if [object Object] quite long for you, we can use slice  
  8. //output: true  
  9. console.log(Object.prototype.toString.call(customer).slice(8, -1) === 'Object');  
  10.   
  11. //and by combining the expression !==null  
  12. //output: true  
  13. console.log((Object.prototype.toString.call(customer) === '[object Object]') && customer !==null);  
  14.   
  15. //and by combining the expression !==null with slice  
  16. //output: true  
  17. console.log((Object.prototype.toString.call(customer).slice(8, -1) === 'Object') && customer !==null);  
The difference between the typeof operator and Object.prototype.toString.call
  • The typeof operator returns the type of object in string format. Moreover, you can’t overload this operator.
  • The Object.prototype.toString.call() method returns the string representation of the object. Moreover, you can override it to return anything based on your needs.
Remarks
 
Thank goodness you got this far. As you can see, you have a lot of options for what to use when checking a variable if it is an array or an object. Of course, the decision is all up to you. Hopefully, this post has given you enough practical knowledge and makes you confident when deciding what, when, and how to use these methods and operators in a given situation.
 

Summary

 
This post has started on checking if a variable is an array and given some code samples. We have seen how to check if a variable is an object and given some code samples.
I hope you have enjoyed this article, as I have enjoyed writing it. Stay tuned for more. This article was originally written and posted here. Until next time, happy programming!


Similar Articles