2

This question about JavaScript with function-Object.

I have a function like:

function person(){
this.name = 'Tom',
this.Age //not set any value
} 

And I created a object by "person" function:

var obj = new person();
obj.name //Tom
obj.Age //undefined
obj.DOB //also returned undefined

How to distinguish "Age” property already exist in "obj" but no value, or "DOB" does not exist at all.

1
  • You can set this.Age = null; (null !== undefined) Commented Oct 19, 2015 at 6:41

3 Answers 3

3

JavaScript distinguishes between null, which is a value that indicates a deliberate non-value (and is only accessible through the null keyword), and undefined, which is a value of type undefined that indicates an uninitialized value — that is, a value hasn't even been assigned yet.

You can simply use

if(this.hasOwnProperty('Age')){

}

Or

if('Age' in this){

}
Sign up to request clarification or add additional context in comments.

4 Comments

Note that these two choices have slightly different behavior. The second will be true if Age is anywhere in the object including in the prototype. The first will only be true if Age is a direct property on the object (and not only on the prototype).
Also, note that a property can exist, but have an assigned value of undefined, so you can't test for undefined to see if the property exists or not. .hasOwnProperty() is probably the best choice to test if a given property has been specifically assigned to this object or not.
Anyway if you do not initialize 'Age' property, it does not function, so initialization is mandatory
Thank you for your answer. I tried use "hasOwnProperty" and "in" to distinguishes. but returned same value is "undefined". "hasOwnProperty" is only used for normal object in Javascript. this is a "function-Object" not normal. so its not work.
2

obj.Age is not already existing. if you wanted it to then you have to initialize it to null or undefined then you could check like

if(obj.hasOwnProperty('Age')){

}

Comments

-2

You only want to check for it's existence? Use an if statement

if (obj.Age) {
  // do stuf
} else {
  // do other stuff
}

undefined returns as a falsy value to the if statement, so if it's not there it will execute the else statement. If it does exist, then the first block.

1 Comment

false, 0, empty strings (""), NaN, null, and undefined all become false.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.