Categories
JavaScript Answers

How to efficiently check if variable is Array or Object with Node.js and JavaScript?

Spread the love

Sometimes, we want to efficiently check if variable is Array or Object with Node.js and JavaScript.

In this article, we’ll look at how to efficiently check if variable is Array or Object with Node.js and JavaScript.

How to efficiently check if variable is Array or Object with Node.js and JavaScript?

To efficiently check if variable is Array or Object with Node.js and JavaScript, we can use the util.isArray method.

For instance, we write

const util = require("util");

const isArray = util.isArray([]);
const isArray2 = util.isArray({});

to call util.isArray with an array and an object.

isArray returns true is its argument is an array.

So isArray is true and isArray2 is false.

Conclusion

To efficiently check if variable is Array or Object with Node.js and JavaScript, we can use the util.isArray method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *