Skip to content
Home ยป JavaScript Object In-Depth

JavaScript Object In-Depth

    In this article, you will learn about JavaScript object in more details. All the previous examples have one or two objects created. Now we will look at more complex construct.

    JavaScript objects are like arrays . You can access them like arrays using index. However, the index is its property.
    For example:

    let arr = [โ€˜johnโ€™, โ€˜leeโ€™]; //an array
    console.log(arr[0]); // prints the first element of array
    Now consider an object.
    let person = {
    firstName : โ€˜Johnโ€™,
    lastName: โ€˜Miroโ€™
    };
    //to access the property like array use the bracket notation
    console.log(person[โ€˜firstNameโ€™]);
    How many ways to define the property?

    How many ways to define the property?

    Method 1: use double quotes

    
    let person = {
    โ€œfirstNameโ€: โ€˜Johnโ€™
    };

    Method 2: use single quotes

    let person = {
    โ€˜firstNameโ€™: โ€˜Johnโ€™
    };

    Method 3: use no quotes

    let person = {
    firstName: โ€˜Johnโ€™
    };

    Nested Objects

    Objects can contain other objects.
    For example:

    let person = {
    firstName: โ€˜Sherlockโ€™,
    lastName: โ€˜Holmesโ€™,
    address: {
        street: โ€˜221 Baker Streetโ€™,
        city: โ€˜Londonโ€™,
        country: โ€˜UKโ€™
    }
    };

    How do you access the nested Object ?

    The dot notation and the bracket notation still works for the nested objects.

    console.log(person.address.street);
    console.log(person.address[โ€˜cityโ€™]);

    How to add or delete object property?

    person.age = 34; /* simply type the object and its        property name and it will add it.*/
    
    delete person.address.city; /*will delete the city property in the nested object.*/

    Objects Have Methods

    Objects have methods that define the behavior of the object.
    For example.

    let person = {
    firstName : โ€˜Tedโ€™,
    lastName: โ€˜coddโ€™,
    say: function (){
    alert(โ€˜I am a data scientist!โ€);
    }
    };

    How to call the object function?

    person.say();

    The โ€˜thisโ€™ keyword

    You can refer to a property or method inside a function with โ€˜thisโ€™ keyword.

    let person = {
    firstName : โ€˜Tedโ€™,
    lastName: โ€˜coddโ€™,
    talk: function (){
    document.body.innerHTML = โ€˜My name isโ€ + this.firstName;
    }
    };

    In the next article, we will talk about strings.