Arrays are one of the most fundamental and useful data structures in JavaScript. They allow you to store multiple values in a single variable, maintain order, and efficiently manipulate collections of data. Whether you're building a shopping cart, managing user lists, or processing data, arrays are essential. Let's master array fundamentals!
What Are Arrays?
An array is an ordered collection of values (called elements) stored in a single variable. Each element has a numeric position (index) starting from 0.
Think of an array like a list:
- Shopping list: ["milk", "bread", "eggs"]
- Todo list: ["study", "exercise", "sleep"]
- Scores: [85, 92, 78, 95]
- Mixed data: ["Alice", 25, true, null]
Why Use Arrays?
- Store multiple values: Keep related data together
- Maintain order: Elements stay in the order you add them
- Easy access: Get any element by its position
- Powerful methods: Built-in functions for manipulation
- Iterate easily: Loop through all elements efficiently
Creating Arrays
Array Literal (Most Common)
// Empty array
let emptyArray = [];
// Array with numbers
let numbers = [1, 2, 3, 4, 5];
// Array with strings
let fruits = ["apple", "banana", "orange"];
// Array with mixed types
let mixedArray = [1, "hello", true, null, undefined];
// Array with expressions
let calculated = [1 + 1, 5 * 2, Math.PI];
console.log(calculated); // [2, 10, 3.141592653589793]
console.log(numbers); // [1, 2, 3, 4, 5]
console.log(fruits); // ["apple", "banana", "orange"]Array Constructor (Less Common)
// Using new Array()
let arr1 = new Array(); // Empty array
console.log(arr1); // []
let arr2 = new Array(5); // Array with 5 empty slots
console.log(arr2); // [empty × 5]
console.log(arr2.length); // 5
let arr3 = new Array(1, 2, 3); // Array with elements
console.log(arr3); // [1, 2, 3]
// Array.of() - creates array with elements
let arr4 = Array.of(5); // [5] (not 5 empty slots)
console.log(arr4); // [5]
let arr5 = Array.of(1, 2, 3);
console.log(arr5); // [1, 2, 3]Best Practice: Use array literal syntax [] for creating arrays. It's shorter, clearer, and the most common approach.
Creating Arrays from Other Data
// Array.from() - create array from array-like or iterable
let str = "hello";
let chars = Array.from(str);
console.log(chars); // ["h", "e", "l", "l", "o"]
// Split string into array
let sentence = "Hello World";
let words = sentence.split(" ");
console.log(words); // ["Hello", "World"]
// Array from range (using Array.from with map)
let range = Array.from({ length: 5 }, (_, i) => i + 1);
console.log(range); // [1, 2, 3, 4, 5]
// Spread operator
let original = [1, 2, 3];
let copy = [...original];
console.log(copy); // [1, 2, 3]Accessing Array Elements
Arrays use zero-based indexing. The first element is at index 0, the second at index 1, and so on.
Using Index
let fruits = ["apple", "banana", "orange", "grape", "mango"];
// Access by index
console.log(fruits[0]); // "apple" (first element)
console.log(fruits[1]); // "banana"
console.log(fruits[2]); // "orange"
console.log(fruits[4]); // "mango" (last element)
// Index out of bounds returns undefined
console.log(fruits[10]); // undefined
console.log(fruits[-1]); // undefined (doesn't work like Python)
// Visual representation:
// Index: 0 1 2 3 4
// Value: ["apple", "banana", "orange", "grape", "mango"]Accessing First and Last Elements
let numbers = [10, 20, 30, 40, 50];
// First element
let first = numbers[0];
console.log(first); // 10
// Last element (using length)
let last = numbers[numbers.length - 1];
console.log(last); // 50
// Why length - 1?
// Length is 5, but last index is 4 (because of zero-indexing)
// Helper function for last element
function getLastElement(arr) {
return arr[arr.length - 1];
}
console.log(getLastElement(numbers)); // 50
console.log(getLastElement(["a", "b", "c"])); // "c"Negative Indexing (Using at() method)
let fruits = ["apple", "banana", "orange", "grape"];
// Modern way: at() method (ES2022)
console.log(fruits.at(0)); // "apple" (first)
console.log(fruits.at(-1)); // "grape" (last)
console.log(fruits.at(-2)); // "orange" (second to last)
// Compare to old way
console.log(fruits[fruits.length - 1]); // "grape"
console.log(fruits.at(-1)); // "grape" (cleaner!)
// at() works with positive indices too
console.log(fruits.at(1)); // "banana"
console.log(fruits.at(10)); // undefined (out of bounds)Modifying Array Elements
Changing Elements
let fruits = ["apple", "banana", "orange"];
// Modify existing element
fruits[1] = "mango";
console.log(fruits); // ["apple", "mango", "orange"]
// Change multiple elements
fruits[0] = "strawberry";
fruits[2] = "grape";
console.log(fruits); // ["strawberry", "mango", "grape"]
// Add element at specific index
fruits[3] = "kiwi";
console.log(fruits); // ["strawberry", "mango", "grape", "kiwi"]
// Creates gaps if you skip indices
let numbers = [1, 2, 3];
numbers[5] = 6;
console.log(numbers); // [1, 2, 3, empty × 2, 6]
console.log(numbers.length); // 6Warning: Assigning to indices beyond the array's length creates "empty slots" (sparse arrays). Usually, you want to use push() instead to add elements sequentially.
Array Length Property
The length property returns the number of elements in an array.
let fruits = ["apple", "banana", "orange"];
console.log(fruits.length); // 3
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(numbers.length); // 10
let emptyArray = [];
console.log(emptyArray.length); // 0
// Length is one more than the highest index
let items = [];
items[0] = "first";
items[4] = "fifth";
console.log(items.length); // 5 (not 2!)
console.log(items); // ["first", empty × 3, "fifth"]Using Length in Loops
let colors = ["red", "green", "blue", "yellow"];
// Common pattern: loop using length
for (let i = 0; i < colors.length; i++) {
console.log(`Index ${i}: ${colors[i]}`);
}
// Output:
// Index 0: red
// Index 1: green
// Index 2: blue
// Index 3: yellow
// Last element using length
let lastColor = colors[colors.length - 1];
console.log(lastColor); // "yellow"Modifying Length
let numbers = [1, 2, 3, 4, 5];
console.log(numbers.length); // 5
// Increase length (adds empty slots)
numbers.length = 8;
console.log(numbers); // [1, 2, 3, 4, 5, empty × 3]
// Decrease length (truncates array)
numbers.length = 3;
console.log(numbers); // [1, 2, 3]
// Empty an array by setting length to 0
numbers.length = 0;
console.log(numbers); // []Types of Array Elements
JavaScript arrays can hold any type of data, and even mix different types in the same array.
Single Type Arrays
// Numbers
let numbers = [1, 2, 3, 4, 5];
// Strings
let names = ["Alice", "Bob", "Charlie"];
// Booleans
let flags = [true, false, true, true];
// Objects
let users = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
{ name: "Charlie", age: 35 }
];
// Arrays (nested arrays)
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
// Functions
let operations = [
function(x) { return x + 1; },
function(x) { return x * 2; },
function(x) { return x ** 2; }
];
console.log(operations[0](5)); // 6
console.log(operations[1](5)); // 10Mixed Type Arrays
// Array with different types
let mixed = [
1, // number
"hello", // string
true, // boolean
null, // null
undefined, // undefined
{ name: "Alice" }, // object
[1, 2, 3], // array
function() {} // function
];
console.log(mixed.length); // 8
console.log(mixed[0]); // 1
console.log(mixed[1]); // "hello"
console.log(mixed[5].name); // "Alice"
console.log(mixed[6][0]); // 1
// Practical mixed array example
let userData = [
"Alice", // name
25, // age
"alice@test.com", // email
true, // isActive
["read", "write"] // permissions
];
console.log(`Name: ${userData[0]}`);
console.log(`Age: ${userData[1]}`);
console.log(`Permissions: ${userData[4].join(", ")}`);Nested Arrays (Multidimensional)
Arrays can contain other arrays, creating multidimensional data structures.
2D Arrays (Matrices)
// 2D array (array of arrays)
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
// Access outer array
console.log(matrix[0]); // [1, 2, 3]
console.log(matrix[1]); // [4, 5, 6]
// Access nested elements
console.log(matrix[0][0]); // 1
console.log(matrix[0][1]); // 2
console.log(matrix[1][2]); // 6
console.log(matrix[2][2]); // 9
// Visualize:
// matrix[row][column]
// Row 0: [1, 2, 3]
// Row 1: [4, 5, 6]
// Row 2: [7, 8, 9]
// Loop through 2D array
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix[i].length; j++) {
console.log(`[${i}][${j}] = ${matrix[i][j]}`);
}
}Practical Nested Arrays
// Student grades
let classGrades = [
["Alice", 85, 92, 78],
["Bob", 90, 88, 95],
["Charlie", 78, 85, 80]
];
// Access student data
console.log(classGrades[0][0]); // "Alice"
console.log(classGrades[0][1]); // 85 (first grade)
// Calculate average for first student
let aliceGrades = classGrades[0].slice(1); // [85, 92, 78]
let sum = aliceGrades.reduce((a, b) => a + b, 0);
let average = sum / aliceGrades.length;
console.log(`Alice's average: ${average}`); // 85
// Shopping cart with items
let cart = [
["Laptop", 1000, 1],
["Mouse", 25, 2],
["Keyboard", 75, 1]
];
// Calculate total
let total = 0;
for (let item of cart) {
let [name, price, quantity] = item;
total += price * quantity;
}
console.log(`Total: $${total}`); // Total: $1125Checking if Value is Array
let fruits = ["apple", "banana"];
let number = 42;
let obj = { name: "Alice" };
// Array.isArray() - the correct way
console.log(Array.isArray(fruits)); // true
console.log(Array.isArray(number)); // false
console.log(Array.isArray(obj)); // false
console.log(Array.isArray([])); // true
// typeof doesn't work well for arrays
console.log(typeof fruits); // "object" (not helpful!)
console.log(typeof obj); // "object"
// Why Array.isArray() is needed
function processData(data) {
if (Array.isArray(data)) {
console.log(`Processing ${data.length} items`);
} else {
console.log("Not an array");
}
}
processData([1, 2, 3]); // "Processing 3 items"
processData("hello"); // "Not an array"Practical Examples
Example 1: Shopping List Manager
// Simple shopping list
let shoppingList = ["milk", "bread", "eggs"];
console.log("Shopping List:");
console.log("Items:", shoppingList.length);
// Display all items
for (let i = 0; i < shoppingList.length; i++) {
console.log(`${i + 1}. ${shoppingList[i]}`);
}
// Output:
// 1. milk
// 2. bread
// 3. eggs
// Add item
shoppingList[shoppingList.length] = "butter";
console.log(shoppingList); // ["milk", "bread", "eggs", "butter"]
// Update item
shoppingList[0] = "almond milk";
console.log(shoppingList); // ["almond milk", "bread", "eggs", "butter"]
// Check if list is empty
if (shoppingList.length === 0) {
console.log("List is empty");
} else {
console.log(`You have ${shoppingList.length} items`);
}Example 2: Student Grade Tracker
// Student scores
let scores = [85, 92, 78, 95, 88];
console.log("Student Scores:", scores);
console.log("Number of tests:", scores.length);
// Calculate total
let total = 0;
for (let i = 0; i < scores.length; i++) {
total += scores[i];
}
// Calculate average
let average = total / scores.length;
console.log("Total:", total);
console.log("Average:", average.toFixed(2));
// Find highest score
let highest = scores[0];
for (let i = 1; i < scores.length; i++) {
if (scores[i] > highest) {
highest = scores[i];
}
}
console.log("Highest score:", highest);
// Find lowest score
let lowest = scores[0];
for (let i = 1; i < scores.length; i++) {
if (scores[i] < lowest) {
lowest = scores[i];
}
}
console.log("Lowest score:", lowest);Example 3: Contact List
// Array of contact objects
let contacts = [
{ name: "Alice", phone: "555-0001", email: "alice@test.com" },
{ name: "Bob", phone: "555-0002", email: "bob@test.com" },
{ name: "Charlie", phone: "555-0003", email: "charlie@test.com" }
];
console.log(`Total contacts: ${contacts.length}`);
// Display all contacts
for (let i = 0; i < contacts.length; i++) {
let contact = contacts[i];
console.log(`${i + 1}. ${contact.name} - ${contact.phone}`);
}
// Find contact by name
function findContact(name) {
for (let i = 0; i < contacts.length; i++) {
if (contacts[i].name === name) {
return contacts[i];
}
}
return null;
}
let found = findContact("Bob");
if (found) {
console.log("Found:", found);
} else {
console.log("Contact not found");
}
// Add new contact
contacts[contacts.length] = {
name: "Diana",
phone: "555-0004",
email: "diana@test.com"
};
console.log(`Total contacts: ${contacts.length}`);Array Basics Practice
Experiment with array creation and manipulation
console.log() to see your output in the console above.Key Takeaways
- Arrays are ordered collections of values stored in one variable
- Create arrays using array literal syntax:
[] - Arrays use zero-based indexing (first element is at index 0)
- Access elements using bracket notation:
array[index] lengthproperty returns number of elements- Last element is at
array[array.length - 1]orarray.at(-1) - Arrays can hold any type of data, including mixed types
- Modify elements by assigning to an index
- Arrays can be nested (multidimensional arrays)
- Use
Array.isArray()to check if value is an array
What's Next?
You now understand array fundamentals—how to create, access, and manipulate basic arrays! Arrays are essential to JavaScript programming and you'll use them constantly.
In the next lesson, we'll explore Array Methods: Adding and Removing Elements—learning powerful methods like push, pop, shift, unshift, splice, and slice. These methods make array manipulation much easier and more efficient!
💪 Practice Challenge:
Before moving on, try creating:
- An array of your favorite movies and loop through to display them
- A function that finds the maximum value in a number array
- A 2D array representing a tic-tac-toe board and access specific positions
- An array of user objects with name and age, then find users over 21
- A function that returns the first and last elements of any array