Mariton Mariton - 1 month ago 7
Javascript Question

I would like to improve my JavaScript condition code

Please bear with me because I am new to JavaScript and I was given this code to try to improve it so any input is helpful. I was told to list some concerns or problems that you see with the code. So far I see that:

Using the double equal equality operator to compare an object against a string may not be the best solution

if typeof data !=='object'

Also please assume that assume PeopleFactory is defined globally

Feel free to pick apart the code. It would be very helpful.
Thanks

var Person_D = function Person_D(name) {
//assume PeopleFactory is defined globally
//getDetailsAsync returns either null or a record with specific name.
PeopleFactory.getDetailsAsync(name, function(data) {
if (typeof data !== 'object') {
throw new Error('No record found for this individual.');
}

this.name = data.name;
this.age = data.age || 'No age data available.';
this.eyeColor = data.eyeColor || "This individual's eye color data is not listed.";
this.height = data.size.height || "No height specified.";

});

return this;

}

var personD = new Person_D('Jana');

console.log(personD.name);

Answer

Your question in its current state is too broad to "answer", however there are at least 2 bugs in the code that will cause errors in all cases.

  1. The code loads the properties of Person_D through PeopleFactory.getDetailsAsync, which is asynchronous, but access personD.name synchronously.

  2. The code uses this to assign properties in a callback so this is no longer referencing the Person_D object.

Possible fix (making no assumptions on how the code should work, just making it work as probably intended with correct outputs):

var Person_D = function Person_D(name) {
  var self = this;
  //assume PeopleFactory is defined globally
  //getDetailsAsync returns either null or a record with specific name.
  PeopleFactory.getDetailsAsync(name, function(data) {
    if (typeof data !== 'object') {
      throw new Error('No record found for this individual.');
    }

    self.name = data.name;
    self.age = data.age || 'No age data available.';
    self.eyeColor = data.eyeColor || "This individual's eye color data is not listed.";
    self.height = data.size.height || "No height specified.";
    console.log(self.name);
  });

  return this;
}

var personD = new Person_D('Jana');

To add: if(typeof data !=='object') is completely valid js and is actually the best way to do a type comparison.