🚀 1. Creating Arrays

Before we explore functions, let’s cover how to create arrays in JavaScript.

1.1 Using Array Literals (Recommended)

let arr = [1, 2, 3, 4, 5]; 
console.log(arr); // [1, 2, 3, 4, 5]

1.2 Using the Array Constructor

let arr1 = new Array(5); 
console.log(arr1); // [empty × 5] (5 empty slots)

let arr2 = new Array(1, 2, 3); 
console.log(arr2); // [1, 2, 3]

🚨 Avoid using new Array(size) because it creates empty slots! Instead, prefer Array.from({ length: size }).

1.3 Using Array.of() (To avoid new Array() issues)

let arr = Array.of(5);
console.log(arr); // [5]

🔥 2. Adding & Removing Elements

2.1 push() – Add elements at the end

Modifies the original array.

let nums = [1, 2, 3];
nums.push(4, 5);
console.log(nums); // [1, 2, 3, 4, 5]

🔹 Use case: Adding elements dynamically (e.g., chat messages, new data entries)


2.2 pop() – Remove last element

Modifies the original array.

let nums = [1, 2, 3, 4];
let removed = nums.pop();
console.log(nums); // [1, 2, 3]
console.log(removed); // 4

🔹 Use case: Implementing a stack (LIFO structure)


2.3 unshift() – Add elements at the beginning

Modifies the original array.

let nums = [2, 3, 4];
nums.unshift(1);
console.log(nums); // [1, 2, 3, 4]

🔹 Use case: Adding priority elements at the start of a queue.


2.4 shift() – Remove first element

Modifies the original array.

let nums = [1, 2, 3, 4];
let removed = nums.shift();
console.log(nums); // [2, 3, 4]
console.log(removed); // 1

🔹 Use case: Implementing a queue (FIFO structure)


🔍 3. Searching & Finding Elements

3.1 indexOf() – Get index of an element

Returns the first occurrence index or -1 if not found.

let colors = ['red', 'green', 'blue', 'red'];
console.log(colors.indexOf('red')); // 0
console.log(colors.indexOf('yellow')); // -1

🔹 Use case: Checking if an element exists before performing an operation.


3.2 lastIndexOf() – Get last occurrence index

let colors = ['red', 'green', 'blue', 'red'];
console.log(colors.lastIndexOf('red')); // 3

🔹 Use case: Finding the last inserted duplicate value.


3.3 includes() – Check if an element exists

Returns true or false.

let fruits = ['apple', 'banana', 'mango'];
console.log(fruits.includes('banana')); // true
console.log(fruits.includes('grape')); // false

🔹 Use case: Avoid unnecessary indexOf() checks.


3.4 find() – Find first matching element

Returns the first element that satisfies the condition.

let users = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 }
];

let user = users.find(user => user.age > 26);
console.log(user); // { name: 'Bob', age: 30 }

🔹 Use case: Finding a user in a database.


3.5 findIndex() – Find index of first matching element

let numbers = [5, 12, 8, 130, 44];
let index = numbers.findIndex(num => num > 10);
console.log(index); // 1 (because 12 is at index 1)

🔹 Use case: Useful for updating/removing a specific item in an array.


3.6 some() – Check if at least one element meets a condition

Returns true if at least one element satisfies the condition.

let ages = [10, 20, 30, 40];
console.log(ages.some(age => age >= 18)); // true

🔹 Use case: Checking if any user is above a certain age.


3.7 every() – Check if all elements meet a condition

Returns true only if all elements satisfy the condition.

let ages = [20, 25, 30, 35];
console.log(ages.every(age => age >= 18)); // true

🔹 Use case: Checking if all users meet certain criteria.


🔄 4. Transforming & Iterating Arrays

4.1 map() – Transform each element

Returns a new array.

let nums = [1, 2, 3];
let squared = nums.map(num => num ** 2);
console.log(squared); // [1, 4, 9]

🔹 Use case: Data transformation in APIs.


4.2 filter() – Get elements that match a condition

Returns a new array.

let ages = [10, 15, 18, 21];
let adults = ages.filter(age => age >= 18);
console.log(adults); // [18, 21]

🔹 Use case: Filtering search results.


4.3 reduce() – Reduce array to a single value

let numbers = [1, 2, 3, 4];
let sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // 10

🔹 Use case: Summing values in a shopping cart.


4.4 forEach() – Iterate over each element (No return)

let nums = [1, 2, 3];
nums.forEach(num => console.log(num * 2));
// 2
// 4
// 6

🔹 Use case: Logging each element.


🔥 5. Modifying & Extracting Arrays

5.1 slice() – Extract Part of an Array (Immutable)

✅ Returns a new array (does not modify original).

let nums = [1, 2, 3, 4, 5];
let sliced = nums.slice(1, 4); // Extracts from index 1 to 3
console.log(sliced); // [2, 3, 4]
console.log(nums);   // [1, 2, 3, 4, 5] (Original remains unchanged)

🔹 Use case: Getting a sublist without affecting the original data.


5.2 splice() – Modify an Array (Mutable)

🚨 Modifies the original array by removing, replacing, or inserting elements.

