Here you will learn how to check whether a variable is a type of Array or an Object in JavaScript.
In the following example, you can see there are three variables (var1
, var2
, var3
) containing three different types of values. But the result shows that all three values are object types –
const var1 = {};
const var2 = [];
const var3 = null;
console.log(typeof var1);
console.log(typeof var2);
console.log(typeof var3);
/* Result is -
object
object
object
*/
How to get the exact type of a value in JS?
JS condition to check if the variable is Array or Object
const val = {name:"John"}
// For Object
if (val !== null && typeof val === "object" && val.constructor === Object) {
// Code will Execute if the value is Object
}
// For Array
if (typeof val === "object" && Array.isArray(val)) {
// Code will Execute if the value is Array
}
Wrapping the logic into the function
const var1 = {};
const var2 = [];
// Checking if value is Object
function isObject(val) {
return (
val !== null && typeof val === "object" && val.constructor === Object
);
}
// Checking if value is Array
function isArray(val) {
return typeof val === "object" && Array.isArray(val);
}
if (isObject(var1)) {
console.log("This is an Object.");
}
if (isArray(var1)) {
console.log("This is an Array.");
}