Objects in JavaScript

JavaScript , Tue Jan 03 2023

    Intro to Objects

    Objects are the most important data type and building block for modern JavaScript.

    Objects are quite different from JavaScript's primitive data-types (numbers, strings, booleans...) in the sense that while these primitive data-types all store a single value, objects can store multiple.

    Objects in JavaScript can be compared to objects in real life. The concept of objects in JavaScript can be understood with real life, tangible objects.

    In JavaScript, an object is a standalone entity, with properties and type.

    Compare it with a cup, for example. A cup is an object, with properties. A cup has a cooler, a design, weight, a material it is made of, etc.

    The same way, JavaScript objects can have properties, which define their characteristics.

    So what are objects, why do we need them and how can we declare them?

    In simple words, object is an unordered collection of related data in form of key and value pairs.

    Let's create a simple object so that we can see everything in action:

    const person = {
        firstName: 'John',
        lastName: 'Doe',
        age: 25,
    };

    In here, we can see that to create an object, we need to just open a set of curly brackets & assign it to a variable, that's the form of the object.

    Then, inside, we have key and value pairs. For instance, first key in the person object is firstName, with a corresponding value of 'John'. Inside of there, we also have lastName and age.

    And all of these properties are somehow grouped together. Each of these keys is referred to as properties of the object.

    Opposed to having something like this, where every value stands for itself, objects allow us to make certain pieces of data related.

    const firstName = 'John';
    const lastName = 'Doe';
    const age = 25;

    Also, we mentioned that objects are unordered, what does that mean? The order of properties in an object can change, and will not always stay the same as we declared it. But that's fully okay.

    But that's fully okay. When we're working with objects, we are not worried about the order, that's what arrays are for, more on that really soon! :)

    In our person object, you can see that our firstName & lastName are strings, & age is an object. Values in an object can be of absolutely any type. For example, let's say that our person has a car, that car, can again be an object, because there are a lot of properties we want to describe that car with:

    const person = {
        firstName: 'John',
        lastName: 'Doe',
        age: 25,
        car: {
            year: 25,
            color: 'Red',
    }
    };

    That simply means that we can nest objects inside other objects.

    We can also add variables as values in an object. In a sense, a variable is just a box that holds a value. Because of that, we can do the following:

    const firstName = 'John';

    const person = {
    firstName: firstName
    };
    // show the output

    ... one thing that we can notice is that the key and value have the same name. If that is the case, JavaScript allows us to write it like this:

    const person = {
    firstName,
    }
    // show the output

    meaning, just remove one, and it is still going to work.

    Accessing, adding and updating properties

    Dot Notation

    To access, add, or update a property of an object, we use something called dot notation.

    Dot notation allows us to retrieve some values from an object, for example, if we want to get only the firstName of our person.

    we can do the following:

    person.firstName;

    In the same fashion, we can add or overwrite some properties:

    person.dog = { name: 'Fluffy', age: 2};
    person.age = 26;

    Square Bracket Notation

    There is also a second way to retrieve properties from an object, it is called square bracket notation.

    Square bracket notation, like the dot notation, also allows us to access properties of an object:

    person['firstName'];

    ...but it also has some additional features, for example, we can access propererties dynamically. Let me show you what I mean:

    const property = 'age';
    person['property'];

    It is also used when we have key names that are not usual JavaScript variable names:

    // add 'this-is-a-key-with-dashes'
    // and 'this is another key' to the person object.

    person['this-is-a-key-with-dashes'];
    person['this is another key'];

    // person.this is another key - error
    // person.this-is-a-key-with-dashes - error

    Object Methods

    A method is a function associated with an object, or, simply put, a method is a property of an object that is a function.

    Methods are defined the way normal functions are defined, except that they have to be assigned as the property of an object.

    objectName.methodname = functionName;

    var myObj = {
        myMethod: function(params) {
            // ...do something
        }

        // OR THIS WORKS TOO

        myOtherMethod: function(params) {
            // ...do something else
        }
    }

    Where objectName is an existing object, methodname is the name you are assigning to the method, and functionName is the name of the function.

    You can then call the method in the context of the object as follows:

    object.methodname(params);

    You can define methods for an object type by including a method definition in the object constructor function. You could define a function that would format and display the properties of the previously-defined Car objects; for example,

    function displayCar(){
        var result = `A Beautiful ${this.year} ${this.make} ${this.model}`;
        pretty_print(result);
    }

    where pretty_print is a function to display a horizontal rule and a string.

    Notice the use of this to refer to the object to which the method belongs.

    You can make this function a method of Car by adding the statement

    this.displayCar = displayCar;

    to the object definition. So, the full definition of Car would now look like

    function Car(make, model, year, owner){
        this.make = make;
        this.model = model;
        this.year = year;
        this.owner = owner;
        this.displayCar = displayCar;
    }

    Then you can call the displayCar method for each of the objects as follows:

    car1.displayCar;
    car2.displayCar;