check if property is object javascript code example

Example 1: How to tell if an attribute exists on an object

const user = {
    name: "Sicrano",
    age: 14
}

user.hasOwnProperty('name');       // Retorna true
user.hasOwnProperty('age');        // Retorna true
user.hasOwnProperty('gender');     // Retorna false
user.hasOwnProperty('address');    // Retorna false

Example 2: js check if object has property

const object1 = new Object();
object1.property1 = 42;

console.log(object1.hasOwnProperty('property1'));
// expected output: true

Example 3: 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 4: javascript check if object

typeof yourVariable === 'object' // true if it's an object or if it's NULL.

// if you want to exclude NULL
typeof yourVariable === 'object' && yourVariable !== null