Object

In JavaScript, an object is a complex data type that can hold various values and functions, which are called properties and methods respectively. Objects are used to store and organize data in a structured way, and they are an essential part of the language.

An object in JavaScript is created by defining a variable and assigning it to an object literal using curly braces {}. Here's an example:

let person = {
  name: "John",
  age: 30,
  occupation: "Software Developer",
  greet: function() {
    console.log("Hello, my name is " + this.name + " and I am a " + this.occupation);
  }
};

In the example above, we have created an object called person that has four properties: name, age, occupation, and greet. The first three properties are simple string and number values, while greet is a function.

We can access and modify the values of an object's properties using dot notation or bracket notation. Here are some examples:

// Accessing properties using dot notation
console.log(person.name); // "John"
console.log(person.age); // 30

// Modifying properties using dot notation
person.age = 35;
console.log(person.age); // 35

// Accessing properties using bracket notation
console.log(person["occupation"]); // "Software Developer"

// Modifying properties using bracket notation
person["name"] = "Jane";
console.log(person.name); // "Jane"

We can also add new properties and methods to an object at any time using dot notation or bracket notation:

// Adding a new property using dot notation
person.email = "john@example.com";
console.log(person.email); // "john@example.com"

// Adding a new method using dot notation
person.sayHello = function() {
  console.log("Hello, my name is " + this.name);
};

// Adding a new method using bracket notation
person["sayGoodbye"] = function() {
  console.log("Goodbye!");
};

Objects can also be used to create more complex data structures, such as arrays of objects, objects within objects, and so on. Here's an example of an array of objects:

let people = [
  {
    name: "John",
    age: 30,
    occupation: "Software Developer"
  },
  {
    name: "Jane",
    age: 25,
    occupation: "Designer"
  },
  {
    name: "Bob",
    age: 40,
    occupation: "Manager"
  }
];

console.log(people[1].name); // "Jane"

In this example, we have created an array called people that contains three objects, each with its own set of properties. We can access the properties of each object using dot notation and bracket notation as before, but we can also access the objects themselves using array notation.

Last updated