8

Identify If a Variable is an Array or Object in JavaScript

 3 years ago
source link: https://jinnecesario.com/2020/10/22/identify-if-a-variable-is-an-array-or-object-in-javascript/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Introduction

Hi! Fellow developers, once again, another article (from your very own Mr. Jin Vincent Necesario). 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.  

Disclaimer

The view and opinions expressed in this post are my analysis and not sponsored by anyone. Lastly, the source codes written here are just examples and are as-is.  

Table of Contents

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 an Array is 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.

const pizza = [];
//output: object
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.

const pizza = ['pepperoni','double cheese pizza', 'hawaiian'];
//output: Array of pizza has a length of 3
console.log('Array of pizza has a length of ' + pizza.length);
//add a new string property to the array
pizza["hasOnions"] = true;
//output: Array of pizza has a length of 3 after adding a new string property
console.log('Array of pizza has a length of '+ pizza.length + ' after adding a new string property');
//output: undefined
console.log(pizza[3]);
//output: [ 'pepperoni', 'double cheese pizza', 'hawaiian', hasOnions: true ]
console.log(pizza);

Another confusing feature about array. If a string value is equivalent to an integer/standard base-10 number, the JavaScript assumes that you wanted to use it as a number index rather than a string key/property.

const techWriters = [];
techWriters["10"] = "Mr. Jin Vincent Necesario";
//output: (11) [empty × 10, "Mr. Jin Vincent Necesario"]
console.log(techWriters);
//output: 11
console.log(techWriters.length);

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().

/* Start */
/* Using Object.prototype.toString.call() */
// evaluation: [object Array] is equal to [object Array]
//output: true
console.log(Object.prototype.toString.call([]) === '[object Array]');
// evaluation: [object Array] is equal to [object Array]
//output: true
console.log(Object.prototype.toString.call(new Array()) === '[object Array]');
// evaluation: [object Object] is not equal to [object Array]
// output: false
console.log(Object.prototype.toString.call({}) === '[object Array]');
//evaluation: [object Number] is not equal to [object Array]
//output: false
console.log(Object.prototype.toString.call(123) === '[object Array]');
//evaluation: [object Boolean] is not equal to [object Array]
//output: false
console.log(Object.prototype.toString.call(true) === '[object Array]');
//evaluation: [object String] is not equal to [object Array]
//output: false
console.log(Object.prototype.toString.call('javascript') === '[object Array]');
//evaluation: [object Null] is not equal to [object Array]
//output: false
console.log(Object.prototype.toString.call(null) === '[object Array]');
//evaluation: [object Undefined] is not equal to [object Array]
//output: false
console.log(Object.prototype.toString.call(undefined) === '[object Array]');
//evaluation: [object Number] is not equal to [object Array]
//output: false
console.log(Object.prototype.toString.call(NaN) === '[object Array]'); 
/* End */

Using the Array.isArray().

/* Start */
/*Using Array.isArray()*/
//output:true
console.log(Array.isArray([]));
//output:true
console.log(Array.isArray(new Array()));
//output: false
console.log(Array.isArray({}));
//output: false
console.log(Array.isArray(123));
//output: false
console.log(Array.isArray(true)) ;
//output: false
console.log(Array.isArray('javascript'));
//output: false
console.log(Array.isArray(null));
//output: false
console.log(Array.isArray(undefined)) ;
//output: false
console.log(Array.isArray(NaN)) ; 
/* End */

Before going to the next section, you can quickly check a variable of an array with another code sample below.

function checkIfArray(array){
return (Array.isArray(array) === true && !array.length);
}
//output:true
console.log(Array.isArray([]));
//output:true
console.log(checkIfArray(new Array()));
//output: false
console.log(checkIfArray({}));
//output: false
console.log(checkIfArray(123));
//output: false
console.log(checkIfArray(true)) ;
//output: false
console.log(checkIfArray('javascript'));
//output: false
console.log(checkIfArray(null));
//output: false
console.log(checkIfArray(undefined)) ;
//output: false
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.

Identify If a Variable is an Array or Object in JavaScript

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.

const pizza = document.createElement('iframe');
document.body.appendChild(pizza);
const iframeArray = window.frames[window.frames.length-1].Array;
const newPizza = new iframeArray('pizza1','pizza2');
//output: ["pizza1", "pizza2"]
console.log(newPizza);
//output: false (this is what we are talking about!)
console.log(newPizza instanceof Array);
//output: true (therefore is much more safer to use Array.isArray() compare to instanceof)
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.

const computer = null;
//output: object
console.log(typeof(computer));
//output: true
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.

const customer = {};
//output: object;
console.log(typeof(customer));
//Note: it is better to check if typeof object and not null
//output: true
console.log(typeof(customer) === "object" && customer !== null);
const product = null;
//Note: it is better to check if typeof object and not null
//output: false
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.

const customer = {};
//checking customer variable if it is an Object
//output: true
console.log(Object.prototype.toString.call(customer) === '[object Object]');
//if [object Object] quite long for you, we can use slice
//output: true
console.log(Object.prototype.toString.call(customer).slice(8, -1) === 'Object');
//and by combining the expression !==null
//output: true
console.log((Object.prototype.toString.call(customer) === '[object Object]') && customer !==null);
//and by combining the expression !==null with slice
//output: true
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. Until next time, happy programming! Please don’t forget to follow/subscribe, bookmark, like, and comment. Cheers! And Thank you!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK