Tech Junkie Blog: JavaScript Objects Deep Dive: Preventing Errors When Accessing Object Properties

Friday, December 1, 2017

JavaScript Objects Deep Dive: Preventing Errors When Accessing Object Properties

There are times when you will get an error when you tried to access a property in an object, sometimes you think a property exists in the object but it does not.  Let's use the product object from the previous blog post as an example.


        var product = new Object();

        product.name = "Chai";
        product.category = "Tea";
        product.country = "India";
        product.supplier = {
            name: "ACME Tea Of India",
            location: "New Delhi"
        };

Let's say another developer works on the project and he assumes that since there's a "country" property that there should be a "city" property.  If he tries to access the access the "city" property in the product object he will get an undefined, because the property does not exist.   If he types the following he will get the undefined message.

product.city; or type console.log(product.city)







If the developer still persists and still tries to access property by checking it's length he will get the TypeError:








As you can see these errors are not very descriptive, so the best thing to do is to avoid them all together.  The way to do that is to check to if a property exists before you access it with the example below.

var length = undefined;

if(product)
  if (product.city)
      length = product.city.length;


Now if console.log(length) we will get an undefined if the "city" property does not exist.  It's way better than getting a TypeError exception and it's the expected result because you initialized the length variable to "undefined".  Another alternative is to use the .hasOwnProperty() method or the in
operator to test if the property exists in the product object.

For the .hasOwnProperty()

The code would look something like this

if(product.hasOwnProperty("city")
     length = product.city.length;

With the in operator the code would look something like this.

if("city" in product)
   length = product.city.length;

No comments:

Post a Comment