1. Overview

In JavaScript, objects are versatile data structures used for storing collections of named fields, known as properties. Each property has a unique key and a corresponding value. Objects are incredibly flexible and widely used in various applications, ranging from simple data storage to complex program structures.

2. Creating Objects

Using Object Literals:
The simplest and most common way to create objects is by using object literals, denoted by curly braces {}. Properties are defined within the object literal as key-value pairs separated by commas.

Example 1:

let testObj = {};
console.log(typeof testObj); // -> object

Example 2:

let testObj = {
    nr: 500,
    str: "text"
};

3. Accessing Object Properties

Properties of an object can be accessed using dot notation or bracket notation.

let testObj = {
    nr: 500,
    str: "text"
};

console.log(testObj.nr);  // -> 500
console.log(testObj.str);  // -> text

4. Use Cases of Objects

Objects are invaluable for storing related data in a structured manner. Consider the scenario of managing user information. Instead of using separate variables for each user attribute, objects provide a more organized approach.

Without Object:

let employee1Name = "Alice";
let employee1Surname = "Smith";
let employee1Age = 35;
let employee1Email = "alice.smith@example.com";

let employee2Name = "Bob";
let employee2Surname = "Johnson";
let employee2Age = 28;
let employee2Email = "bob.johnson@example.com";

With Object:

let employee1 = {
    firstName: "Alice",
    lastName: "Smith",
    age: 35,
    email: "alice.smith@example.com"
};

let employee2 = {
    firstName: "Bob",
    lastName: "Johnson",
    age: 28,
    email: "bob.johnson@example.com"
};

5. Modifying Objects

Properties of an object can be modified or added using dot notation.

console.log(employee1.age); // -> 35
employee1.age = 35;
console.log(employee1.age); // -> 35

employee2.phone = "922-399-8875";
console.log(employee2.phone); // -> 922-399-8875

6. Deleting Object Properties

The delete operator is used to remove properties from an object.

console.log(employee2.phone); // -> 922-399-8875
delete employee2.phone;
console.log(employee2.phone); // -> undefined

7. Summary

Objects in JavaScript serve as powerful tools for organizing and manipulating data. Understanding how to create, access, modify, and delete object properties is essential for effective programming. While this tutorial covers the basics of objects, there are advanced concepts in object-oriented programming that further enhance their utility.

8. Exercise

An object named Avenger1 contain the following properties:

  • Name: Ironman
  • Age: 38
  • Power: Genius-level intellect

1. Write the JavaScript code to create the object with these properties.

2. Write JavaScript code to update the age of Avenger1 to 40.

3. Write JavaScript code to remove the power property from Avenger1.

End Of Article

End Of Article