Javascript Object Properties

    Properties are the technical term for JavaScript name:value pairs.

    JavaScript Properties

    In the previous JavaScript tutorial, we learned what is an Object in JavaScript and how we define them. Just for a quick reference, a JavaScript object is a collection of name:value pairs separated with commas, inside curly brackets. We can treat the individual name:value pair as a property of the Object. And we can access, change, add, and delete properties from the object.

    Accessing JavaScript Properties

    There are two ways we can access the properties from the Object. Using the object . operator followed by property name.

    object_name.property_name

    Using the property name inside the square bracket.

    object_name["property_name"]

    Example

    <script>
        var man = {name:"Rahul", age:24};
        //using . operator
        document.write(man.name + "  " + man.age); //Rahul 24
        document.write("<br>")// new line
        //using sq bracket
        document.write(man["name"] + "  " + man["age"]) //Rahul 24
    </script>
    Output
    Rahul 24
    Rahul 24

    Change the property

    We can also change the value of a property name, by accessing the property and assigning a new value to it. Example

    <script>
        var man = {name:"Rahul", age:24};
        //change property value
        man.age =30;
        document.write(man.name + "  " + man.age); //Rahul 30
    </script>
    Output
    Rahul 30

    Add new Property

    Similar to updating the property we can add a new property to the object using dot or square brackets. To add a new property we need to specify the new property name and its value. If we try to add a new property with an already existing name then instead of creating new property it will update or change the old one. Example

    <script>
        var man = {name:"Rahul", age:24};
        man.gender = "Male";  //or man["gender"] ="Male"
        document.write(man.name+" "+ "("+man.gender+")");
    </script>

    Output

    Rahul (Male)

    Delete property

    let say we wish to delete a property from the object for that we can use the delete keyword followed by the object property.

    <script>
        var man = {name:"Rahul", age:24};
    
        delete man.age; // delete man age property
    
        console.log(man);
    </script>
    Output
    {name: "Rahul"}

    The delete keyword will delete the property name as well as its value from the object.

    Summary

    • The object is a container that can store multiple name:value pairs.
    • All the name:value pairs are of the object are known as properties.
    • We can access, add, delete and change the object properties.
    • The delete keyword will delete the property form the object.

    People are also reading: