JavaScript : Objects

In JavaScript, objects are a fundamental data type that allows you to store collections of data in key-value pairs. Objects are used to represent real-world entities, and they are versatile and powerful constructs in JavaScript. Here's how you can work with objects in JavaScript:

1. Object Literal:


You can create an object using object literal notation, which consists of key-value pairs enclosed in curly braces {}.


let person = {
  name: "John",
  age: 30,
  isStudent: false
};

 

2. Accessing Object Properties:


You can access properties of an object using dot notation ( ) or bracket notation ( [] ).


console.log(person.name);      // Output: "John"
console.log(person["age"]);    // Output: 30

 

3. Adding or Modifying Properties:


You can add new properties or modify existing properties of an object.


person.city = "New York";  // Adding a new property
person.age = 35;            // Modifying an existing property

 

4. Nested Objects:


Objects can contain other objects as properties, allowing you to create nested data structures.


let student = {
  name: "Alice",
  age: 25,
  contact: {
    email: "alice@example.com",
    phone: "123-456-7890"
  }
};

 

5. Object Methods:


You can define functions as properties of an object, known as methods.


let car = {
  brand: "Toyota",
  model: "Camry",
  start: function() {
    console.log("Engine started");
  }
};

car.start();  // Output: "Engine started"
 

6. Object Constructor:


You can create objects using constructor functions or the Object constructor.


function Person(name, age) {
  this.name = name;
  this.age = age;
}

let john = new Person("John", 30);
 

7. Object Destructuring:


You can extract properties from objects and assign them to variables using object destructuring.


let { name, age } = person;
console.log(name);  // Output: "John"
console.log(age);   // Output: 30

 

8. Object Iteration:


You can iterate over the properties of an object using for...in loop or Object.keys() method.


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

 

Example Usage:

Here's an example demonstrating various operations with objects in JavaScript:


let person = {
  name: "John",
  age: 30,
  isStudent: false
};

console.log(person.name);        // Accessing property
person.city = "New York";        // Adding property
console.log(person.city);        // Output: "New York"

let student = {
  name: "Alice",
  age: 25,
  contact: {
    email: "alice@example.com",
    phone: "123-456-7890"
  }
};

console.log(student.contact.email);  // Nested property access
 

Conclusion:


Objects are a powerful feature of JavaScript, allowing you to represent complex data structures and organize related data. By understanding how to create, access, modify, and iterate over objects, you can effectively work with data in your JavaScript programs. Objects are essential for building robust and maintainable JavaScript applications.