SimpleTuts.com

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:


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

  1. User enters student details.
  2. When the button is clicked, JavaScript creates a student object.
  3. The object stores all related information.
  4. The details are displayed on the webpage.

7. Practice Exercise

Create a Car Information System.

Inputs:

Output:

Display all car details using a JavaScript object.


8. What Students Learned


Next Chapter

Chapter 8: DOM Manipulation in JavaScript with Real-Life Example: Dynamic To-Do List Application