Say I have the following code:
function One() {} One.prototype.x = undefined; function Two() {} var o = new One(); var t = new Two();
o.x
and t.x
will both evaluate to undefined
. o.hasOwnProperty('x')
and t.hasOwnProperty('x')
will both return false; the same goes for propertyIsEnumerable
. Two questions:
undefined
?A small caveat: doing (for propName in o) loop will yield 'x' as one of the strings, while doing it in t will not - so there IS a difference in how they're represented internally (at least in Chrome).
We can check if a property exists in the object by checking if property !== undefined . In this example, it would return true because the name property does exist in the developer object.
Use the typeof operator to check if a variable is defined or initialized, e.g. if (typeof a !== 'undefined') {} . If the the typeof operator doesn't return a string of "undefined" , then the variable is defined.
To check for undefined in TypeScript, use a comparison to check if the value is equal or is not equal to undefined , e.g. if (myValue === undefined) {} or if (myValue !== undefined) {} . If the condition is met, the if block will run.
Difference Between undefined and null Though, there is a difference between them: undefined is a variable that refers to something that doesn't exist, and the variable isn't defined to be anything. null is a variable that is defined but is missing a value.
A slightly simpler way than your method is to use the Javascript in operator
alert('x' in o); // true alert('x' in t); // false
object.hasOwnProperty(name) only returns true for objects that are in the same object, and false for everything else, including properties in the prototype.
function x() { this.another=undefined; }; x.prototype.something=1; x.prototype.nothing=undefined; y = new x; y.hasOwnProperty("something"); //false y.hasOwnProperty("nothing"); //false y.hasOwnProperty("another"); //true "someting" in y; //true "another" in y; //true
Additionally the only way do delete a property is to use delete. Setting it to undefined do NOT delete it.
The proper way to do it is to use in like roborg said.
Update: undefined is a primitive value, see ECMAScript Language Specification section 4.3.2 and 4.3.9.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With