Skip to main content

Command Palette

Search for a command to run...

Understanding Objects in JavaScript

Updated
•7 min read•View as Markdown
Understanding Objects in JavaScript

Before understanding what an object is, let’s first understand why we need it.

As we know, an array allows us to store multiple elements. However it becomes less suitable when we need to store structured information about each item.

For example:

suppose we want to store details about a laptop, such as its RAM, storage capacity, processor, etc. If we try to store this information in an array, it might look something like this which does make any sense.

let laptop = [8, 512, "ryzen 5"]

To solve this problem object exit.


What is an Object?

Object is an Non-primitive data type and it's a collection of related data,

In object data stored in key-value pairs, each key is a string and value can be any data type including: string, number, array, function or object.

In JavaScript everything is treated as object except primitive data types including string, number, bigint, undefined etc.

We can assume object like a student ID card that stores related information about one person.

Student information like his:

  • Name

  • Roll Number

  • Class

  • Age

  • Photo

const student = {
  name: "Rahul",
  rollNumber: 21,
  class: "10th",
  age: 15
};

Creating objects

There are 2 ways to create an object in JavaScript.

Object literal:

Object literal is the simplest and common way to create an object. for that we just need to assign empty curly brases {} or with initial value inside it.

const hokage = {
    firstName: "Naruto",
    lastName: "Uzumaki",
};

Object constructor

JavaScript provides a built-in Object() constructor to create objects. to create an object we just have to assign Object() constructor with new keyword and empty object will create.

const obj = new Object();

Accessing properties

There are 2 ways to access properties in object

  • Dot notation

  • Bracket notation

Dot notation

Dot notation is the simple and common way to access elemets in JavaScript, for that we just have to put .propertyName .

it is used when property is known and valid identifier. like property name must not have spaces between, not start with any digit and not have any special character.

const laptop = {
  brand: "Lenovo",
  ram: "16GB",
  processor: "Intel i7"
};

console.log(laptop.brand);      // Dell
console.log(laptop.ram);        // 16GB

Bracket Notation

Bracket notation is more flexible than Dot notation, for accessing the property its necessary that it exist in object,

It's commonly used when property name contains spaces or special symbols.

const movie = {
  "full name": "Tanjiro"
};

console.log(user["full name"]); // Tanjiro

Updating object properties

Updating an object means changing the value of an existing property. and it is as simple as accessing property which have assign new value after that.

There is also 2 ways to update object properties

Dot Notation

In Dot notation we just have to assign new value after accessign any property.

const laptop = {
  brand: "Lenovo",
  ram: "16GB"
};

// update property
laptop.ram = "32GB";

console.log(laptop.ram); // 32GB

Bracket Notation

As we discussed bracket notation is mainly used when property name has spaces or property name is a digit, which can't be accessed by Dot notation. but here we can access and update.

const laptop = {
  "brand name": "Dell",
  ram: "16GB",
};

// update property
laptop["brand name"] = "HP";

console.log(laptop["brand name"]); // HP

Adding and Deleting Properties

Addign and deleting object properties is also easy in JavaScript.

Adding property using Dot notation

Using dot notation, we can define a property name and assign a value to it. This adds the property to the object.

  • If the property does not exist --> it adds a new property.

  • If the property already exists --> it updates the value.

const user = {};

user.name = "Alex";  
user.name = "John"; 

Adding using Bracket notation

Using bracket notation we specify the property name inside square brackets and assign a value to it. This adds the property to the object.

const laptop = {};

laptop["brand name"] = "Lenovo";  // property added

console.log(laptop)

Deleting property using Dot notation

For deleting an property from object we use delete operator and specify property name using dot notation.

const laptop = {
  brand: "Lenovo",
  ram: "16GB",
  processor: "Intel i7"
};

delete laptop.ram;

console.log(laptop);
// { brand: "Lenovo", processor: "Intel i7" }

Deleting property using Bracket notation

Same as dor notation in this we also have to use delete operator but with bracket notation.

And as we know that we use bracket notation when there is any space in property name or property name is a digit.

const laptop = {
  "brand name": "Lenovo",
  ram: "16GB",
  processor: "Intel i7"
};

delete laptop["brand name"];

console.log(laptop);
// { ram: '16GB', processor: 'Intel i7' }

You might think that a variable declared with const cannot be modified. Let’s clarify:

we cannot reassign a const variable, but in JavaScript objects are copied by reference. This means that even if we add or delete properties, the reference to the object remains the same.

However, if we try to assign a completely new object to that variable, it will throw an error.
Looping through object keys


Looping through object keys

There buit-in methods for looping over object in JavaScript, but the most common is for...in loop.

It used to iterate over the properties (keys) of an object.

const laptop = {
  brand: "Dell",
  ram: "16GB",
  processor: "Intel i7"
};

for (let key in laptop) {
  console.log(key);          // property name
  console.log(laptop[key]);  // property value
}

For accessing the value we use [] because here key is an variable so dot notation would not work here.

There are some object methods like Object.keys(), Object.values() and Object.entries() which returns array of properties and we can loop over them using array methods like map(), filter(), forEach().


Array vs Object

Feature Array Object
Definition Ordered collection of values Collection of key–value pairs
Structure Ordered list of values Collection of key–value pairs
Access By index By property name (key)
Use Case Store similar items Store related data about one entity
Syntax [] {}

Assignments

  1. Create an empty object representing student using object literal or Object() constructor.

  2. Assign values like name, age, course using dot or bracket notation.

  3. Now update any one property

  4. Try to print all key and values using for...in loop and see the result on console


Conclusion

As we discussed at the beginning, arrays can also store multiple values like objects.

However, arrays are not suitable for storing related pieces of information together. That is why objects exist so we can store related data about something in a structured way.

We have discussed almost everything about objects, from creating an object to looping over its properties.

Hope you like this article❤️