JS Object

HTML
CSS
C#
SQL

Object

In JavaScript, objects serve as dynamic collections of key-value pairs, allowing for versatile data representation. They can encapsulate various data types, such as arrays, functions, and even other objects.

Here’s an example of how to create an object in JavaScript:

Object Properties:

Object properties are the values associated with a JavaScript object, forming unordered collections. Properties can be modified, added, or deleted dynamically.

Accessing object properties can be done through dot notation, square bracket notation, or an expression.

Example

person.firstname + ” is ” + person.age + ” years old.”;

person[“firstname”] + ” is ” + person[“age”] + ” years old.”;

Object Methods

In JavaScript, the `this` keyword refers to an object, and its reference depends on how it’s used. Methods, which are functions within objects, utilize `this` to refer to the object itself.

Example

Display Objects

Displaying JavaScript objects can be achieved through various methods. The default behavior often outputs `[object Object]`

Example:

Some common solutions to display JavaScript objects are:

Displaying Object Properties by Name:

Displaying specific object properties by name involves directly accessing the properties and presenting them as needed. This method provides control over which properties to display.

Example:

  const person = {
    name: “John”,
    age: 30,
    city: “New York”
  };

  // Displaying specific properties
  document.getElementById(“demo”).innerHTML =
    person.name + “, ” + person.age + “, ” + person.city;

Displaying the Object in a Loop:

Displaying the object in a loop allows for a more dynamic approach, especially when dealing with a larger number of properties. This method works well when the properties are not known in advance.

Example:

  const person = {
  name: “John”,
  age: 30,
  city: “New York”
};

let displayText = “”;

// Looping through object properties
for (let property in person) {
  displayText += person[property] + ” “;
}

document.getElementById(“demo”).innerHTML = displayText;

Using Object.values():

The Object.values() method returns an array of a given object’s property values, providing a concise way to display all values in the object.

Example:

const person = {
  name: “John”,
  age: 30,
  city: “New York”
};

// Using Object.values() to get property values
const valuesArray = Object.values(person);

// Displaying values
document.getElementById(“demo”).innerHTML = valuesArray.join(“, “);

Using JSON.stringify():

`JSON.stringify()` converts an object into a JSON string, offering a convenient way to display the entire object in a structured format.

Example:

const person = {
  name: “John”,
  age: 30,
  city: “New York”
}
let myString = JSON.stringify(person);

Course Video