javascript check class of object code example
Example 1: 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 2: js class check if new instance
new Date() instanceof Date;
Example 3: how to check which class a object is from
if (obj instanceof C) {
}