programming

JavaScript Array Methods

// Array Functions Legend:
// ⚠️ Mutable Functions   
// ✅ Immutable Functions

const arr = [1, 2, 3, 4];

// Iteration
arr.forEach(item => item); // ⚠️ Log: 1, 2, 3, 4
arr.map(item => item * 2); // ✅ Log: [2, 4, 6, 8]
arr.filter(item => item > 2); // ✅ Log: [3, 4]
arr.reduce((acc, curr) => acc + curr, 0); // ✅ Log: 10

// Searching
arr.indexOf(3); // ✅ Log: 2
arr.findIndex(item => item === 3); // ✅ Log: 2
arr.includes(4); // ✅ Log: true
arr.some(item => item > 2); // ✅ Log: true
arr.every(item => item > 0); // ✅ Log: true

// Checks

Array.isArray(arr); // ✅ Log: true

// Modification
arr.push(5); // ⚠️ Log: [1, 2, 3, 4, 5]
arr.pop(); // ⚠️ Log: [1, 2, 3, 4]
arr.shift(); // ⚠️ Log: [2, 3, 4]
arr.unshift(0); // ⚠️ Log: [0, 2, 3, 4]
arr.splice(1, 2, 9, 10); // ⚠️ Log: [0, 9, 10, 4]

// Concatenation
const newArr = arr.concat([6, 7]); // ✅ Log: [0, 9, 10, 4, 6, 7]

// Transformation
arr.join(', '); // ✅ Log: "0, 9, 10, 4"
arr.reverse(); // ⚠️ Log: [4, 10, 9, 0]
arr.sort((a, b) => a - b); // ⚠️ Log: [0, 4, 9, 10]
arr.slice(1, 3); // ✅ Log: [4, 9]

// Functional Programming
arr.map(item => item * 2).filter(item => item > 4); // ✅ Log: [8, 18, 20]
arr.reduce((acc, curr) => acc.concat(curr), []); // ✅ Log: [0, 4, 9, 10]

Mutable refers to data structures that can be modified or altered after creation, allowing changes to the underlying values.

Immutable implies that once a data structure is created, its values cannot be changed, providing stability and avoiding direct modifications.

Author avatar
About Authorpolubis

👋 Hi there! My name is Adrian, and I've been programming for almost 7 years 💻. I love TDD, monorepo, AI, design patterns, architectural patterns, and all aspects related to creating modern and scalable solutions 🧠.