Understanding Objects in JavaScript
I’ve been diving deep into JavaScript lately, and the best way to make sure I actually understand something is to write it down and explain it.
What Exactly is an Object?
The easiest way to think about an object is like a dictionary or the contacts app on your phone.
In a dictionary, you look up a word (the key), and it gives you the definition (the value). A JavaScript object is just a collection of these key value pairs. The key is the label, and the value is the data.
Creating an Object
const person = {
name: "Raj",
age: 28,
city: "Jaipur"
};
How to Access the Data
Once your data is inside an object, you need to know how to get it out. I learned there are two ways to do this.
1. Dot Notation
console.log(person.name);
console.log(person.city);
2. Bracket Notation
console.log(person["name"]);
const whatIWantToKnow = "age";
console.log(person.whatIWantToKnow); // Output: undefined
console.log(person[whatIWantToKnow]); // Output: 28
Changing the Data
Modifying an object is pretty straightforward.
- **Updating a Property -**Just grab the property and give it a new value.
person.age = 29;
- Adding a Property - You don't need to change the original object. Just pretend the new key already exists and assign something to it.
person.job = "Developer";
- Deleting a Property - If you need to completely remove something, use the
deletekeyword.
delete person.city;
Looping Through an Object
what if you want to print out everything inside the object? Because objects don't have numbered indexes like arrays do, a normal for loop doesn't work.
const person = {
name: "Raj",
age: 28,
city: "Jaipur"
};
for (let key in person) {
// Notice I have to use bracket notation here because 'key' is a variable!
console.log(`\({key} : \){person[key]}`);
}
/* Console Output:
name: Raj
age: 28
city: Jaipur
*/
That’s it for the basics, switching my mindset from putting everything in an array to using an object to label my data has made my code so much easier to read.