2

Let say :

myVariable.color;
myVariable.height;
myVariable.width;

But sometimes, myVariable only have "color" and "height" property.

I have try this, but no luck :

if(myVariable.width == undefined) {
//but not filtered here
}

How to know if myVariable doesn't contain "width" property by code, is it possible ?

Crocodile
  • 469
  • 2
  • 8
  • 22

2 Answers2

0

You could try to double negate:

if(!!myVariable.width){
    //do something here
}
Mihai Iorga
  • 39,330
  • 16
  • 106
  • 107
  • Nope, not the answer. – Isaaс Weisberg Jul 01 '19 at 07:34
  • @IsaacCarolWeisberg I know about `hasOwnProperty` but .. what's wrong with above code? Why isn't it the answer .. It does not do what it should do? – Mihai Iorga Jul 01 '19 at 07:38
  • The thing is that you could've assigned `undefined` to the `width` yourself, or alternatively you could have never assigned to `width` anything in the first place. But: if you have never touched the property setter, then `hasOwnProperty` and `in` will return false. However, if you assign `undefined` to `width` manually, your check will still fail since the value is `undefined`, but `hasOwnProperty` and `in` will be both true because this key was actually set. – Isaaс Weisberg Jul 01 '19 at 08:19
0

You are looking for hasOwnProperty.

If you would like to perform a search in the whole potential prototype chain of an object, you can also use the in operator.

if (width in object) {
Isaaс Weisberg
  • 2,296
  • 2
  • 12
  • 28