JavaScript Arrays
Fundamentals, Methods
JavaScript arrays are powerful tools for data management. This article combines fundamental concepts, creation methods, key techniques, and practical tips using simple and advanced examples.
let arr1 = []; // Empty array
let arr2 = [1, 'text', true]; // Mixed types
let numbers = new Array(1, 2, 3); // [1, 2, 3]
let emptyArray = new Array(5); // Creates empty array with 5 elements
In JavaScript, arrays can contain any data type:
let mixedArray = [
1,
'two',
true,
{ name: 'Aram', age: 30 },
[4, 5, 6]
];
Creates array from array-like or iterable objects:
let str = 'hello';
let arr6 = Array.from(str); // ['h', 'e', 'l', 'l', 'o']
Creates array from arguments regardless of type:
let arr7 = Array.of(5); // [5] (Not [ <5 empty elements> ])
Example: Output last element
const fruits = ['apple', 'banana', 'mango'];
console.log(fruits[fruits.length - 1]); // "mango"
let fruits = ['apple', 'banana'];
console.log(fruits.length); // 2
fruits.length = 5; // ["apple", "banana", empty × 3]
Avoid empty elements:
let sparseArr = [1, , 3]; // Bad practice
Arrays are objects and use reference assignment:
let arrA = [1, 2];
let arrB = arrA;
arrB.push(3);
console.log(arrA); // [1, 2, 3]
Method | Description | Example |
splice() | Adds/removes elements | arr.splice(1, 0, 'x') |
reverse() | Reverses array | arr.reverse() |
sort() | Sorts elements | arr.sort((a, b) => a - b) |
Method | Description | Example |
concat() | Merges arrays | arr.concat([4, 5]) |
includes() | Checks element existence | arr.includes('apple') |
indexOf() | Finds element index | arr.indexOf('banana') |
Method | Description | Example |
find() | Finds first matching element | arr.find(n => n > 2) |
every() | Checks all elements | arr.every(n => n > 0) |
flat() | Flattens nested arrays | arr.flat(2) |
Method | Description | Example |
push() | Adds to end | fruits.push('pear'); |
pop() | Removes from end | fruits.pop(); |
unshift() | Adds to start | fruits.unshift('peach'); |
shift() | Removes from start | fruits.shift(); |
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
for (let item of arr) {
console.log(item);
}
arr.forEach((item, index) => {
console.log(index, item);
});
let numbers = [1, 2, 3];
let doubled = numbers.map(n => n * 2); // [2, 4, 6]
let evens = numbers.filter(n => n % 2 === 0); // [2]
let sum = numbers.reduce((acc, curr) => acc + curr, 0); // 6
let phrases = ["Hello world", "Goodbye universe"];
let words = phrases.flatMap(phrase => phrase.split(' ')); // ["Hello", "world", "Goodbye", "universe"]
let [first, second] = [10, 20];
console.log(first); // 10
let arr8 = [1, 2];
let arr9 = [...arr8, 3]; // [1, 2, 3]
let arr10 = new Array(3).fill(0); // [0, 0, 0]
let matrix = [
[1, 2],
[3, 4],
[5, 6]
];
console.log(matrix[1][0]); // 3
let flatMatrix = matrix.flat(); // [1, 2, 3, 4, 5, 6]
Shift/Unshift vs Push/Pop
shift/unshift are slow for large arrays (O(n) complexity):
// Bad
arr.unshift(0); // Avoid with large arrays
// Good
arr.push(4); // O(1) complexity
Avoid Nested Loops
Use Map or Set for fast lookups:
let map = new Map(arr.map(item => [item.id, item]));
const colors = ['red', 'blue'];
console.log(Array.isArray(colors)); // true
// Bad
let copy = arr.slice();
// Good (ES6)
let copy = [...arr];
// Assume we get array of objects from API
let users = [
{ id: 1, name: 'Anna', age: 25 },
{ id: 2, name: 'Aram', age: 30 }
];
// Filter users over 25 and get names
let names = users
.filter(user => user.age > 25)
.map(user => user.name);
console.log(names); // ["Aram"]
let arrA = [1, 2, 3];
let arrB = [3, 4, 5];
let merged = [...new Set([...arrA, ...arrB])]; // [1, 2, 3, 4, 5]
Fundamentals, Methods