Skip to main content

Command Palette

Search for a command to run...

Objects in JavaScript

Updated
8 min readView as Markdown
Objects in JavaScript

Introduction

What objects are in JavaScript?

We learnt from the article on data types, that there are primitive and non-primitive data types in JavaScript. Primitives hold values that are only of a single data type (such as string, number, booleans, and so on).

On the other hand, objects store a collection of values and use keys to organize and access them. Imagine a toolbox that has different compartments for storing different types of tools. Each compartment can hold a variety of tools, such as hammers, screwdrivers, or pliers. Similarly, objects can store different pieces of information.

Importance of objects in JavaScript

In JavaScript, objects are used a lot and are an important part of the language. It's crucial that you understand them well before learning other parts of JavaScript.

Creating Objects

In JavaScript, there are three(3) ways of creating objects, and they include;

  1. using object literal

  2. object constructor function

  3. Object.create() method

Using Object Literal

In this method, an object is defined by listing each property and its corresponding value separated by : , all enclosed in curly braces. The syntax for this way of creating an object is;

const person = { 
    firstName: "John",
    lastName: "Doe",
    age: 30,
};

Object Constructor Function

This method involves two steps, and they are;

  • Define the object type

  • Create an instance of the object with new.

  1. Now let's define the object type;

We create a function for the object type which specifies its name, properties, and methods.

For instance, to create an object type for Tesla. You want this type of object to be called Tesla, and you want it to have properties for the model, battery capacity, and year. To do this, we could write the following function:

function Tesla(model, capacity, year) { 
    this.model = model; 
    this.capacity = capacity; 
    this.year = year;
}

We use this to assign values to the object's properties based on the values passed when calling the function.

Note; it is a JavaScript convention to start a constructor function name with a capital letter.

  1. Now, let's create an object called myTesla;

const myTesla = new Tesla("Roadster", "200 kWh", 2023);

The above statement creates myTesla and assigns it the specified values for its properties. Then the value of myTesla.model is the string "Roadster", myCar.capacity is the string "200 kWh", myCar.year is the integer 2023. Make sure the order of arguments and parameters is the same.

Object.create() method

This involves creating a new object by specifying an existing object as its prototype. This method has an advantage; it allows you to choose the prototype object for the object you want to create, without having to define a constructor function. For example;

// this is the prototype object
const teslaProto = { 
    accelerate: function() { 
        console.log("Accelerating..."); 
    }, 
    break: function() { 
        console.log("Breaking..."); 
    }
};
// this is the newly created object
const myTesla = Object.create(teslaProto); 
myTesla.model = "Roadster"; 
myTesla.capacity = "200 kWh"; 
myTesla.year = 2023;

console.log(myTesla.model); // outputs, "Roadster" 
console.log(myTesla.capacity); // outputs, "200 kWh"

myCar.accelerate(); // outputs "Accelerating..."
myCar.break(); // outputs "Breaking..."

In this example, we define a prototype object called teslaProto with two methods: accelerate() and break(). We then create a new object called myTesla using Object.create() and set its model, capacity, and year properties. Finally, we access the properties of myTesla and call its accelerate() and drive() methods.

Object Properties and Methods

JavaScript objects usually have a collection of unordered properties. A property is a “key: value” pair, where key is a string (also called a “property name”), and value can be anything of any data type. The characteristics of an object are determined by its properties. For example;

const myTesla = {
    model: "Roadster",
    capacity: "200 kWh",
    year: 2023
};

The example above creates an object named myTesla, with properties named model, capacity, and year, with their values set to "Roadster", "200 kWh", and 2023. JavaScript also provides the features to add, access, delete and modify the properties of objects.

