In JavaScript, an object is a complex data type that allows you to store and organize data. Objects are collections of key-value pairs, where each key is a string (or a Symbol) and each value can be of any data type, including other objects. Objects in JavaScript are versatile and widely used in the language. Here's a basic overview of how objects work:
Creating an Object:
You can create an object using the curly braces {}
notation.
let person = {
name: "John Doe",
age: 25,
job: "Web Developer"
};
In this example, person
is an object with three properties: name
, age
, and job
.
Accessing Properties:
You can access the properties of an object using dot notation or square bracket notation.
console.log(person.name); // Output: John Doe
console.log(person['age']); // Output: 25
Adding and Modifying Properties:
You can add new properties or modify existing ones easily.
person.location = "Cityville";
person.age = 26;
console.log(person);
// Output: { name: 'John Doe', age: 26, job: 'Web Developer', location: 'Cityville' }
Nested Objects:
Objects can contain other objects as properties.
let car = {
make: "Toyota",
model: "Camry",
year: 2022,
owner: {
name: "Alice",
age: 30
}
};
console.log(car.owner.name); // Output: Alice
Object Methods:
You can also include functions (methods) as properties of an object.
let calculator = {
add: function(a, b) {
return a + b;
},
subtract: function(a, b) {
return a - b;
}
};
console.log(calculator.add(5, 3)); // Output: 8
Iterating Over Object Properties:
You can use for...in
loop to iterate over the properties of an object.
for (let key in person) {
console.log(key + ": " + person[key]);
}
This will output each key-value pair in the person
object.
Objects in JavaScript provide a flexible and powerful way to structure and manipulate data, making them a fundamental part of the language.