π¦ What are Arrays? Arrays are like containers that can hold many things at once. Imagine you have a box where you can keep your toys, books, or snacks. An array is just like that box - it can store many values in one place! ππ§Έπͺ
π Introduction In JavaScript, arrays are one of the most useful tools you can learn. They help us store multiple items together and work with them easily. Think of an array like a shopping list - you can add items, remove items, check what's in the list, and much more! Let's learn how to use them step by step! π
π§ How to Create Arrays
There are different ways to create arrays in JavaScript. Let's see the most common ways:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Method 1: Using square brackets (most common)
let fruits = ["apple", "banana", "orange"];
console.log(fruits); // ["apple", "banana", "orange"]
// Method 2: Using the Array constructor
let numbers = new Array(1, 2, 3, 4, 5);
console.log(numbers); // [1, 2, 3, 4, 5]
// Method 3: Creating an empty array
let emptyArray = [];
console.log(emptyArray); // []
// Arrays can hold different types of data
let mixedArray = ["hello", 42, true, "world"];
console.log(mixedArray); // ["hello", 42, true, "world"]
π Accessing Array Items
Each item in an array has a position number called an 'index'. The first item is at position 0, the second at position 1, and so on. Think of it like house numbers on a street! π π π
1
2
3
4
5
6
7
8
9
10
11
12
13
let colors = ["red", "green", "blue", "yellow"];
// Getting items by index (remember: counting starts from 0!)
console.log(colors[0]); // "red" (first item)
console.log(colors[1]); // "green" (second item)
console.log(colors[2]); // "blue" (third item)
console.log(colors[3]); // "yellow" (fourth item)
// Getting the length of an array
console.log(colors.length); // 4 (total number of items)
// Getting the last item
console.log(colors[colors.length - 1]); // "yellow" (last item)
β Adding Items to Arrays
There are several ways to add new items to your array:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
let animals = ["cat", "dog"];
// Method 1: push() - adds to the end
animals.push("bird");
console.log(animals); // ["cat", "dog", "bird"]
// Method 2: unshift() - adds to the beginning
animals.unshift("fish");
console.log(animals); // ["fish", "cat", "dog", "bird"]
// Method 3: Using index
animals[4] = "rabbit";
console.log(animals); // ["fish", "cat", "dog", "bird", "rabbit"]
// Adding multiple items at once
animals.push("horse", "cow");
console.log(animals); // ["fish", "cat", "dog", "bird", "rabbit", "horse", "cow"]
β Removing Items from Arrays
Just like adding items, there are different ways to remove them:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
let food = ["pizza", "burger", "salad", "pasta", "soup"];
// Method 1: pop() - removes from the end
let lastItem = food.pop();
console.log(lastItem); // "soup"
console.log(food); // ["pizza", "burger", "salad", "pasta"]
// Method 2: shift() - removes from the beginning
let firstItem = food.shift();
console.log(firstItem); // "pizza"
console.log(food); // ["burger", "salad", "pasta"]
// Method 3: splice() - removes from any position
// splice(start_index, number_of_items_to_remove)
food.splice(1, 1); // Remove 1 item starting at index 1
console.log(food); // ["burger", "pasta"]
π Useful Array Functions
Arrays come with many helpful functions. Let's learn the most important ones:
π Finding Items
1
2
3
4
5
6
7
8
9
10
11
12
13
14
let students = ["John", "Mary", "Bob", "Alice", "John"];
// indexOf() - finds the first position of an item
console.log(students.indexOf("Mary")); // 1
console.log(students.indexOf("Bob")); // 2
console.log(students.indexOf("David")); // -1 (not found)
// includes() - checks if an item exists
console.log(students.includes("Alice")); // true
console.log(students.includes("David")); // false
// find() - finds the first item that matches a condition
let longName = students.find(name => name.length > 4);
console.log(longName); // "Alice"
π Changing All Items
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
let numbers = [1, 2, 3, 4, 5];
// map() - creates a new array by changing each item
let doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
console.log(numbers); // [1, 2, 3, 4, 5] (original unchanged)
// forEach() - does something with each item
numbers.forEach(num => {
console.log("Number:", num);
});
// Output:
// Number: 1
// Number: 2
// Number: 3
// Number: 4
// Number: 5
π Filtering Items
1
2
3
4
5
6
7
8
9
10
11
let ages = [12, 25, 18, 35, 16, 28];
// filter() - creates a new array with items that match a condition
let adults = ages.filter(age => age >= 18);
console.log(adults); // [25, 18, 35, 28]
let teenagers = ages.filter(age => age >= 13 && age <= 19);
console.log(teenagers); // [18, 16]
// Original array is unchanged
console.log(ages); // [12, 25, 18, 35, 16, 28]
π Sorting Arrays
1
2
3
4
5
6
7
8
9
10
11
12
13
14
let fruits = ["banana", "apple", "orange", "cherry"];
let numbers = [3, 1, 4, 1, 5, 9, 2, 6];
// sort() - sorts items alphabetically
fruits.sort();
console.log(fruits); // ["apple", "banana", "cherry", "orange"]
// For numbers, we need to be more specific
numbers.sort((a, b) => a - b); // Sort from smallest to largest
console.log(numbers); // [1, 1, 2, 3, 4, 5, 6, 9]
// reverse() - reverses the order
numbers.reverse();
console.log(numbers); // [9, 6, 5, 4, 3, 2, 1, 1]
π Joining Arrays
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
let firstNames = ["John", "Mary"];
let lastNames = ["Smith", "Johnson"];
// concat() - combines arrays
let fullNames = firstNames.concat(lastNames);
console.log(fullNames); // ["John", "Mary", "Smith", "Johnson"]
// join() - converts array to string
let fruits = ["apple", "banana", "orange"];
let fruitString = fruits.join(", ");
console.log(fruitString); // "apple, banana, orange"
// split() - converts string to array
let sentence = "Hello world JavaScript";
let words = sentence.split(" ");
console.log(words); // ["Hello", "world", "JavaScript"]
π― Practice Examples
Let's practice with some real-world examples:
Example 1: Shopping Cart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Creating a shopping cart
let cart = [];
// Adding items to cart
cart.push("laptop");
cart.push("mouse");
cart.push("keyboard");
console.log("Cart:", cart); // ["laptop", "mouse", "keyboard"]
// Checking if item exists
if (cart.includes("laptop")) {
console.log("Laptop is in your cart! π»");
}
// Removing an item
let removedItem = cart.splice(cart.indexOf("mouse"), 1);
console.log("Removed:", removedItem[0]); // "mouse"
console.log("Updated cart:", cart); // ["laptop", "keyboard"]
// Total items in cart
console.log("Total items:", cart.length); // 2
Example 2: Student Grades
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Student grades
let grades = [85, 92, 78, 96, 88, 73, 91];
// Finding average grade
let total = grades.reduce((sum, grade) => sum + grade, 0);
let average = total / grades.length;
console.log("Average grade:", average.toFixed(1)); // 86.1
// Finding highest and lowest grades
let highest = Math.max(...grades);
let lowest = Math.min(...grades);
console.log("Highest grade:", highest); // 96
console.log("Lowest grade:", lowest); // 73
// Students who passed (grade >= 80)
let passingGrades = grades.filter(grade => grade >= 80);
console.log("Passing grades:", passingGrades); // [85, 92, 96, 88, 91]
console.log("Students passed:", passingGrades.length); // 5
Example 3: To-Do List
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Simple to-do list
let todoList = ["Buy groceries", "Walk the dog", "Study JavaScript"];
// Adding new tasks
todoList.push("Call mom");
todoList.push("Clean room");
console.log("To-do list:", todoList);
// Completing a task (removing from list)
function completeTask(task) {
let index = todoList.indexOf(task);
if (index !== -1) {
todoList.splice(index, 1);
console.log("β
Completed:", task);
} else {
console.log("β Task not found:", task);
}
}
completeTask("Walk the dog");
console.log("Updated list:", todoList);
// Checking remaining tasks
console.log("Tasks remaining:", todoList.length);
Example 4: Name List Manager
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Managing a list of names
let names = ["alice", "bob", "charlie", "diana"];
// Making all names start with capital letter
let capitalizedNames = names.map(name =>
name.charAt(0).toUpperCase() + name.slice(1)
);
console.log("Capitalized:", capitalizedNames); // ["Alice", "Bob", "Charlie", "Diana"]
// Finding names with more than 4 letters
let longNames = capitalizedNames.filter(name => name.length > 4);
console.log("Long names:", longNames); // ["Alice", "Charlie", "Diana"]
// Sorting names alphabetically
let sortedNames = capitalizedNames.sort();
console.log("Sorted:", sortedNames); // ["Alice", "Bob", "Charlie", "Diana"]
// Creating a sentence from names
let sentence = "My friends are: " + sortedNames.join(", ");
console.log(sentence); // "My friends are: Alice, Bob, Charlie, Diana"
π Summary
Arrays are super useful for storing and working with multiple items:
β’ Creating: Use square brackets []
or new Array()
β’ Adding: Use push()
for end, unshift()
for beginning
β’ Removing: Use pop()
for end, shift()
for beginning, splice()
for any position
β’ Finding: Use indexOf()
, includes()
, find()
, filter()
β’ Changing: Use map()
to create new array, forEach()
to do something with each item
β’ Sorting: Use sort()
and reverse()
β’ Joining: Use concat()
to combine arrays, join()
to make string
Practice with these examples and you'll become an array master! Arrays make your code more organized and powerful. Happy coding! ππ©βπ»π¨βπ»