Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - Identify whether a property is defined and set to 'undefined', or undefined

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:

  • Is there any way to tell that o.x is defined and set to undefined?
  • Is there ever any reason to? (should the two be semantically equivalent?)

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).

like image 304
Claudiu Avatar asked Dec 22 '08 10:12

Claudiu


People also ask

How do you check if a property is defined in JavaScript?

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.

How do you know if something is defined or undefined?

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.

How do I know if a Typecript property is undefined?

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.

Is undefined or null JavaScript?

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.


2 Answers

A slightly simpler way than your method is to use the Javascript in operator

alert('x' in o); // true alert('x' in t); // false 
like image 108
Greg Avatar answered Sep 20 '22 20:09

Greg


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.

like image 45
some Avatar answered Sep 24 '22 20:09

some