Tech Junkie Blog - Real World Tutorials, Happy Coding!: JavaScript Objects Deep Dive: Preventing Errors When Accessing Object Properties

Thursday, October 21, 2021

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(); = "Chai";
        product.category = "Tea"; = "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.; or type console.log(

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 (
      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

     length =;

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

if("city" in product)
   length =;


  1. Free Worldwide Shipping, Cafe Business Cards, Restaurant Business Card, Loyalty Card, Stamp Card, Pie Business Cards, Restaurant Loyalty Card - Free Shipping - Aladdin Print. Visit our website to learn more!

  2. Excellent trancription provider. Adam was my initial contact and was able to answer all my questions, provide an immediate quote with full transparency on fees & expedited services. Their process is quick and efficient with excellent follow-through throughout the process. Excellent quality on final trancription & entire transaction was completed in under 24 hours. Reasonable price for outstanding service!


Search This Blog