Skip to main content

Command Palette

Search for a command to run...

Understanding Objects in JavaScript

Updated
8 min read

"Everything in Javascript is an Object". Object is a datatype in javascript used for storing data. Objects store data in key-value pair, the data you want to store should always have a key. This key will help you in accessing, updating the value, it's kind of name of that value you use that key to access the value. Under the hood all the datatypes string, number, boolean etc all are objects.
Since we now know that, objects are very important part/datatype in Javascript so let's understand how to create an object.

Creating Objects

There are many ways in Javascript for creating an object. Let's understand the important one, one by one.

1. Object Literal (Most Common One)

This is the most common & simplest way of creating an object in JS. Here, You simply have to use {} for creating an object.

const student = {
        name: "Vishal",
        age: "20",
        hello(){
            console.log("Hello EveryOne")
        }
    }

We have created an object using curly brackets {}, this object have 2 properties "name" & "age" and a method "hello".

Let's understand how this looks like at memory level.

The variable having reference of this object is in stack memory and the actual object is in the heap memory.

2. Using "new" (The Constructor way)

There is parent class for every datatype string have String, number have Number similarly object have Object.

Now using this class constructor we can create a new instance(object) of this Object class. This method is used for creating instances.

const student = new Object();
student.name = "Vishal",
student.age = "20",
student.greet = function(){
    console.log("Hello EveryOne")
}

console.log(student);

------------------------------------------------------------------
OUTPUT:
{ name: 'Vishal', age: '20', greet: [Function (anonymous)] }

Here the flow would be like this :

new --> created an empty object of Object Class --> then you added properties, methods

3. Using "Object.create()" (Might use sometime)

const proto = {
    greet(){
        console.log("Hello EveryOne")
    }
}
const student = Object.create(proto);
student.name = "Vishal";
student.age = "20",
student.greet()

console.log(student);

------------------------------------------------------------------
OUTPUT:
Hello EveryOne
{ name: 'Vishal', age: '20' }

Object.create takes prototype as an argument and then create an empty object with the specified prototype.

Then we have added the properties like "name" & "age" to this object.

These are the most common way of creating an object, you can create an object with factory function, function constructor, from classes but they are bit similar to the "new" way of creating a object.


Accessing Properties

This section of article will make you familiar with accessing values in the objects. Their are two ways to do it. Let's understand both of them.

dot(.) Notation:

We can access values of object by using "." you have to first write name of the variable referencing to that object then . and then keys this will give you value corresponding to that key.

const student = {
    name: "Vishal",
    age:"20"
}
console.log(student.name);
console.log(student.age);

------------------------------------------------------------------
OUTPUT:
Vishal
20

We are able to access name and age of student object.

[NOTE]: You can only access values using dot notation if the property / key is a valid identifier. Let's see the cases where you cannot use dot notation.

  • Property have space in them:
    If the property have space in their name then we cannot access that property using dot notation. We're not allowed to do this student.first name
const student = {
    "first name": "Vishal",
    age:"20"
}
console.log(student.first name); // This will throw ERROR
  • Property Name starts with a number:
    If the property name starts with number then also you cannot access it's value using dot notation.
const class10 = {
    "1stRank": "Vishal",
}
console.log(class10.1stRank); // This will throw ERROR
  • Property Name have a special character:
    If the property name have a special character like #, @, - then also you cannot access them using dot notation.
const product = {
  "item-price": 100
};

console.log(product.item-price);    // This will throw ERROR

If we cannot access them using dot notation then how to access them?

bracket ([]) Notation:

Bracket notation is more safer way for accessing properties in an object it works fine with all sort of cases. You simply have to write name of object and then [] inside bracket you have to pass string (key).

const student = {
    name: "Vishal",
    age:"20"
}
console.log(student["name"]);
console.log(student["age"]);

------------------------------------------------------------------
OUTPUT:
Vishal
20

This way of accessing values works fine in all the cases like

  • Property have space in them
const student = {
    "first name": "Vishal",
    age:"20"
}
console.log(student["first name"]);

------------------------------------------------------------------
OUTPUT:
Vishal
  • Property Name starts with a number
const class10 = {
    "1stRank": "Vishal",
}
console.log(class10["1stRank"]); 

