Update JavaScript objects

 Update JavaScript objects

In JavaScript, once objects are created they can have different values. In other words these are mutable. They can have different values assigned to them.

Changing the values can be achieved using dot notation or bracket notation. Both are valid.

Let's take a look at an example to understand the concept.
As you can see initially when the object is created the age is 5. However, before we print, we update the age and display it inside the res div.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Update object</title>
</head>
<body>
    <div id="res"></div>
    <script>
        var res = document.getElementById("res");

        var myDog = {
            name: "Fido",
            age: 5,
            breed: "Pug",
            favFood: "Muffins"
        };
        
        var updateAge = myDog.age = 6;
        res.innerHTML = (updateAge);
    </script>
</body>
</html>

Note: Adding an additional property to the object is pretty similar. Thus we will not have a separate lesson for it. Suppose you wanted to have an additional property you would do this:

myDog.legs = 4; or myDog["legs"] = 4;

It will be evaluated in the same fashion: 
myDog.legs will yeild 4.



Post a Comment

0 Comments

React