Prateek Budhiraja
Prateek Budhiraja

Prateek Budhiraja

In-Depth Guide to JavaScript Objects

In-Depth Guide to JavaScript Objects

Learn about how javascript object works, how we can create our own objects, take a sneak peek into console object and much more!

Prateek Budhiraja's photo
Prateek Budhiraja
Β·Sep 14, 2022Β·

6 min read

Subscribe to my newsletter and never miss my upcoming articles

Objects are said to be the backbone, the skeleton of javascript. And almost everything in javascript is an object! Which makes learning and mastering objects absolute necessary! In this blog, we'll try to understand what an object is, and why we even need an object in the first place. Let's start!

What are Objects?

Objects are nothing but an entity to store data.

Isn't there a thing in javascript which is called a "variable" for this same purpose?

Yes, we have variables to store data, but with objects, we can club some properties of a particular entity into a single place. Objects can have some properties and some behaviours, which are stored as a key-value pair. And the concept of Object came from real-life objects.

Let's take an example of a Car πŸš—

Car has some properties like price, color, capacity, engine (and it further can have more features), etc. and it also has some behaviour or functionality like engine start, accelerate, brake and so on.

object-car.png

So in real life, we have objects with properties and behaviours, similarly, in programming as well we have these things, we can call properties as variable of object and can call behaviour as function/method.

Why do we even write programs?

To solve real-world problems!

So it makes sense that we took the concept from the real world to solve the problems of the real world.

How do we create objects?

As stated earlier, objects store data in key-value pairs. We will see different ways in which we can declare objects and along the way, we will write code for a couple of use cases so that the use of objects makes absolute sense.

πŸ”΅ Declarative/Literal

Creating Objects using this method is as simple as it gets, we can declare and implement objects just like we declare arrays, we just need to use curly brackets ({}) instead of [] as we do in the case of arrays.

var myObject = {
  key: "value",
}

So we just named our object myObject and assigned it data as a key-value pair inside {}. If we console log myObject, we get the below output.

image.png

There are many methods with which we can access this key, one of which is by using . operator, so the syntax is objectName.propertyName.

Here in this case we can use myObject.key


πŸ”΅ Constructor

We can initialize objects using the new keyword and Object constructor.

var myObj = new Object();
myObj.key = "value";

If we try to console log myObj, it will produce 100% same results. But we usually create new objects with declarative syntax instead of using new!


πŸ”΅ Functional Approach

With this approach, we can design a template, and on basis of that, we can create new objects using new keyword!

Let's understand it with an example:

const Laptop = function (brand, model, price) {
    this.brand = brand;
    this.model = model;
    this.price = price;
    this.buy = function (quantity) {
        return `You have successfully bought ${quantity} ${this.model} from ${
            this.brand
        }.
Your total bill is ${price * quantity} rupees.`;
    };
};

let macbook = new Laptop("apple", "macbook-air", 90000);
let pavillion = new Laptop("hp", "pavillion 14s", 80000);

console.table(macbook);
console.log(macbook.buy(2));

So first we designed a template with variables brand, model and price. And we are accepting them as an argument. Then we have a function called buy, which can be invoked by any object which is created using this template. We can use new keyword for creating different objects and those objects will have all the properties and behaviours we have defined!

Now when we print it to the console, we get the below output!

image.png


There are many more ways in which we can create new objects, let's discuss one more!

πŸ”΅ Object's create function

It is similar to the functional approach, but we don't create a function, instead, we create a prototype of the object and we use the prototype to create brand-new objects.

// prototype for "User" object
const User = {
    firstName: "",
    lastName: "",
    userName: "",
    password: "",
};

// initializing object name "prateek" using "create" method
const prateek = Object.create(User);

// assigning values to object variables
prateek.firstName = "Prateek";
prateek.lastName = "Budhiraja";
prateek.userName = "prateek-budhiraja";
prateek.password = "12345";

console.table(prateek);

image.png

Till now, it is simple, but the problem arises when we need to pass default values for the object at the time of object creation. We can surely do that, but the syntax is a little tricky. See how we can pass values at the time of creation.

const User = {
    firstName: "",
    lastName: "",
    userName: "",
    password: "",
};

const prateek = Object.create(User, {
    firstName: { value: "Prateek" },
    lastName: { value: "Budhiraja" },
    userName: { value: "prateek-budhiraja" },
    password: { value: "12345" },
});

image.png


Accessing Object's properties and behaviours

Before moving on to the examples, first, let's look at some of the ways in which we can access object values.

Example Object:

const Laptop = {
    brand: "apple",
    model: "macbook air",
    price: 89000,
  buy: function () {
        console.log(`You have successfully bought ${this.model} from ${this.brand}`);
  }
};

console.log(Laptop);
console.table(Laptop);

image.png

πŸ”΅ Using . operator

As seen above, we can use the dot operator to access object properties and behaviours.

console.log(Laptop.brand);  // access Laptop brand
Laptop.buy();      // trigger buy method from Laptop

image.png

Oh, wait a second, isn't this syntax similar to our console.log()? Does that mean...?

Yes! You guessed it right! console is also an object! To prove it, we try to run the below code!

console.log(console);

image.png

We have so many methods that are already defined inside console object. Now you might have already guessed how console object must be written.

const console = {
  log: function(...argv) {
    // code to print on console
  },
  table: function(...argv){
    // code to print data in table format
  },
  // more methods ...
  // ...
}

This is almost true, we can verify the prototype of the console log from the node source code.

image.png

We can see that it is using _stdout.write to print on our console!

Going up next we have more ways to access object variables, but as we just saw that javascript language itself is using dot operator, so it is the recommended way of doing things, but still, we have more ways which we'll discuss just for the sake of completion.


πŸ”΅ Using []

We can use square brackets just like we use with arrays, just that we need to put key name in quotes to access the values.

const Laptop = {
    brand: "apple",
    model: "macbook air",
    price: 89000,
    buy: function () {
        console.log(
            `You have successfully bought ${this.model} from ${this.brand}`
        );
    },
};

console.log(Laptop["price"]);

let brand = "brand";
console.log(Laptop[brand]);      // using variable inside brackets

Example of Objects

Apple Store 🍏

Here we will design an array of objects to store products in an Apple Store.

const appleStore = [
    {
        prodName: "Iphone 14",
        launchDate: new Date(2022, 08, 15),
        quantity: 65,
        price: 100000,
        colors: ["white", "black", "purple"],
    },
    {
        prodName: "Iphone 14 pro",
        launchDate: new Date(2022, 08, 15),
        quantity: 10,
        price: 120000,
        colors: ["white", "black", "purple", "blue"],
    },
    {
        prodName: "Macbook air 2022",
        launchDate: new Date(2022, 03, 11),
        quantity: 19,
        price: 90000,
        colors: ["white", "black"],
    },
    {
        prodName: "Macbook pro",
        launchDate: new Date(2022, 07, 11),
        quantity: 40,
        price: 200000,
        colors: ["white", "black"],
    },
];

console.log(appleStore[1]);

image.png

I hope you learned something new, if you wish to read more about these topics, you can refer to the resources below! You can also comment down your thoughtsπŸ€

Happy Learning ⭐

Resources

Β 
Share this