Arrays in JavaScript
Understanding Arrays in JavaScript
1. What is an Array?
An array is a data structure used to store multiple values in a single variable.
Example:
Instead of creating multiple variables:
let student1 = "Rahul";
let student2 = "Anu";
let student3 = "Aman";
We can store them in an array:
let students = ["Rahul", "Anu", "Aman"];
2. Accessing Array Elements
Each element in an array has an index number starting from 0.
let students = ["Rahul", "Anu", "Aman"];
console.log(students[0]);
console.log(students[1]);
console.log(students[2]);
Output:
Rahul
Anu
Aman
3. Adding Values to an Array
We use the push() method.
let fruits = ["Apple", "Banana"];
fruits.push("Mango");
console.log(fruits);
Output:
["Apple", "Banana", "Mango"]
4. Looping Through Arrays
Arrays are commonly used with loops.
let numbers = [10,20,30,40];
for(let i = 0; i < numbers.length; i++){
console.log(numbers[i]);
}
5. Real-Life Example: Student List Manager
This application allows users to:
- Add student names
- Display the student list
index.html
<!DOCTYPE html>
<html>
<head>
<title>Student List Manager</title>
</head>
<body>
<h2>Student List Manager</h2>
<input type="text" id="studentName" placeholder="Enter student name">
<button onclick="addStudent()">Add Student</button>
<button onclick="showStudents()">Show Students</button>
<ul id="studentList"></ul>
<script src="app.js"></script>
</body>
</html>
Run Code
app.js
let students = [];
function addStudent(){
let name = document.getElementById("studentName").value;
students.push(name);
document.getElementById("studentName").value = "";
}
function showStudents(){
let list = document.getElementById("studentList");
list.innerHTML = "";
for(let i = 0; i < students.length; i++){
list.innerHTML += "<li>" + students[i] + "</li>";
}
}
Run Code
6. How This Example Works
- User enters a student name.
- When Add Student is clicked, the name is stored in the array.
- When Show Students is clicked, a loop displays all students.
7. Practice Exercise
Create a Shopping List Manager.
Features:
- Add items
- Display item list
8. What Students Learned
- What arrays are
- Array indexing
push()method- Looping through arrays
- Building a dynamic list application
Next Chapter
Chapter 7: Objects in JavaScript with Real-Life Example: Student Information System