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
2 Answers 2
You could try to double negate:
if(!!myVariable.width){
//do something here
}
answered Jul 1, 2019 at 7:34
3 Comments
Isaaс Weisberg
Nope, not the answer.
Mihai Iorga
@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?Isaaс Weisberg
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.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
Crocodile
Is it secure if implement in React Native ?
Isaaс Weisberg
Yes, this is a feature of JS runtime and not the browser/node specifically.
lang-js