📘 Additional Discussion: JavaScript
Array Functions
JavaScript arrays come with many built-in functions (also called methods) that help you store,
manipulate, search, and update data. These functions make coding easier and help you write
cleaner programs.
Below are the most commonly used and most important array functions, grouped by their
purpose.
✅ 1. Adding and Removing Elements
➤ push()
Adds a new element at the end of the array.
let fruits = ["apple", "banana"];
[Link]("mango");
[Link](fruits);
// ["apple", "banana", "mango"]
➤ pop()
Removes the last item in the array.
let fruits = ["apple", "banana", "mango"];
[Link]();
[Link](fruits);
// ["apple", "banana"]
➤ unshift()
Adds an item at the beginning of the array.
let numbers = [2, 3, 4];
[Link](1);
[Link](numbers);
// [1, 2, 3, 4]
➤ shift()
Removes the first item in the array.
let numbers = [1, 2, 3, 4];
[Link]();
[Link](numbers);
// [2, 3, 4]
🔄 2. Searching and Checking Values
➤ indexOf()
Returns the index (position) of a value. Returns -1 if not found.
let colors = ["red", "green", "blue"];
let index = [Link]("green");
[Link](index);
// 1
➤ includes()
Checks if a value exists inside the array.
let pets = ["dog", "cat", "bird"];
[Link]([Link]("cat"));
// true
🛠️ 3. Transforming Arrays
➤ map()
Creates a new array by applying a function to each element.
let nums = [1, 2, 3];
let doubled = [Link](n => n * 2);
[Link](doubled);
// [2, 4, 6]
➤ filter()
Creates a new array with ONLY elements that pass a test.
let ages = [12, 18, 25, 10];
let adults = [Link](a => a >= 18);
[Link](adults);
// [18, 25]
➤ reduce()
Reduces an array to a single value (sum, average, etc.).
let numbers = [1, 2, 3, 4];
let total = [Link]((sum, num) => sum + num, 0);
[Link](total);
// 10
🔄 4. Looping Through Elements
➤ forEach()
Runs a function for each element.
let students = ["Ana", "Mark", "John"];
[Link](name => {
[Link]("Hello " + name);
});
✂️ 5. Extracting or Editing Parts of an
Array
➤ slice()
Extracts part of an array (does NOT modify original).
let letters = ["a", "b", "c", "d", "e"];
let part = [Link](1, 4);
[Link](part);
// ["b", "c", "d"]
➤ splice()
Adds, removes, or replaces array elements (MODIFIES the array).
Example 1: remove items
let items = ["pen", "pencil", "book", "eraser"];
[Link](1, 2); // remove 2 items starting at index 1
[Link](items);
// ["pen", "eraser"]
Example 2: insert items
[Link](1, 0, "marker");
[Link](items);
// ["pen", "marker", "eraser"]
🧩 6. Joining & Splitting
➤ join()
Converts array into a string.
let words = ["Hello", "world"];
[Link]([Link](" "));
// "Hello world"
🔢 7. Sorting and Reversing
➤ sort()
Sorts elements (alphabetically by default).
let names = ["John", "Ana", "Mike"];
[Link]();
[Link](names);
// ["Ana", "John", "Mike"]
➤ reverse()
Reverses the order of elements.
let nums = [1, 2, 3];
[Link]();
[Link](nums);
// [3, 2, 1]