Borislav Hadzhiev
Sun Oct 03 2021·3 min read
Photo by Marcos Paulo Prado
To check if a key exists in a JavaScript object, use the in
operator, e.g.
"key" in myObject
. The in
operator will return true
if the key is in the
specified object or its prototype chain.
const person = { name: 'John', }; console.log('name' in person); // 👉️ true console.log('age' in person); // 👉️ false
The syntax when using the
in operator
is: string
in object
.
The value before the in
keyword should be of type string
or symbol
. Any
non symbol
value will get automatically coerced to a string
.
const person = { 0: 'John', }; console.log('0' in person); // 👉️ true console.log(0 in person); // 👉️ true
string
or symbol
. Even though our object seemingly has a key of type number
, it actually is a string
.The in
operator will coerce the 0
to a string
in our second console.log
statement.
We can use the Object.hasOwnProperty
method to check if a key exists in an
object, e.g. - myObject.hasOwnProperty('key')
. The Object.hasOwnProperty
method returns true
if the key exists in the object and false
otherwise.
const person = { name: 'John', }; console.log(person.hasOwnProperty('name')); // 👉️ true console.log(person.hasOwnProperty('age')); // 👉️ false
Object.hasOwnProperty
method and the in
operator is that the in
operator checks for a key in an object and its prototype chain, whereas the Object.hasOwnProperty
method only checks for the existence of the key directly on the object.We can use the Optional chaining (?.
) operator to check if a key exists in
an object, e.g. - myObject?.key
. If the key exists on the object, the Optional
chaining operator will return the key's value, otherwise it returns
undefined
.
// Not Supported in IE 6-11 const person = { name: 'John', }; console.log(person?.name); // 👉️ John console.log(person?.age); // 👉️ undefined if (person?.name !== undefined) { // the key exists on the object }
In the code example we used the Optional chaining operator to check if the
name
and age
keys exist in the object.
The name
key, exists therefore person?.name
evaluates to John
. The age
key doesn't, so the Optional chaining operator returns undefined
.
undefined
values in an object, in that case this approach would return a false negative.const person = { name: undefined, }; console.log(person?.name); // 👉️ undefined if (person?.name !== undefined) { // the `name` key exists, but this never runs }
In the code example, even though the name
key exists on the object, our
conditional check does not account for the case if it's value is set to
undefined
.