One of the easiest ways we can use JavaScript to check if a variable is an object is by using the JavaScript typeof Operator in an if conditional statement.
if ( typeof someVariable == "object" ){
//The variable IS an object
}
In the code above, someVariable is the variable that we want to check to see if it is an object. typeof someVariable will return “object” if the variable is an object, and therefore the conditional statement will be true.
We can put this code in a function to make checking if a variable is an object very simple.
Here is the function:
function isObject(variable){
if ( typeof variable == "object" ){
return true;
} else {
return false;
}
};
Our function simply returns true if the variable you enter is an object, and false if not.
Now let’s show some examples of this function is use:
function isObject(variable){
if ( typeof variable == "object" ){
return true;
} else {
return false;
}
};
var variable1 = {name:'tom', age:25};
var variable2 = [1,2,3,4];
var variable3 = "1234";
var variable4 = ["Red","Yellow","Green","Blue"];
var variable5 = function isObject(variable){
if ( typeof variable == "object" ){
return true;
} else {
return false;
}
};
var variable6 = {};
console.log(isObject(variable1));
console.log(isObject(variable2));
console.log(isObject(variable3));
console.log(isObject(variable4));
console.log(isObject(variable5));
console.log(isObject(variable6));
#Output:
true
true
false
true
false
true
Hopefully this article has been useful for you to learn how to use JavaScript to check if a variable is an object.