Javascript Creating objects

To store and manage data, objects are utilized in JavaScript. A collection of properties, each of which is a key-value pair, make up an object. The values of an object can be any data type, while the keys are always strings.

Syntax:

let obj = {
  key1: value1,
  key2: value2,
  key3: value3,
  ...
};

Example:

let person = {
  name: "John",
  age: 30,
  address: {
    street: "123 Main St",
    city: "Anytown",
    state: "CA"
  },
  hobbies: ["reading", "music", "traveling"],
  sayHello: function() {
    console.log("Hello, my name is " + this.name + " and I am " + this.age + " years old.");
  }
};

In this example, we have created an object called person. It has four properties: name, age, address, and hobbies. The address property is itself an object with three sub-properties: street, city, and state. The hobbies property is an array of strings. The sayHello property is a function that logs a greeting to the console, using the name and age properties of the person object.

To access the properties of an object, we use dot notation or bracket notation. Here’s an example:

console.log(person.name); // Output: "John"
console.log(person["age"]); // Output: 30
console.log(person.address.city); // Output: "Anytown"
console.log(person.hobbies[1]); // Output: "music"
person.sayHello(); // Output: "Hello, my name is John and I am 30 years old."

In this example, we are accessing the name, age, city, and hobbies properties of the person object using both dot notation and bracket notation. We are also calling the sayHello method on the person object.