yomamma
yomamma

Reputation: 13

'key' in vs object.key

Is there any difference between:

if('mykey' in obj){

}

and

if(obj.mykey){

}

?

Upvotes: 0

Views: 104

Answers (5)

Rishabh
Rishabh

Reputation: 1213

let obj = {
   mykey: true

}

if('mykey' in obj){
   //checks if the object has this key
   //true
}


if(obj.mykey){
   //check if object key's value is 'true'
   //true
}

whereas

let obj = {
   mykey: false

}

if('mykey' in obj){
   //checks if the object has this key
   //true
}


if(obj.mykey){
   //check if object key's value is 'true'
   //false
}

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409196

Lets say you have

var obj = { mykey: false };

Then 'mykey' in obj will be true, while obj.mykey will be false. A very big difference.

The 'mykey' in obj expression will check if the object have a property or not. The obj.mykey expression will retrieve the value of the property and use that.

Also, if the object obj doesn't have a mykey property, then 'mykey' in obj will result in false while obj.mykey result in undefined.

Upvotes: 1

Rax Weber
Rax Weber

Reputation: 3780

In the first case, you are checking if mykey property exists in the object. In the second case, you are checking if mykey property of object is false, which includes being null, undefined, zero or even empty. So in the second case, if it exists, yet the value is zero, then the if statement won't get executed. In the first case it will, because it only checks if the property exists.

Example:

var obj = {"a": 1, "b": 0};

if ("b" in obj) { // gets executed }

if (obj.b) { // doesn't get executed }

Upvotes: 0

Orr Siloni
Orr Siloni

Reputation: 1308

if ('mykey' in obj) checks for existence of mykey property in obj.

if (obj.mykey) checks the value of mykey property in obj. The value could be undefined if the property doesn't exist, but it could also be null, false or empty string which will also evaluate to false.

Upvotes: 0

Pranay
Pranay

Reputation: 430

if('mykey' in obj){

}

In the above case mkey is type of object say "Car" in "obj-Car" list

whereas

 if(obj.mykey){

}

In the above you have mkey as property as "Engine" of object 'obj-Car'

Upvotes: 0

Related Questions