loading...

Check if key exists in Dictionary/Object in Python vs Javascript

victoromondi1997 profile image VICTOR OMONDI ・1 min read

Python

dict = { 'platform': 'telegram' }

if 'platform' in dict:
 # do something

Javascript

let obj ={ platform: 'telegram' }

if(obj['platform']){

   // do something

}

Discussion

markdown guide
 

The JavaScript version is wrong. The object can contain property that is falsey and you code would evaluate as if the object doesn't contain that property.

The right way would be using in operator, hasOwnProperty method or similar.

if ('platform' in obj) {
  // ...
}

if (obj.hasOwnProperty('platform')) {
  // ...
}