Which is the right thing to do?
if (myObj['key'] == undefined)
or
if (myObj['key'] == null)
or
if (myObj['key'])
!!myObj.key
which returns true
(if in) and false
(if not). - anyone const user = { name: "John", admin: false }; !!user.name
will return true. But !!user.admin
will return false even though the 'admin' key exists - anyone Try the JavaScript in operator.
if ('key' in myObj)
And the inverse.
if (!('key' in myObj))
Be careful! The in
operator matches all object keys, including those in the object's prototype chain.
Use myObj.hasOwnProperty('key')
to check an object's own keys and will only return true
if key
is available on myObj
directly:
myObj.hasOwnProperty('key')
Unless you have a specific reason to use the in
operator, using myObj.hasOwnProperty('key')
produces the result most code is looking for.
Answered 2023-09-21 08:08:20
You should use hasOwnProperty
. For example:
myObj.hasOwnProperty('myKey');
Note: If you are using ESLint, the above may give you an error for violating the no-prototype-builtins rule, in that case the workaround is as below:
Object.prototype.hasOwnProperty.call(myObj, 'myKey');
Answered 2023-09-21 08:08:20
has**Own**Property
? - anyone Do not access Object.prototype method 'hasOwnProperty' from target object.
- anyone {}.hasOwnProperty.call(object, "key")
- anyone