All you need to about JavaScript Objects

All you need to about JavaScript Objects

·

6 min read

Introduction

Almost everything in JavaScript is an Object. In this article, I'll share my understanding of what an object is, how an object can be created, modified, and how its properties can be accessed.

What is an Object?

An object is a collection of properties having name-value pairs. The value of the property could be a simple string, integer, boolean, or could be another object or even a function.

//Object with the value String
const name = 'Skay';

//Object with the value Integer
let number = 5;

//Object with the value boolean
let isCorrect = true;

//Object with the value of another Object
const car = {
    make : 'Honda',
    modal : 'CR-v',
    year : 2018
}

//Object with the value of a function
const greeting = function() {
    return 'Hello, How are you?';
}

Object Creation

In JavaScript, there are many ways to create an object. Let us look at each of them with examples.

Using the Object Literal

The simplest form of object creation is using the Object literal, which we saw in the 'Car' example above. Let us look at another example of the book object.

    const book = {
        name : 'Atomic Habits',
        author : 'James Clear',
        year : 2018
    }

The values assigned to an object within the braces are referred to as the properties of an object.

Using the New Keyword

Using the new keyword, you can first create the object and then add the properties to it later.

const book = new Object();
book.name = 'Atomic Habits';
book.author = 'James Clear';
book.year = 2018;

console.log(book);

Using a Constructor

Constructors are code snippets that run while creating an object. You can optionally pass parameters while the creation of an object. Generally, in modern object-oriented languages such as Java, the constructors are defined within a class and are used to create an instance of the class.

const Movie = function(title, director, genre, rating) {
    this.title = title;
    this.director = director;
    this.genre = genre;
    this.rating = rating;
    this.getDetails = function() {
        console.log(`${this.title} of the genre ${this.genre} has a rating of ${this.rating}. It is directed by ${this.director}.`);
    }
}

const matrix = new Movie('The Matrix', 'The Wachowski Brothers', 'Sci-Fi', 8.7);
const inception = new Movie('Inception', 'Christopher Nolan', 'Sci-Fi', 8.8);

console.log(matrix.getDetails());
console.log(inception.getDetails());

It is considered a good practice to use Capital letters while naming the constructor.

This method of creating an object is favored in real-life projects since you can create as many objects as you would like by using the new keyword and if you need to add/edit a property at a later time, it's very simple to do it within the constructor.

Another thing to note in the above example is that the property getDetails is also a function. What this means is that you can literally define anything as a property to an object, such as a literal, object, or a function that I mentioned at the beginning of this article.

There are two more ways to create an object. Using the object.create() method which was introduced with ES5 and using the prototype pattern. These will require some understanding of JavaScript Prototype and I will cover this in a separate article.

Accessing the Properties of an Object

The properties assigned to an object can be accessed using one of the two ways:

a. Using the '.' operator.

const book = {
        name : 'Atomic Habits',
        author : 'James Clear',
        year : 2018
    }

console.log(book.name);

b. Using the square brackets []

const book = {
        name : 'Atomic Habits',
        author : 'James Clear',
        year : 2018
    }

console.log(book["author"];

The dot operator is generally more popular in use, due to it's the simplicity of use. However, the other option is particularly useful in two instances

a. When the property name contains a space and cannot be used with a dot operator. Although, the chances of this are pretty rare.

b. If a property name of the object is only known at run-time. In the example below, person.propName will give an undefined, whereas a person[propName] will display 38.

const person = {
    name : 'Skay',
    age : 38
}

const propName = 'age';

//Will output 38
console.log(person[propName]);

//Will output undefined
console.log(person.propName);

Objects are referenced by Type

When a variable is assigned a non-primitive value (except string, integer, boolean, null, and undefined), then the variable is assigned a reference to the value and not the actual value.

If you did not understand a word of the above statement, don't worry, let us break it down by using the below code as a reference:

Step 1

As you can see the variable 'person' is assigned the object {name : 'skay', age : 38}. But what happens internally is that, the object {name : 'skay', age : 38} is stored in a location in your computer's memory.

const person = {
    name: 'Skay',
    age: 38
}

const newPerson = person;

console.log(newPerson === person);

Step 2

The memory location allocated to the object {name : 'skay', age : 38} is assigned to the variable 'person'.

Step 3

In the above code, when the newPerson variable is assigned to the person variable, then it also receives a reference of the same address location of the object {name : 'skay', age : 38} and hence the console.log(newPerson === person) will output the value of 'true'.

Conclusion

If you gotten until here, thank you so much for taking the time to read through the article, and hope you've gained some insight into what JavaScript objects are.

Let me summarize what I have covered so far in this article.

  • Except for primitive types such as strings, numbers, boolean, null, and undefined, everything else is an object in JavaScript. For example, an array is an object and so is a function.
  • In JavaScript objects are mutable, i.e. they can be changed.
  • Objects are referenced by type and hence the variable containing the object has a reference to the object and not the value.

Hope you enjoyed this article. Don't forget to subscribe to my newsletter and connect with me on Twitter @skaytech

You might also be interested in:

Did you find this article valuable?

Support Skay by becoming a sponsor. Any amount is appreciated!