EastenCat
EastenCat

Reputation: 21

How to check is property existed in function-object (Javascript)

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.

Upvotes: 2

Views: 59

Answers (3)

Özgür Kaplan
Özgür Kaplan

Reputation: 2136

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

}

Upvotes: 3

danleyb2
danleyb2

Reputation: 1068

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')){

}

Upvotes: 2

Dustin Stiles
Dustin Stiles

Reputation: 1424

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.

Upvotes: -2

Related Questions