Search code examples
javascriptobjecterror-handlingjavascript-objectsobject-properties

How can I rescue an undefined property of an object in JavaScript?


Okay, say you've got two objects: greg and stacy. They're both people. Greg's object looks like this:

var greg = {
  name: "Greg",
  job: "doctor",
  age: 45
}

and Stacy's like this:

var stacy = {
  name: "Stacy",
  age: 42
}

When someone tries to access Stacy's job property, how can I have that return 'Unemployed' without directly putting that as her job? I'd like a solution that doesn't use prototypes, and I'd really rather not use a function to access all the properties of an object.

Just for context: I'm using this for an Ajax auto-loading system, similar to Rails's server-side one.


Solution

  • Use || to specify a default value when extracting the property.

    var job = person.job || "Unemployed";
    

    However, this has to be done in every place where you get the job. If you don't want to have to repeat it all over the place, you need to use a function or prototype.