I have a javascript object that may or may not contain a certain key which may or may not be true;
{
myKey: true,
}
I want to test whether the key exists, and if it does exist, whether it is true. I could do it like this;
if (myObject.myKey == true) {
}
With the use of the loose equality operator ==
, the answer will be false if myKey
is undefined or false and only true if it is true. However, eslint complains 'Expected '===' and instead saw '=='. eslint(eqeqeq)'
'Expected '===' and instead saw '=='. eslint(eqeqeq)'
. Is this a valid warning, or should I just ignore it?
The ==
operator has many surprises, which is why eslint is discouraging it. In this case, what eslint suggests does exactly what you're asking for:
if (myObject.myKey === true) {
}
Differences with the ==
operator only occur here if the value exists and is not a boolean; eg the value 1
. Due to the type conversions, 1 == true
is true, but 1 === true
is false.
If you also want a true value for such cases, just write
if (myObject.myKey) {
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.