JavaScript Objects

In this chapter, we will learn about JavaScript objects. Objects are a collection of properties, and each property is an association between a key and a value. We will cover:

  • What are Objects?
  • Creating Objects
  • Accessing Object Properties
  • Modifying Object Properties
  • Adding and Deleting Properties
  • Methods
  • Iterating Over Object Properties
  • Nested Objects
  • Built-in Object Methods
  • Simple Programs using Objects

What are Objects?

An object is a collection of properties, where each property is a key-value pair. Objects are used to store related data and functions.

Creating Objects

You can create objects using object literals or the Object constructor.

Syntax

// Object literal
let objectName = {
  key1: value1,
  key2: value2,
  // ...
};

// Object constructor
let objectName = new Object();
objectName.key1 = value1;
objectName.key2 = value2;

Examples

// Using object literal
let person = {
  firstName: "Ramesh",
  lastName: "Fadatare",
  age: 30,
  occupation: "Engineer"
};

// Using Object constructor
let car = new Object();
car.make = "Toyota";
car.model = "Camry";
car.year = 2020;

Accessing Object Properties

You can access object properties using dot notation or bracket notation.

Dot Notation

let person = {
  firstName: "Ramesh",
  lastName: "Fadatare"
};

console.log(person.firstName);
console.log(person.lastName);

Output:

Ramesh
Fadatare

Bracket Notation

let person = {
  firstName: "Ramesh",
  lastName: "Fadatare"
};

console.log(person["firstName"]);
console.log(person["lastName"]);

Output:

Ramesh
Fadatare

Modifying Object Properties

You can modify object properties by assigning a new value to the property.

Example

let person = {
  firstName: "Ramesh",
  lastName: "Fadatare",
  age: 30
};

person.age = 31;
console.log(person.age);

Output:

31

Adding and Deleting Properties

You can add new properties to an object or delete existing properties.

Adding Properties

let person = {
  firstName: "Ramesh",
  lastName: "Fadatare"
};

person.age = 30;
console.log(person);

Output:

{ firstName: 'Ramesh', lastName: 'Fadatare', age: 30 }

Deleting Properties

let person = {
  firstName: "Ramesh",
  lastName: "Fadatare",
  age: 30
};

delete person.age;
console.log(person);

Output:

{ firstName: 'Ramesh', lastName: 'Fadatare' }

Methods

A method is a function stored as a property of an object.

Example

let person = {
  firstName: "Ramesh",
  lastName: "Fadatare",
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
};

console.log(person.fullName());

Output:

Ramesh Fadatare

Iterating Over Object Properties

You can iterate over object properties using a for...in loop.

Example

let person = {
  firstName: "Ramesh",
  lastName: "Fadatare",
  age: 30
};

for (let key in person) {
  console.log(key + ": " + person[key]);
}

Output:

firstName: Ramesh
lastName: Fadatare
age: 30

Nested Objects

Objects can contain other objects as properties, creating nested objects.

Example

let student = {
  name: "Priya",
  age: 21,
  address: {
    street: "MG Road",
    city: "Bangalore",
    state: "Karnataka"
  }
};

console.log(student.address.city);

Output:

Bangalore

Built-in Object Methods

JavaScript provides several built-in methods to work with objects.

Object.keys()

The Object.keys method returns an array of a given object’s property names.

let person = {
  firstName: "Ramesh",
  lastName: "Fadatare",
  age: 30
};

let keys = Object.keys(person);
console.log(keys);

Output:

["firstName", "lastName", "age"]

Object.values()

The Object.values method returns an array of a given object’s property values.

let person = {
  firstName: "Ramesh",
  lastName: "Fadatare",
  age: 30
};

let values = Object.values(person);
console.log(values);

Output:

["Ramesh", "Fadatare", 30]

Object.entries()

The Object.entries method returns an array of a given object’s own enumerable string-keyed property [key, value] pairs.

let person = {
  firstName: "Ramesh",
  lastName: "Fadatare",
  age: 30
};

let entries = Object.entries(person);
console.log(entries);

Output:

[["firstName", "Ramesh"], ["lastName", "Fadatare"], ["age", 30]]

Object.assign()

The Object.assign method copies all enumerable own properties from one or more source objects to a target object.

let target = { a: 1, b: 2 };
let source = { b: 4, c: 5 };

let returnedTarget = Object.assign(target, source);
console.log(returnedTarget);

Output:

{ a: 1, b: 4, c: 5 }

Object.freeze()

The Object.freeze method freezes an object, preventing new properties from being added and existing properties from being removed or modified.

let person = {
  firstName: "Ramesh",
  lastName: "Fadatare"
};

Object.freeze(person);
person.age = 30; // This will not work
console.log(person);

Output:

{ firstName: 'Ramesh', lastName: 'Fadatare' }

Object.seal()

The Object.seal method seals an object, preventing new properties from being added and marking all existing properties as non-configurable.

let person = {
  firstName: "Ramesh",
  lastName: "Fadatare"
};

Object.seal(person);
person.age = 30; // This will work
delete person.lastName; // This will not work
console.log(person);

Output:

{ firstName: 'Ramesh', lastName: 'Fadatare', age: 30 }

Simple Programs using Objects

Program 1: Create a Car Object and Print its Properties

let car = {
  make: "Maruti",
  model: "Swift",
  year: 2021,
  displayInfo: function() {
    return `${this.make} ${this.model} (${this.year})`;
  }
};

console.log(car.displayInfo());

Output:

Maruti Swift (2021)

Program 2: Calculate the Average Age of Students

let students = [
  { name: "Amit", age: 20 },
  { name: "Neha", age: 22 },
  { name: "Ramesh", age: 19 }
];

let totalAge = 0;

for (let student of students) {
  totalAge += student.age;
}

let averageAge = totalAge / students.length;
console.log("Average age:", averageAge);

Output:

Average age: 20.333333333333332

Program 3: Find the Oldest Person

let people = [
  { name: "Amit", age: 20 },
  { name: "Neha", age: 25 },
  { name: "Ramesh", age: 22 }
];

let oldest = people[0];

for (let person of people) {
  if (person.age > oldest.age) {
    oldest = person;
  }
}

console.log("Oldest person:", oldest.name);

Output:

Oldest person: Neha

Program 4: Group People by Age

let people = [
  { name: "Amit", age: 20 },
  { name: "Neha", age: 22 },
  { name: "Ramesh", age: 20 },
  { name: "Priya", age: 22 }
];

let groupedByAge = {};

for (let person of people) {
  if (!groupedByAge[person.age]) {
    groupedByAge[person.age] = [];
  }
  groupedByAge[person.age].push(person.name);
}

console.log(groupedByAge);

Output:

{ '20': [ 'Amit', 'Ramesh' ], '22': [ 'Neha', 'Priya' ] }

Program 5: Clone

an Object

let original = {
  name: "Amit",
  age: 25
};

let clone = Object.assign({}, original);
console.log(clone);

Output:

{ name: 'Amit', age: 25 }

Conclusion

In this chapter, you learned about JavaScript objects, including their creation, accessing and modifying properties, adding and deleting properties, methods, iterating over object properties, nested objects, and built-in object methods. We also provided various use cases with simple programs to demonstrate the usage of objects. Objects are a fundamental data structure in JavaScript, allowing you to store and manipulate collections of data.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top