Javascript Objects
Dec 09 2023
In Javascript, objects are fundamental data structures that allow us to organize and manipulate data in a structured way.
What is an Object?
In JavaScript, an object is a collection of key-value pairs, where each key is a string (or symbol) and each value can be any valid JavaScript data type, including other objects. Objects are used to represent real-world entities and their properties.
How To Create An Object
We use curly braces {} to create an object. Inside the curly braces, we define properties using key-value pairs. The key is like the label, and the value is the information it holds.
let person = {
name: 'John Doe',
age: 25,
isStudent: true,
};
In this example, person is an object with three properties: name
, age
, and isStudent
. The colon : separates the property name from its value, and each key-value pair is separated by a comma.
How To Access Object Properties
You can access the properties of an object using dot notation or square brackets:
console.log(person.name); // Output: John Doe
console.log(person['age']); // Output: 25
Dot notation is more common, but square bracket notation is useful when the property name contains special characters or spaces.
How To Add And Modify Properties
We can add new properties or modify existing ones dynamically:
person.gender = 'Male';
person.age = 26;
console.log(person);
/* Output:
{
name: 'John Doe',
age: 26, // Modified
isStudent: true,
gender: 'Male' // Added
}
*/
Nested Objects
Objects can contain other objects, creating a nested structure:
let person = {
name: 'John Doe',
age: 25,
isStudent: true,
address: {
street: '123 Main St',
city: 'Cityville',
}
};
console.log(person.address.city); // Output: Cityville
Object Methods
In addition to properties, objects can also contain methods, which are functions associated with the 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
Object Iteration
We loop through the properties of an object using for...in
loop:
let person = {
name: 'John Doe',
age: 25,
isStudent: true,
};
for (let key in person) {
console.log(`${key}: ${person[key]}`);
}
/* Output:
name: John Doe
age: 25
isStudent: true
*/
Conclusion
Objects play a crucial role in JavaScript programming. They enables us to structure and manipulate data in a flexible and organized way. Make sure you practise
Thank you for reading.