JavaScript objects are data structures that store data as key-value pairs. They are similar to dictionaries in other programming languages. Objects can be created using the Object
constructor or by using the shorthand {}
notation.
For example, the following code creates an object called person
with three properties: name
, age
, and gender
.
let person = {
name: "John Doe",
age: 30,
gender: "male"
};
To access an object's properties, we can use the dot notation or the bracket notation. For example, we can access the name
property of the person
object like this:
console.log(person.name); // Output: "John Doe"
Or like this:
console.log(person["name"]); // Output: "John Doe"
In addition to storing data, objects can also have methods, which are functions that are associated with an object. For example, the following code defines a sayHello
method for the person
object:
let person = {
name: "John Doe",
age: 30,
gender: "male",
sayHello: function() {
console.log("Hello, my name is " + this.name);
}
};
person.sayHello(); // Output: "Hello, my name is John Doe"
In summary, JavaScript objects are an important data type that allows us to store and organize data in a structured manner. They provide a convenient way to group related data and functionality.