Computer >> Computer tutorials >  >> Programming >> Javascript

How to check whether a particular key exist in javascript object or array?


There are different ways to check for existence of an object/key in an array and an object. Let us look at the Object case first.

To look if a key exists in a object, we need to use the in operator.

Example

let obj = {
   name: "John",
   age: 22
}
console.log('name' in obj);
console.log('address' in obj);

Output

true
false

Note −The in operator returns true if the specified property is in the specified object or its prototype chain.

For checking if an object exists in an array, we need to use the indexOf method on the array. If the object is not found, -1 is returned, else its index is returned.

Example

let arr = ["test", 1, 2, "hello", 23.5];
console.log(arr.indexOf({}))
console.log(arr.indexOf("hello"))
console.log(arr.indexOf(23.5))

Output

-1
3
4