The JavaScript in operator
The in operator returns true if a property exists in an object (including inherited ones). "name" in user checks for a name property. It tests for the key, not the value, so it works even when the value is undefined or falsy. For own properties only, use Object.hasOwn().
Overview
The in operator checks whether a property exists in an object. "email" in user is true if user has an email property — regardless of its value. That's the important distinction from if (user.email), which is false when the value is falsy ("", 0, false) even though the key is present. in tests the key, not the value.
It also checks inherited properties up the prototype chain, so "toString" in {} is true. When you want only the object's own properties, use Object.hasOwn(obj, key) instead — that's the more common need. in is the right choice when inherited members should count too.
With arrays, in checks for an index, not a value: 1 in ["a", "b"] is true (index 1 exists), but "b" in ["a", "b"] is false. To check for a value in an array, use includes(). Don't confuse the in operator with the for...in loop — they're different features that happen to share the keyword.
Syntax
"property" in object
"name" in { name: "Ada" } // true
"age" in { name: "Ada" } // false
"toString" in {} // true (inherited)
1 in ["a", "b"] // true (index 1 exists)
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
const user = { name: 'Ada', score: 0 };
document.getElementById('out').textContent =
"'name' in user: " + ('name' in user) + '\n' +
"'score' in user: " + ('score' in user) + ' (value is 0)\n' +
"'email' in user: " + ('email' in user);
// true / true / false
</script>
Best practices
- Use
into check a key exists even when its value might be falsy. - Use Object.hasOwn() when you want only own properties (the common case).
- For arrays,
inchecks indices — use includes() to check for a value. - Don't confuse the
inoperator with the for...in loop.
Frequently asked questions
What does the in operator do?
true if a property (key) exists in an object, including inherited ones. It tests the key, not the value.What is the difference between in and Object.hasOwn()?
Why use in instead of if (obj.key)?
if (obj.key) is false when the value is falsy (0, "") even if the key exists. in checks existence regardless of value.Can I use in to check for a value in an array?
in checks indices. Use includes() to check for a value.