JavaScript Objects
JS
JavaScript objects are used to store multiple values in a single variable. They hold data as key-value pairs.
Creating a simple object
In this object:
- name, age, and city are keys (or properties).
- “John”, 30, and “New York” are values.
Accessing Object Properties
You can access values in two ways:
a. Using dot . notation:
b. Using bracket [] notation:
Adding Properties to Objects
You can easily add new properties:
Modifying Object Properties
You can update existing properties easily:
Deleting Object Properties
You can delete properties using the delete keyword:
Object Methods
Objects can also store functions, known as methods:
Looping Through Objects
Use a for...in loop to go through all properties of an object:
Nested Objects
Objects can contain other objects:
Benefits of JavaScript Objects:
- Store multiple related data easily.
- Clear and readable code.
- Easy to add, remove, and update properties.
- Helps manage complex data.
Objects in JavaScript are containers for data. They store data as key-value pairs, making it easy to group and organize your code clearly and efficiently.
Project
Product Catalog (Shopping App)
Create an interactive product catalog that allows users to browse and view detailed information about products.
Features:
- Display product information (name, price, description, image URL).
- Allow users to click and see details.
- Add search functionality to filter products by name or category.
Project Code:
Code details:
- Products are defined using JavaScript objects.
- Dynamically generates the product list in the browser.
- Each product shows a brief overview; clicking shows more detailed information.
- Easily extendable by adding more products to the products array.