Objects in JavaScript
Understanding Objects in JavaScript
1. What is an Object?
An object is used to store multiple related values using key–value pairs.
Example:
let student = {
name: "Rahul",
age: 20,
course: "Computer Science"
};
Here:
name,age, andcourseare properties- The values represent information about the student
2. Accessing Object Properties
We can access object values in two ways.
Dot Notation
console.log(student.name);
Bracket Notation
console.log(student["age"]);
3. Updating Object Values
student.age = 21;
4. Adding New Properties
student.grade = "A";
5. Real-Life Example: Student Information System
This application stores and displays student details.
index.html
<!DOCTYPE html>
<html>
<head>
<title>Student Information System</title>
</head>
<body>
<h2>Student Information System</h2>
<input type="text" id="name" placeholder="Enter name"><br><br>
<input type="number" id="age" placeholder="Enter age"><br><br>
<input type="text" id="course" placeholder="Enter course"><br><br>
<button onclick="showStudent()">Show Student Info</button>
<h3 id="result"></h3>
<script src="app.js"></script>
</body>
</html>
Run Code
app.js
function showStudent(){
let name = document.getElementById("name").value;
let age = document.getElementById("age").value;
let course = document.getElementById("course").value;
let student = {
name: name,
age: age,
course: course
};
let result = document.getElementById("result");
result.innerText = "Name: " + student.name +
" | Age: " + student.age +
" | Course: " + student.course;
}
Run Code
6. How This Example Works
- User enters student details.
- When the button is clicked, JavaScript creates a student object.
- The object stores all related information.
- The details are displayed on the webpage.
7. Practice Exercise
Create a Car Information System.
Inputs:
- Car name
- Model
- Price
Output:
Display all car details using a JavaScript object.
8. What Students Learned
- What objects are
- Key–value pairs
- Accessing object properties
- Updating and adding properties
- Creating objects dynamically
Next Chapter
Chapter 8: DOM Manipulation in JavaScript with Real-Life Example: Dynamic To-Do List Application