check if something is object javascript code example
Example 1: javascript check if variable is object
let myObject = {
firstname: 'harry',
lastname: 'potter'
}
console.log(typeof myObject);
if(typeof myObject === 'object') {
console.log('this is object');
}
Example 2: javascript check if is object
obj = {
"data": 123
}
arr = [
"data",
123
]
function obj_or_arr(val) {
if (typeof val === "object") {
try {
for(x of val)
break;
return "array";
} catch {
return "object";
}
} else return false;
}
console.log(obj_or_arr(obj))
console.log(obj_or_arr(arr))
console.log(obj_or_arr(123))
console.log(obj_or_arr("hello world"))
console.log(obj_or_arr(true))
console.log(obj_or_arr(false))
Example 3: javascript check if variable is object
function isObject(val) {
if (val === null) { return false;}
return ( (typeof val === 'function') || (typeof val === 'object') );
}
var person = {"name":"Boby Snark"};
isObject(person);