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 ?

asked Jul 1, 2019 at 7:32
0

2 Answers 2

0

You could try to double negate:

if(!!myVariable.width){
 //do something here
}
answered Jul 1, 2019 at 7:34

3 Comments

Nope, not the answer.
@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?
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.
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) {
answered Jul 1, 2019 at 7:34

2 Comments

Is it secure if implement in React Native ?
Yes, this is a feature of JS runtime and not the browser/node specifically.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.