30 Days of JAVASCRIPT #7/30

·

2 min read

2.Object Data Structure in JavaScript

In JavaScript, an object is a collection of key-value pairs, also known as a map, dictionary, or hash-table. Objects are a fundamental data structure in JavaScript and are used extensively in the language

Creating Objects

To create an object in JavaScript, we can use object literal syntax, which involves enclosing the key-value pairs in curly braces{}. For example, we can create an object representing a person with the following code:

javascript
const person = {
  name: "John",
  age: 30,
  occupation: "Developer"
};

We can also create an object using a constructor function, which is a function that returns a new object. For example, we can create aPersonconstructor function that takes in a name, age, and occupation and returns a new object with those properties:

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

const person = new Person("John", 30, "Developer");

Accessing Object Properties

We can access the properties of an object using dot notation or bracket notation. For example, to access thenameproperty of thepersonobject we created earlier, we can use the following code:

javascript
console.log(person.name); // Output: "John"

Alternatively, we can use bracket notation to access thenameproperty:

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

Modifying Object Properties

We can modify the properties of an object by assigning a new value to them using dot notation or bracket notation. For example, to change theoccupationproperty of thepersonobject to "Designer", we can use the following code:

javascript
person.occupation = "Designer";
console.log(person.occupation); // Output: "Designer"

Example Code

Here's an example code that demonstrates the creation, accessing, and modification of object properties:

javascript// Create an object representing a person
const person = {
  name: "John",
  age: 30,
  occupation: "Developer"
};

// Access the name property using dot notation
console.log(person.name); // Output: "John"

// Access the age property using bracket notation
console.log(person["age"]); // Output: 30

// Modify the occupation property
person.occupation = "Designer";
console.log(person.occupation); // Output: "Designer"

In conclusion, objects are a powerful and versatile data structure in JavaScript that allow us to represent complex data and functionality in a simple and organized way.