let colors = ['red', 'green', 'blue', 'yellow'];
let removed = colors.splice(1, 2, 'black', 'white');

console.log(colors);  // ['red', 'black', 'white', 'yellow'] (Mutated)
console.log(removed); // ['green', 'blue'] (Deleted items)

📌 Syntax: splice(startIndex, deleteCount, item1, item2, ...)

🔹 Use case: Inserting or removing elements dynamically.


5.3 reverse() – Reverse the Array (Mutable)

🚨 Modifies the original array.

let nums = [1, 2, 3, 4];
nums.reverse();
console.log(nums); // [4, 3, 2, 1]

🔹 Use case: Reversing order of a leaderboard, list, or queue.


5.4 sort() – Sorting the Array (Mutable)

🚨 Changes the original array and sorts as strings by default.

let numbers = [4, 20, 1, 100];
numbers.sort();
console.log(numbers); // [1, 100, 20, 4] ❌ Wrong (Sorted as Strings!)

Fix Sorting for Numbers

numbers.sort((a, b) => a - b); // Ascending order
console.log(numbers); // [1, 4, 20, 100]

numbers.sort((a, b) => b - a); // Descending order
console.log(numbers); // [100, 20, 4, 1]

🔹 Use case: Sorting leaderboard scores, prices, dates.


🎭 6. Flattening & Combining Arrays

6.1 concat() – Merge Multiple Arrays (Immutable)

✅ Returns a new array.

let arr1 = [1, 2];
let arr2 = [3, 4];
let merged = arr1.concat(arr2);
console.log(merged); // [1, 2, 3, 4]

🔹 Use case: Merging datasets without modifying originals.


6.2 flat() – Flatten Nested Arrays (Immutable)

✅ Returns a new array.

let nested = [1, [2, [3, 4]], 5];
console.log(nested.flat(1)); // [1, 2, [3, 4], 5] (Flattens 1 level)
console.log(nested.flat(2)); // [1, 2, 3, 4, 5] (Fully flattened)

🔹 Use case: Working with deeply nested API responses.


6.3 flatMap() – Map & Flatten in One Step

✅ Returns a new array.

let words = ['hello world', 'goodbye moon'];
let splitWords = words.flatMap(str => str.split(' '));
console.log(splitWords); // ['hello', 'world', 'goodbye', 'moon']

🔹 Use case: Processing text, breaking sentences into words.


🎯 7. Advanced & Utility Methods

7.1 fill() – Fill Array with a Value (Mutable)

🚨 Modifies the original array.

let arr = new Array(5).fill(0);
console.log(arr); // [0, 0, 0, 0, 0]

🔹 Use case: Creating placeholders for UI.


7.2 copyWithin() – Copy a Section of an Array (Mutable)

🚨 Overwrites part of the array.

let arr = [1, 2, 3, 4, 5];
arr.copyWithin(1, 3); // Copy from index 3, paste at index 1
console.log(arr); // [1, 4, 5, 4, 5]

🔹 Use case: Rearranging elements efficiently.


7.3 reduceRight() – Reduce from Right to Left

let nums = [1, 2, 3, 4];
let product = nums.reduceRight((acc, num) => acc * num, 1);
console.log(product); // 24

🔹 Use case: Processing arrays backwards.


7.4 toSorted() & toReversed() (Immutable Alternative)

🚀 Modern JavaScript alternative to sort() and reverse()

let numbers = [3, 1, 4, 2];

let sorted = numbers.toSorted(); // Does not mutate original
console.log(sorted);  // [1, 2, 3, 4]
console.log(numbers); // [3, 1, 4, 2] ✅ Original remains unchanged

let reversed = numbers.toReversed();
console.log(reversed); // [2, 4, 1, 3]

🔹 Use case: Avoid modifying original data while sorting or reversing.


🚀 8. Bonus: Super Cool Tricks

🔹 Remove Duplicates from an Array

let arr = [1, 2, 2, 3, 4, 4, 5];
let unique = [...new Set(arr)];
console.log(unique); // [1, 2, 3, 4, 5]

🔹 Convert an Object to an Array

let obj = { name: 'Saroj', age: 25 };
console.log(Object.entries(obj)); // [['name', 'Saroj'], ['age', 25]]
console.log(Object.keys(obj)); // ['name', 'age']
console.log(Object.values(obj)); // ['Saroj', 25]

🔹 Generate an Array of Numbers (Range)

let range = Array.from({ length: 5 }, (_, i) => i + 1);
console.log(range); // [1, 2, 3, 4, 5]

🔹 Shuffle an Array (Fisher-Yates Algorithm)

let arr = [1, 2, 3, 4, 5];
arr.sort(() => Math.random() - 0.5);
console.log(arr); // Randomly shuffled array

🎯 Final Takeaways

✅ JavaScript arrays are powerful—but some methods mutate while others return new arrays.

✅ Use map() for transformation, filter() for selection, reduce() for aggregation.

✅ Avoid holes in sparse arrays—use Array.from() or fill().

✅ Modern alternatives like toSorted() and toReversed() are safer than sort() and reverse().