Objects in Javascript

Página 7

Objects are fundamental in Javascript, as they allow the creation of complex structures to store and manipulate data. In Javascript, everything is an object, from a simple string to a function.

An object is a collection of properties, which are key-value pairs. The key is a string that identifies the property, and the value can be any data type, including another object. For example:


const person = {
  name: "John",
  age: 30,
  address: {
    street: "Street A",
    number: 123
  }
};

In this example, we have an object called "person" with three properties: "name", "age" and "address". The "address" property is, in turn, another object with two properties: "street" and "number".

To access a property of an object, just use the dot notation or square brackets. For example:


console.log(person.name); // "John"
console.log(person["age"]); // 30
console.log(person.address.street); // "Street A"

It is also possible to add or modify properties of an object dynamically:


person.email = "[email protected]";
person.age = 31;

In addition, it is possible to create objects from constructor functions or classes. For example:


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

const person1 = new Person("Mary", 25);
const person2 = new Person("Peter", 35);

In this example, the "Person" constructor function defines an object with two properties: "name" and "age". By creating a new object from this function with the "new" operator, we can pass the desired values ​​to the properties.

In summary, objects are a fundamental part of JavaScript and allow the creation of complex structures to store and manipulate data. With dot or square bracket notation, you can access and modify the properties of an object, and you can also create objects from constructor functions or classes.

Now answer the exercise about the content:

_What is the definition of an object in Javascript?

You are right! Congratulations, now go to the next page

You missed! Try again.

Next page of the Free Ebook:

8DOM Manipulation with Javascript

Earn your Certificate for this Course for Free! by downloading the Cursa app and reading the ebook there. Available on Google Play or App Store!

Get it on Google Play Get it on App Store

+ 6.5 million
students

Free and Valid
Certificate with QR Code

48 thousand free
exercises

4.8/5 rating in
app stores

Free courses in
video, audio and text