Objects in JS
Grouping Related Data
While an Array is great for a simple list, what if you want to store detailed information about a single entity, like a User? You use an Object.
An object is a collection of properties, and a property is an association between a name (or key) and a value.
Creating an Object
You create objects using curly braces {}.
const user = {
firstName: "Himanshu",
lastName: "Dubey",
age: 25,
isDeveloper: true
};
Accessing Object Properties
You can access data inside an object in two ways:
1. Dot Notation (Most Common)
console.log(user.firstName); // "Himanshu"
2. Bracket Notation
console.log(user["age"]); // 25
Bracket notation is necessary if your key has a space in it or if you are accessing a key using a variable.
Modifying and Adding Properties
Objects are mutable (changeable).
// Modifying an existing property
user.age = 26;
// Adding a brand new property
user.country = "India";
Methods in Objects
An object's value can also be a function! When a function is attached to an object, it is called a method.
const developer = {
name: "Himanshu",
code: function() {
console.log("Writing React code...");
}
};
developer.code(); // Outputs: Writing React code...
💡 Himanshu's Tip:
When you have a variable name that exactly matches the object key you want to create, you can use ES6 shorthand! Instead of { name: name }, you can just write { name }. It keeps your objects super clean!
Interview Questions
- When must you use bracket notation instead of dot notation to access an object property?
- What is a method in the context of a JavaScript object?
- How can you delete a property from an object?