------------------------------------------------------------------
OUTPUT:
Vishal
  • Property Name have a special character
const product = {
  "item-price": 100
};

console.log(product["item-price"]);  

------------------------------------------------------------------
OUTPUT:
100

Updating Properties

If you want to change the value of the property in an object you simply had to access the property and pass it's new value their.

const product = {
  price: 100
};

product.price = 200;
console.log(product)

------------------------------------------------------------------
OUTPUT:
{ price: 200 }

Always remember Objects are always pass by reference so , if you take reference of object and store it to another variable and updated any property using that new variable the change will be in original object.

const product = {
  price: 100
};

const newProduct = product

newProduct.price = 200;
console.log(product)

------------------------------------------------------------------
OUTPUT:
{ price: 200 }

Here we're changing value of newProduct object but the change is happening in product, this is because of how object are passed object always passed by reference this is the main reason behind this kind of behavior.

For copying product into newProduct you need to use spread operator ... then if you make changes in newProduct the changes will only be reflected in newPrduct.

const product = {
  price: 100
};

const newProduct = {...product}

newProduct.price = 200;
console.log(product)
console.log(newProduct)

------------------------------------------------------------------
OUTPUT:
{ price: 100 }
{ price: 200 }

[NOTE]: In case of nested object spread operator will work only for one level of nesting all the object after that level again will be passed as reference so in the case of nested object use structuredClone() .


Adding & Deleting Properties

Adding:

Adding property is similar to accessing it if you want to add any property you can simply use dot notation or bracket notation for it they will add the new property and it's value to the object.

const product = {
  price: 100
};

product.discount = "10%"
product["afterDiscount"] = 90;
console.log(product)

------------------------------------------------------------------
OUTPUT:
{ price: 100, discount: '10%', afterDiscount: 90 }

For adding multiple properties you can use Object.assign() method

const product = {
  price: 100
};

Object.assign(product, {discount: "20%", afterDiscount: 80})
console.log(product)

------------------------------------------------------------------
OUTPUT:
{ price: 100, discount: '20%', afterDiscount: 80 }

Deleting:

For deleting properties, you have to use delete operator, you simply have to write delete before the property then it will be removed from the object

const product = { price: 100, discount: '20%', afterDiscount: 80 }

delete product.discount;
delete product["afterDiscount"]
console.log(product)

------------------------------------------------------------------
OUTPUT:
{ price: 100 }

[NOTE]: delete only removes the reference of the property from the object it will still be present in the memory until garbage collection happens.


Looping through Object

Objects are not iterable like arrays but their are some ways/ technique by which we can iterate over them.

1. For in loop:

We can use this loop to iterate over keys of the object and we can access value corresponding to that key using that key.

const user = {
  name: "Rahul",
  age: 25,
  city: "Delhi"
};

for (let key in user) {
  console.log(key, user[key]);
}

------------------------------------------------------------------
OUTPUT:
name Rahul
age 25
city Delhi

2. Object.keys() / Object.values():

We can use Object.keys() method this will return an array of all the keys and we can iterate over that array and access corresponding values. Similarly, for values we can use Object.values() this will create an array of values of that object and we can then iterate over that array.

const user = {
  name: "Rahul",
  age: 25,
  city: "Delhi"
};

Object.keys(user).forEach((key) => {
    console.log(key, user[key])
})

console.log("VALUES")
Object.values(user).forEach((value) => {
    console.log(value)
})

------------------------------------------------------------------
OUTPUT:
name Rahul
age 25
city Delhi
VALUES
Rahul
25
Delhi

3. Object.entries():

We can use Object.entries() this will give array of array having key value pair as element inside it. Then we can iterate over this array of array and can access, update the keys and values of objects.

const user = {
  name: "Rahul",
  age: 25,
  city: "Delhi"
};

for (const [key, value] of Object.entries(user)) {
  console.log(key, value);
}

------------------------------------------------------------------
OUTPUT:
name Rahul
age 25
city Delhi

Conclusion

To wrap up, working with objects is a fundamental part of building applications in JavaScript. From creating objects using different patterns to adding, updating, deleting, and iterating through their properties, understanding these techniques helps you manage data more effectively in your programs.