JavaScript Arrays — Complete Guide
Phase 4 — Arrays
Module 9 — Arrays
Arrays are one of the most commonly used data structures in JavaScript. They allow you to store multiple values in a single variable and efficiently manage collections of data.
Almost every JavaScript application uses arrays:
- Shopping carts
- User lists
- API responses
- Product catalogs
- Tables
- Menus
- Chat messages
- Images
- React state
- Database records
Understanding arrays is essential before learning advanced array methods like map(), filter(), and reduce().
What is an Array?
An array is an ordered collection of values stored under a single variable.
Unlike objects, arrays use numeric indexes starting from 0.
1Index 2 30 1 2 3 4 5↓ 6 7["HTML","CSS","JavaScript","React"]
Example
1const skills = [ 2 "HTML", 3 "CSS", 4 "JavaScript", 5 "React" 6]; 7 8console.log(skills);
Output
1["HTML", "CSS", "JavaScript", "React"]
Why Use Arrays?
Without arrays:
1const student1 = "Ankit"; 2const student2 = "Rahul"; 3const student3 = "Priya";
With arrays:
1const students = [ 2 "Ankit", 3 "Rahul", 4 "Priya" 5];
Arrays make code:
- Cleaner
- Faster
- Easier to manage
- Easier to loop through
Creating Arrays
Array Literal (Recommended)
1const numbers = [10, 20, 30];
Using Array Constructor
1const colors = new Array( 2 "Red", 3 "Green", 4 "Blue" 5);
Empty Array
1const users = [];
Mixed Data Types
Arrays can store different data types.
1const data = [ 2 "Ankit", 3 23, 4 true, 5 null, 6 { 7 city: "Delhi" 8 } 9];
Accessing Array Elements
Use indexes.
1const fruits = [ 2 "Apple", 3 "Banana", 4 "Orange" 5]; 6 7console.log(fruits[0]); 8console.log(fruits[2]);
Output
1Apple 2Orange
Updating Array Elements
1const colors = [ 2 "Red", 3 "Blue", 4 "Green" 5]; 6 7colors[1] = "Black"; 8 9console.log(colors);
Output
1["Red","Black","Green"]
Array Length
1const colors = [ 2 "Red", 3 "Blue", 4 "Green" 5]; 6 7console.log(colors.length);
Output
13
Nested Arrays
Arrays can contain other arrays.
1const matrix = [ 2 3 [1, 2, 3], 4 5 [4, 5, 6], 6 7 [7, 8, 9] 8 9];
Visualization
1matrix 2 3[ 4 [1,2,3], 5 [4,5,6], 6 [7,8,9] 7]
Access Values
1console.log(matrix[0][1]); 2console.log(matrix[2][2]);
Output
12 29
Nested Objects Inside Arrays
1const users = [ 2 3 { 4 name: "Ankit", 5 age: 23 6 }, 7 8 { 9 name: "Rahul", 10 age: 20 11 } 12 13]; 14 15console.log(users[1].name);
Output
1Rahul
Array Destructuring
Extract values directly into variables.
1const colors = [ 2 "Red", 3 "Blue", 4 "Green" 5]; 6 7const [ 8 first, 9 second, 10 third 11] = colors; 12 13console.log(first); 14console.log(second);
Output
1Red 2Blue
Skip Values
1const numbers = [ 2 10, 3 20, 4 30, 5 40 6]; 7 8const [ 9 first, 10 , 11 third 12] = numbers; 13 14console.log(first); 15console.log(third);
Output
110 230
Default Values
1const colors = [ 2 "Red" 3]; 4 5const [ 6 first, 7 second = "Blue" 8] = colors; 9 10console.log(second);
Output
1Blue
Spread Operator (...)
Spread expands an array into individual elements.
1const numbers = [ 2 1, 3 2, 4 3 5]; 6 7const newNumbers = [ 8 ...numbers, 9 4, 10 5 11]; 12 13console.log(newNumbers);
Output
1[1,2,3,4,5]
Merge Arrays
1const frontend = [ 2 "HTML", 3 "CSS" 4]; 5 6const backend = [ 7 "Node.js", 8 "MongoDB" 9]; 10 11const fullStack = [ 12 ...frontend, 13 ...backend 14]; 15 16console.log(fullStack);
Output
1["HTML","CSS","Node.js","MongoDB"]
Rest Operator (...)
Collects remaining elements.
1const numbers = [ 2 10, 3 20, 4 30, 5 40, 6 50 7]; 8 9const [ 10 first, 11 second, 12 ...remaining 13] = numbers; 14 15console.log(remaining);
Output
1[30,40,50]
Rest Parameters in Functions
1function sum(...numbers) { 2 3 let total = 0; 4 5 for (const number of numbers) { 6 total += number; 7 } 8 9 return total; 10 11} 12 13console.log(sum(10,20,30,40));
Output
1100
Copy Arrays
Arrays are reference types.
Incorrect Copy
1const a = [ 2 1, 3 2, 4 3 5]; 6 7const b = a; 8 9b[0] = 100; 10 11console.log(a);
Output
1[100,2,3]
Both variables reference the same array.
Shallow Copy
Using Spread
1const original = [ 2 1, 3 2, 4 3 5]; 6 7const copy = [ 8 ...original 9]; 10 11copy[0] = 100; 12 13console.log(original); 14console.log(copy);
Output
1[1,2,3] 2[100,2,3]
Using slice()
1const copy = original.slice();
Using Array.from()
1const copy = Array.from(original);
Using concat()
1const copy = [].concat(original);
Shallow Copy Limitation
1const users = [ 2 3 { 4 name: "Ankit" 5 } 6 7]; 8 9const copy = [...users]; 10 11copy[0].name = "Rahul"; 12 13console.log(users[0].name);
Output
1Rahul
The object inside the array is still shared.
Deep Copy
Deep copy duplicates nested objects and arrays.
Using structuredClone()
1const users = [ 2 3 { 4 name: "Ankit" 5 } 6 7]; 8 9const copy = structuredClone(users); 10 11copy[0].name = "Rahul"; 12 13console.log(users[0].name);
Output
1Ankit
Using JSON
1const copy = JSON.parse( 2 JSON.stringify(users) 3);
Note: This approach does not preserve functions, Date, Map, Set, undefined, or special object types.
Shallow vs Deep Copy
| Feature | Shallow Copy | Deep Copy |
|---|---|---|
| Top-level copied | ✅ | ✅ |
| Nested objects copied | ❌ | ✅ |
| Nested arrays copied | ❌ | ✅ |
| Independent copy | Partially | Fully |
| Recommended API | Spread (...) | structuredClone() |
Array Comparison
1const a = [1,2,3]; 2const b = [1,2,3]; 3 4console.log(a === b);
Output
1false
Arrays are compared by reference, not by value.
Practical Example
1const employees = [ 2 3 { 4 id: 1, 5 name: "Ankit" 6 }, 7 8 { 9 id: 2, 10 name: "Rahul" 11 } 12 13]; 14 15const clonedEmployees = structuredClone(employees); 16 17clonedEmployees.push({ 18 id: 3, 19 name: "Priya" 20}); 21 22console.log(employees.length); 23console.log(clonedEmployees.length);
Output
12 23
Best Practices
- Use array literals (
[]) instead ofnew Array(). - Prefer destructuring for cleaner code.
- Use the spread operator for merging arrays.
- Use rest parameters for flexible function arguments.
- Avoid modifying original arrays unnecessarily.
- Use
structuredClone()for deep copying complex data. - Understand the difference between shallow and deep copies.
- Keep arrays homogeneous when possible for better readability.
Mini Project — Student Management System
index.html
1<!DOCTYPE html> 2<html lang="en"> 3<head> 4 <meta charset="UTF-8"> 5 <title>Student Management</title> 6</head> 7<body> 8 9<h2>Students</h2> 10 11<div id="output"></div> 12 13<script src="script.js"></script> 14 15</body> 16</html>
script.js
1const students = [ 2 3 { 4 id: 1, 5 name: "Ankit", 6 course: "JavaScript" 7 }, 8 9 { 10 id: 2, 11 name: "Rahul", 12 course: "React" 13 } 14 15]; 16 17const copiedStudents = structuredClone(students); 18 19copiedStudents.push({ 20 id: 3, 21 name: "Priya", 22 course: "Node.js" 23}); 24 25const output = document.getElementById("output"); 26 27copiedStudents.forEach(student => { 28 29 output.innerHTML += ` 30 <p> 31 ${student.id} 32 - 33 ${student.name} 34 - 35 ${student.course} 36 </p> 37 `; 38 39});
Summary
In this module, you learned:
- What arrays are and how they store ordered collections of data.
- How to create arrays using literals and constructors.
- How to access, update, and inspect array elements.
- How nested arrays can represent multi-dimensional data structures.
- How array destructuring simplifies extracting values.
- How the spread operator merges and copies arrays.
- How the rest operator collects remaining values.
- The difference between assigning an array reference and creating a copy.
- Multiple techniques for creating shallow copies using spread,
slice(),Array.from(), andconcat(). - Why shallow copies don't duplicate nested objects.
- How to perform deep copies using
structuredClone()and whenJSON.parse(JSON.stringify())is appropriate. - Why arrays are compared by reference rather than value.
Next Module: Array Methods (Professional JavaScript) — you'll master essential methods such as
push(),pop(),shift(),unshift(),map(),filter(),reduce(),find(),findIndex(),some(),every(),sort(),reverse(),slice(),splice(),flat(),flatMap(),includes(),indexOf(),join(),concat(), and many more that are used daily in React, Next.js, Node.js, and enterprise JavaScript applications.