Tech Junkie Blog: JavaScript Objects Deep Dive : Setting And Getting Properties

Friday, November 24, 2017

JavaScript Objects Deep Dive : Setting And Getting Properties

Now that we've learned to create objects in all sorts of ways it's time to set and get the object properties that we've created.  In this blog we will go over how to access the object properties either to set them or get them.

First let's create an object that we can work with:

Type in the following code in the between the <script type="text/javascript"></script> tag in an html page.


        var product = new Object();

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

        console.log(product);
If you run the page with the code above you will see the following in the browser console:















Now that we have our object let's start changing the properties. There are two ways you can get and set properties. You can either set the properties using the .dot notations or you can use the [] operators to access the properties. First let's get the properties with these two methods. Add the following lines to the code above.

        console.log(product.name);
        console.log(product["category"]);

As you can see they both got the job done if you look at the console in your browser. With both methods we were able to retrieve the values for the product name, and category.









Now let's do the same to set the properties for our product. First let's set the name property to "Dark Roast" using the dot notation. product.name = "Dark Roast"; Now let's set the category to be "Coffee" with the bracket operators. product["category"] = "Coffee"; If we look at the browser console again we will see that the name, and category has been changed.








Here is the complete code for this example:

<!DOCTYPE html>
<html>
<head>
    <title></title>
 <meta charset="utf-8" />
    <script type="text/javascript">
        var product = new Object();

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

        product.name = "Dark Roast";
        product["category"] = "Coffee";

        console.log(product);
        console.log(product.name);
        console.log(product["category"]);
    </script>
</head>
<body>

</body>
</html>

No comments:

Post a Comment