JavaScript Arrays 101
What Are Arrays?
Arrays store multiple values inside a single variable.
Instead of:
const fruit1 = "Apple"; const fruit2 = "Banana"; const fruit3 = "Mango";
we use an array:
const fruits = ["Apple", "Banana", "Mango"];
Cleaner and easier to manage.
Why Arrays Are Needed
Arrays help organize collections of data.
Examples:
List of fruits
User names
Tasks
Product prices
Student marks
Arrays Store Ordered Values
Arrays keep values in order
Each value has a position called an index.
Array Visualization
Creating an Array
Use square brackets:
const fruits = ["Apple", "Banana", "Mango"];
Arrays Can Store Different Types
const mixed = [ "Ali", 22, true ];
Accessing Elements Using Index
Arrays use indexes starting from:
0
Example
const fruits = ["Apple", "Banana", "Mango"]; console.log(fruits[0]); console.log(fruits[1]);
Output
Apple Banana
Why Does Index Start at 0?
JavaScript arrays are zero-indexed.
Meaning:
Accessing Last Element
const fruits = ["Apple", "Banana", "Mango"]; console.log(fruits[2]);
Output
Mango
Updating Elements
Arrays are mutable.
You can change values.
Example
const fruits = ["Apple", "Banana", "Mango"]; fruits[1] = "Orange"; console.log(fruits);
Output
["Apple", "Orange", "Mango"]
Array Length Property
Use:
length
to get total number of elements.
Example
const fruits = ["Apple", "Banana", "Mango"]; console.log(fruits.length);
Output
3
Memory-Style Array Diagram
Basic Looping Over Arrays
Use loops to access all elements.
Using for Loop
const fruits = ["Apple", "Banana", "Mango"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
Output
Apple Banana Mango
How Loop Works
i = 0 → Apple i = 1 → Banana i = 2 → Mango
Practical Example
const marks = [80, 90, 75]; console.log(marks[0]); marks[2] = 95; console.log(marks);
Output
80 [80, 90, 95]
Comparing Individual Variables vs Arrays
Individual Variables
const movie1 = "Inception"; const movie2 = "Interstellar"; const movie3 = "Avatar";
Array
const movies = [ "Inception", "Interstellar", "Avatar" ];
Arrays are easier to manage.
Assignment
1. Create Array
const movies = [ "Inception", "Interstellar", "Avatar", "Titanic", "Joker" ];
2. Print First and Last Element
console.log(movies[0]); console.log(movies[4]);
3. Change One Value
movies[2] = "Batman"; console.log(movies);
4. Loop Through Array
for (let i = 0; i < movies.length; i++) {
console.log(movies[i]);
}
Common Beginner Mistakes
Starting Index at 1
Incorrect:
fruits[1]
for first element.
Correct:
fruits[0]
Accessing Non-Existing Index
console.log(fruits[10]);
Output
undefined
Key Takeaways
Final Notes
Arrays are one of the most important JavaScript concepts because they are used everywhere:
APIs
Databases
Frontend apps
Backend systems
Real-world data handling
Understanding arrays well makes learning:
Array methods
Objects
APIs
React
Node.js
much easier.
0 Comments
Sign in to join the conversation
No comments yet. Be the first to comment!