Clean β’ Professional
An Array in JavaScript is a special type of object used to store ordered collections of values. These values can be of any type β numbers, strings, Booleans, objects, other arrays, or even functions. Arrays make it easy to store, access, and manipulate multiple values using indices.
Arrays are useful when you need to:
Example:
let fruits = ["apple", "banana", "orange"];
console.log(fruits); // ["apple", "banana", "orange"]
Adding / Removing Elements
arr.push(2); // [1, 'hello', { id: 1 }, 2]
arr.splice(1, 1, 'world'); // [1, 'world', { id: 1 }, 2]
Iterating / Transforming
forEach(callback): Run a function for each element.
arr.forEach(item => console.log(item));
map(callback): Create a new array with transformed elements.
let doubled = [1, 2, 3].map(x => x * 2); // [2, 4, 6]
filter(callback): Create a new array with elements passing a test.
let evens = [1, 2, 3, 4].filter(x => x % 2 === 0); // [2, 4]
reduce(callback, initialValue): Reduce to a single value.
let sum = [1, 2, 3].reduce((acc, x) => acc + x, 0); // 6
find(callback): Return the first element matching the condition.
let found = arr.find(x => x === 'world'); // 'world'
includes(value): Check if a value exists.
arr.includes(1); // true
sort(compareFn): Sort in place. Use compareFn for numbers.
[3, 1, 2].sort((a, b) => a - b); // [1, 2, 3]
let part = arr.slice(1, 3); // ['world', { id: 1 }]
arr.join(', '); // '1, world, [object Object], 2'
Spread Operator: Copy or merge arrays.
let copy = [...arr]; // Shallow copy
let merged = [...arr, ...[3, 4]];
let [first, second] = arr; // first = 1, second = 'world'
Sparse Arrays: Gaps are filled with undefined.
let sparse = [1, , 3]; // [1, undefined, 3]Β