The in
operator in JavaScript is used to check if a property is present in the object.
prop in object
prop
can be an array index, an object key (string), or a symbol representing a property name.object
is the object the property may be in.Let’s check if an array contains an index.
The in
operator will return true if the index is present in the array and the value in the index is not empty.
console.log("Checking if an index present in ayyay using 'in operator' ")let arr = [1,2,3,undefined];console.log("checking if index 0 in arr => ", 0 in arr ); // trueconsole.log("checking if index 3 in arr => ", 3 in arr ); // trueconsole.log("checking if index 4 in arr => ", 4 in arr ); // false -> because array contains index from 0-3console.log("\n-------------\nChecking it with deleted array values");let newArr = [1,2,3]console.log("The array is ", newArr);console.log("Deleting element at index 1");delete newArr[1];console.log("After deleting aray is ", newArr);console.log("Cheking if index 1 present in array => ", 1 in newArr);console.log("\n----------\nCheking if symbol in array ");console.log("Symbol.iterator in newArr =>", Symbol.iterator in newArr); // returns true (arrays are iterable)console.log("\n---------\n")console.log("Checking if length in newArr => ", 'length' in newArr); // true because length is the property of an array
Let’s use the in
operator to check if a property is present in an object.
In an object, if we set the value of the property as undefined
, then the in
operator returns true.
let user = {name : "Anitha", age : 25};console.log("The object is", user);console.log("Checking if 'name in user' => ", 'name' in user);console.log("Checking if 'age in user' => ", 'age' in user);console.log("Checking if 'salay in user' => ", 'salary' in user);console.log("\n-----------\nLet's add salary to user object ");user.salary = 10000;console.log("The object is", user);console.log("Checking if 'salay in user' => ", 'salary' in user);console.log("\n-----------\nLet's delete age from user object ");delete user.age;console.log("The object is", user);console.log("Checking if 'age in user' => ", 'age' in user);console.log("\n-----------\nLet's set the value of age as undefined");user.age = undefined;console.log("The object is", user);console.log("Checking if 'age in user' => ", 'age' in user);
The in
operator returns true for properties in the prototype chain.
let emptyObj = {};console.log('toString' in emptyObj);
The right side of the in
operator must be an object. Otherwise, we will get an error.
10 in 100;
// Cannot use the 'in' operator to search for '10' in 100