Previous Page : JavaScript Functions

In JavaScript, an object is an unordered collection of key-value pairs. Objects are a fundamental building block of the language and are used to represent real-world entities, such as a person, an animal, or a computer.

Objects can be created using the object literal notation, which consists of an opening and closing brace, {}, with key-value pairs separated by commas. For example:

let person = {
  name: "John Doe",
  age: 30,
  address: {
    street: "123 Main St",
    city: "San Francisco",
    state: "CA"
  }
};

In the example above, person is an object with three properties: name, age, and address. The address property is itself an object, with three properties of its own: street, city, and state.

Properties of an object can be accessed using dot notation, such as person.name, or square bracket notation, such as person["name"]. For example

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

JavaScript also provides several built-in objects, such as Array, Date, Math, RegExp, and many others. These objects provide a variety of useful methods and properties for working with data.

Objects can also be used to create custom objects, which are objects that are created using a constructor function. Custom objects are created using the new operator and a constructor function. For example:

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

let john = new Person("John Doe", 30, {
  street: "123 Main St",
  city: "San Francisco",
  state: "CA"
});

In the example above, Person is a constructor function that creates objects with name, age, and address properties. The new operator creates a new instance of the Person object, which is stored in the variable john.

Objects are a versatile and powerful data structure in JavaScript and are used in a variety of ways, from storing data to organizing and structuring code. Understanding objects is essential for becoming proficient in JavaScript.

JOIN WHATSAPP COMMUNITY FOR MORE SUCH AWESOME CONTENT :