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") { // return if is not array or object
		try {
			for(x of val)  // is no errors happens here is an array
				break;
			return "array";
		} catch {
			return "object"; // if there was an error is an object
		}
	} else return false; 
}

console.log(obj_or_arr(obj)) // object
console.log(obj_or_arr(arr)) // array
console.log(obj_or_arr(123)) // false
console.log(obj_or_arr("hello world")) // false
console.log(obj_or_arr(true)) // false
console.log(obj_or_arr(false)) // false

Example 2: js class check if new instance

new Date() instanceof Date;  // => true

Example 3: how to check which class a object is from

if (obj instanceof C) {
//your code
}