Understanding Objects in JavaScript
Objects are another way to organize / store data , but in a key-value pair format. This makes whatever we store more descriptive , depicting them as properties.
For example,
if we are storing a user, an object tells us exactly what each value represents:
const user = {
name: "John",
age: 21
};
In this example, name and age are the keys (or properties), and "John" and 21 are their values. Instead of just having a list of random data, we now have a clear description of the user object.
Accessing the properties -
these properties can be easily accessed through keys
const user = {
name: "John",
age: 21
};
// accessing a property
console,log(user.name) // "John"
console.log(user[name])
Updating Properties
Updating is as simple as assigning a new value to the key, just like a variable.
// Update existing property
user.age = 22;
// Add new property
user.city = "New York";
console.log(user); // { name: "John", age: 22, city: "New York" }
Looping through object keys -
Since objects don't have a .length property like arrays, we have two main ways to loop through them:
Object.keys() (The Array way)
first we get an array of the keys on which we want to iterate using Object.keys() and then we loop through this array.
const keys = Object.keys(user); // ["name", "age", "city"]
keys.forEach(key => {
console.log(`\({key}: \){user[key]}`);
});
for...in Loop
This is a built-in loop specifically designed for objects. It iterates over every key in the object.
for (let key in user) {
console.log(`\({key} has a value of \){user[key]}`);
}