Now, let's try out these features;

  1. Adding properties to objects

    In JavaScript, we can add properties to an object in a few different ways. They include;

    • Dot notation

      As we know, myTesla already exists, so we can use dot notation to add a new property to it. Like so;

        // add a colour property using dot notation
        myTesla.colour = "Matte Black";
        // now lets see all the properties of myTesla
        console.log(myTesla); 
        // { model: "Roadster", capacity: "200 kWh", year: 2023 };
      
    • Bracket notation

      To add a new property using the bracket notation to myTesla, we simply do this;

        // add an autoPilot property using bracket notation
        myTesla['autopilot'] = true;
        // to see all the properties of myTesla 
        console.log(myTesla);
        // { model: "Roadster", capacity: "200 kWh", year: 2023, autopilot: true };
      
    • Object.assign() method

      Object.assign() is used to copy properties from one or more source objects to a target object. This method returns the updated target object. For example;

        const targetObj = { x: 2, b: 0 };
        const sourceObj = { y: 2, c: 3 };
      
        // store the returned target object in the variable `returnedTargetObj`
        const returnedTargetObj = Object.assign(target, source);
      
        console.log(targetObj);
        // { x: 2, b: 0, y: 2, c: 3 }
      
        console.log(returnedTargetObj === targetObj);
        // Expected output: true
      

      This method comes into use mostly for adding multiple properties to an object at once.

  2. Accessing properties in objects

    The value of a property in an object is accessed using its property name(i.e key). You can access the properties of an object using any of the following syntaxes: dot notation and bracket notation

    • Dot notation

      When using this syntax, the property name must be a valid JavaScript identifier. A valid identifier does not have spaces, hyphens, or special characters.

        // Dot notation
        console.log(myTesla.model) // Output: "Roadster";
        console.log(myCar.year) // Output: 2023;
      
    • Bracket notation

      Remember, dot notation can only be used to access properties with valid JavaScript identifiers, right? Bracket notation allows you to access properties with any string, whether it has spaces, hyphens, or special characters.

        // Bracket notation
        const student = { "last name": "Tommy" };
        console.log(student["last name"]); // Output: "Tommy"
      

      We can also use expressions in bracket notation. Like so;

        const student = {
          firstName: "Joshua",
          lastName: "Ishaba",
          age: 16
        };
      
        const propertyToAccess = "firstName";
        console.log(person[propertyToAccess]); // Output: "Joshua"
      

      The bracket notation syntax is also useful when property names are to be dynamically determined, i.e. only determinable at runtime(i.e only when the page is in use by a user)

  3. Deleting properties in objects

    You can remove a non-inherited property using the delete operator. A non-inherited property is a property that is directly assigned to an object, and not inherited from its prototype chain. For example;

     const student = {
       firstName: "Joshua",
       lastName: "Ishaba",
       age: 16,
       eyeColour: "brown"
     };
    
     delete student.age;
     // let's confirm that age was deleted
     console.log(student); // { firstName: "Joshua", lastName: "Ishaba", eyeColor: "brown" };
    
  4. Adding methods to objects

    A method is a property of an object that is a function. Methods are defined the way normal functions are defined, but, they are assigned as the property of an object.

     let myObj = { 
         myMethod: function() { 
         // code to execute 
     } 
         // this works too! 
         myOtherMethod(params) { 
         // code to execute 
         }, 
     }; 
     // we can then call the method, like so; 
     myObj.myMethod(); 
     // methods can also take arguments just like regular functions: 
     myObj.myOtherMethod(arguments);
    

    Object Manipulation

    Updating object properties

    Updating an object property in JavaScript simply means changing the value associated with a particular property key.

    For example, if you have an object representing a Tesla with a model property set to Roadster, you could update the value of the model property to Model S using JavaScript code. Now, let's update myTesla;

     // recall; the object looks like this,
     const myTesla = {
         model: "Roadster",
         capacity: "200 kWh",
         year: 2023
     };
     // to update, we simply override the previous value
     myTesla.model = "Model S";
     console.log(myTesla.model) // outputs, Model S
    

    So, yes you are correct, when you update an object property, you are basically overriding the old value with a new value.

    Updating object properties can be useful in many contexts, such as when you update data in response to user input.

    Using objects with loops

    The "for..in" loop

    The for...in statement iterates over all properties of an object (ignoring properties keyed by symbols), including inherited enumerable properties(i.e those inherited properties from the prototype chain). The syntax is written like so;

     for (let key in object) { 
         // executes the body for each key among object properties
         // note: we could use another variable name instead of `key`            
     }
    

    Let's make an example to print the key and value of all properties of my tesla;

     const myTesla = {
       model: "Roadster",
       capacity: "200 kWh",
       year: 2023
     };
    
     for (let prop in myTesla) {
       console.log(prop + ': ' + myTesla[prop]);
     }
     // outputs, 
     // model: Model S
     // capacity: 200 kWh
     // year: 2023
    

    Best Practices for Working with Objects

    Following these guidelines has made working with objects easier for me. So, I am suggesting them to you;

    1. Use object literals when possible

      It is advisable to use object literals instead of constructor functions, as they make your code more concise and easier to read.

    2. Use either the dot or bracket notation syntax consistently:

      Always maintain the use of one notation syntax(either dot or bracket notation) throughout your code, except you really need to use the other. This enhances the readability and maintainability of your code.

    3. Use const to declare object references

      This will prevent the object reference(i.e variable where the object is stored in memory) from being reassigned. We can still modify the object's properties, but we can't assign a new object to the myTesla variable.

Conclusion

In this article, we talked about;

  1. what objects are

  2. methods of creating objects

  3. working object properties and methods

  4. object manipulation

  5. Best practices for working with objects

Now that you have a good understanding of these concepts, keep practicing and sharing your knowledge with others. See you next time, thank you!