What is the usage of in operator in JavaScript?

The in operator is used in JavaScript to check whether a property exists in an object or not. It returns true if the property is found, and false otherwise.

Syntax

propertyName in object

Basic Example

Here's how to use the in operator to check for properties in objects:

<!DOCTYPE html>
<html>
<body>
<script>
var emp = {name: "Amit", subject: "Java"};
document.write("name" in emp);
document.write("<br>");
document.write("subject" in emp);
document.write("<br>");
document.write("age" in emp);
document.write("<br>");
document.write("MAX_VALUE" in Number);
</script>
</body>
</html>
true
true
false
true

Checking Array Indices

The in operator also works with array indices:

<!DOCTYPE html>
<html>
<body>
<script>
var fruits = ["apple", "banana", "orange"];
document.write(0 in fruits);
document.write("<br>");
document.write(2 in fruits);
document.write("<br>");
document.write(5 in fruits);
</script>
</body>
</html>
true
true
false

Inherited Properties

The in operator checks both own properties and inherited properties from the prototype chain:

<!DOCTYPE html>
<html>
<body>
<script>
var person = {name: "John"};
document.write("name" in person);
document.write("<br>");
document.write("toString" in person);
document.write("<br>");
document.write("hasOwnProperty" in person);
</script>
</body>
</html>
true
true
true

Comparison with hasOwnProperty()

Method Checks Own Properties Checks Inherited Properties
in operator Yes Yes
hasOwnProperty() Yes No

Conclusion

The in operator is a reliable way to check property existence in JavaScript objects and arrays. It checks both own and inherited properties, making it useful for comprehensive property detection.

Updated on: 2026-03-15T23:18:59+05:30

193 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements