Skip to content

Understanding Objects in JavaScript

By learning about objects in JavaScript, you can model real-world entities and organize your code better.

Objects in JavaScript are created using key-value pairs. Each key represents a property name, and the value can be of any type (e.g., string, number, array, function, or even another object). Below is a simple example:

Here, the person object has three properties: name, age, and isStudent.

const person = { name: "John Doe", age: 25, isStudent: true };

You can access object properties in two ways:

Dot notation is the most commonly used way to access properties:

console.log(person.name); // "John Doe"

Bracket notation is useful when the property name is a variable or contains special characters:

const key = "age";
console.log(person[key]); // 25
const anotherObject = { "first-name": "Alice" };
console.log(anotherObject["first-name"]); // "Alice"

Use dot notation for simplicity, and switch to bracket notation when necessary.

Adding, Modifying, and Deleting Properties

Section titled “Adding, Modifying, and Deleting Properties”

Objects are dynamic, meaning you can add, modify, or delete properties at any time.

You can add a new property using either dot or bracket notation:

const person = { name: "John Doe", age: 25, isStudent: true };
person.gender = "Male"; // Dot notation
person["hobby"] = "Reading"; // Bracket notation
console.log(person); // { name: "John Doe", age: 25, isStudent: true, gender: "Male", hobby: "Reading" }

To update an existing property, simply reassign its value:

const person = { name: "John Doe", age: 25, isStudent: true };
person.age = 30;
console.log(person.age); // 30

Use the delete operator to remove a property:

const person = { name: "John Doe", age: 25, isStudent: true };
delete person.isStudent;
console.log(person); // { name: "John Doe", age: 30, gender: "Male", hobby: "Reading" }

Objects can contain other objects as values, helping you represent complex data structures. For example:

const student = {
name: "Emily",
grade: 12,
subjects: { math: "A", science: "B" },
};
console.log(student.subjects.math); // "A"

To access nested properties, chain the dot or bracket notation.

A method is simply a function defined as a property of an object. Methods are a powerful way to group behavior with related data.

const car = {
brand: "Tesla",
model: "Model 3",
start: function () {
console.log("Car is starting...");
},
};
car.start(); // "Car is starting..."

Inside a method, this refers to the object that called the method, giving access to the object’s other properties:

const user = {
firstName: "Jane",
lastName: "Smith",
fullName: function () {
return `${this.firstName} ${this.lastName}`;
},
};
console.log(user.fullName()); // "Jane Smith"

As we discussed in pervious articles, while normal functions have their own this, arrow functions inherit this from the surrounding context. This distinction is important when defining methods in objects.