Track: JavaScript Basics
Lesson: JS-06 / JS-10
๐ฏ Lesson Goal
By the end of this lesson, you will understand what arrays are, how to create and access them, and how to use arrays to store and manipulate multiple values in JavaScript programs.
๐ Prerequisites
- JS-01: Variables and Data Types
- JS-02: Operators and Expressions
- JS-03: Conditional Statements
- JS-04: Loops
- JS-05: Functions
You should be comfortable with:
- Variables and loops
- Basic functions
๐ What is an Array?
An array is a data structure used to store multiple values in a single variable.
Instead of creating many variables:
let subject1 = "HTML";
let subject2 = "CSS";
let subject3 = "JavaScript";
We use an array:
let subjects = ["HTML", "CSS", "JavaScript"];
๐น Creating Arrays
Using Array Literals (recommended)
let colors = ["Red", "Green", "Blue"];
Using new Array()
let numbers = new Array(10, 20, 30);
๐น Accessing Array Elements
Array indexing starts from 0.
let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits[0]); // Apple
console.log(fruits[2]); // Mango
๐น Modifying Array Elements
fruits[1] = "Orange";
console.log(fruits);
๐น Array Length
The length property tells how many elements are in an array.
console.log(fruits.length);
๐น Looping Through Arrays
Arrays are commonly used with loops.
Using for loop
let languages = ["HTML", "CSS", "JavaScript", "React"];
for (let i = 0; i < languages.length; i++) {
console.log(languages[i]);
}
๐น Common Array Methods
push() โ Add element at end
languages.push("Node.js");
pop() โ Remove last element
languages.pop();
unshift() โ Add element at start
languages.unshift("Git");
shift() โ Remove first element
languages.shift();
๐น indexOf() Method
Returns index of an element.
let index = languages.indexOf("JavaScript");
console.log(index);
๐น includes() Method
Checks if an element exists.
console.log(languages.includes("React")); // true
๐น Arrays with Functions
function printArray(arr) {
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
}
printArray(languages);
โ ๏ธ Common Mistakes
- Accessing invalid index
- Forgetting array index starts at 0
- Using
=instead of array methods - Modifying array length accidentally
๐ง Practice Tasks
- Create an array of 5 numbers
- Print all elements using a loop
- Add a new element using
push() - Remove the first element
- Check if a value exists using
includes()
๐งช Mini Coding Challenge
let marks = [45, 67, 80, 90, 55];
Tasks:
- Calculate total marks using a loop
- Find highest mark
- Count how many students scored above 60
๐ Summary
- Arrays store multiple values
- Index starts from 0
lengthgives size- Methods like
push,pop,shiftare useful - Arrays work naturally with loops and functions
โก๏ธ Next Lesson
JavaScript Objects (JS-07)
๐ Quiz & Badge
Quiz and badges will be enabled soon.