Description
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.
1. Array Creation
1.1. Literal Syntax (Recommended)
let arr1 = []; // Empty array
let arr2 = [1, 'text', true]; // Mixed types
1.2. Constructor Syntax
let numbers = new Array(1, 2, 3); // [1, 2, 3]
let emptyArray = new Array(5); // Creates empty array with 5 elements
1.3. Mixed Type Arrays
In JavaScript, arrays can contain any data type:
let mixedArray = [
1,
'two',
true,
{ name: 'Aram', age: 30 },
[4, 5, 6]
];
1.4 Array.from()
Creates array from array-like or iterable objects:
let str = 'hello';
let arr6 = Array.from(str); // ['h', 'e', 'l', 'l', 'o']
1.5 Array.of()
Creates array from arguments regardless of type:
let arr7 = Array.of(5); // [5] (Not [ <5 empty elements> ])
2. Core Array Properties
- Dynamic. Array size and element types can change at any time.
- Mutable. Elements can be added, removed, or modified.
- Indexing. Elements are accessible via 0-based index.
Example: Output last element
const fruits = ['apple', 'banana', 'mango'];
console.log(fruits[fruits.length - 1]); // "mango"
Length Property
let fruits = ['apple', 'banana'];
console.log(fruits.length); // 2
fruits.length = 5; // ["apple", "banana", empty × 3]
Sparse Arrays
Avoid empty elements:
let sparseArr = [1, , 3]; // Bad practice
References
Arrays are objects and use reference assignment:
let arrA = [1, 2];
let arrB = arrA;
arrB.push(3);
console.log(arrA); // [1, 2, 3]
3. Essential Methods
3.1. Mutator Methods (Modify Array)
| 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) |
3.2. Accessor Methods (Non-modifying)
| Method | Description | Example |
| concat() | Merges arrays | arr.concat([4, 5]) |
| includes() | Checks element existence | arr.includes('apple') |
| indexOf() | Finds element index | arr.indexOf('banana') |
3.3. Iteration Methods
| 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) |
3.4. Element Addition/Removal
| 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(); |
4. Iteration & Loops
4.1. Classic For Loop
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
4.2. For...of Loop
for (let item of arr) {
console.log(item);
}
4.3. Array.forEach()
arr.forEach((item, index) => {
console.log(index, item);
});
5. Array Transformations
5.1. Map & Filter
let numbers = [1, 2, 3];
let doubled = numbers.map(n => n * 2); // [2, 4, 6]
let evens = numbers.filter(n => n % 2 === 0); // [2]
5.2. Reduce
let sum = numbers.reduce((acc, curr) => acc + curr, 0); // 6
5.3. FlatMap
let phrases = ["Hello world", "Goodbye universe"];
let words = phrases.flatMap(phrase => phrase.split(' ')); // ["Hello", "world", "Goodbye", "universe"]
6. ES6+ Features
6.1. Destructuring
let [first, second] = [10, 20];
console.log(first); // 10
6.2. Spread Operator
let arr8 = [1, 2];
let arr9 = [...arr8, 3]; // [1, 2, 3]
6.3. Array.fill()
let arr10 = new Array(3).fill(0); // [0, 0, 0]
7. Multi-dimensional Arrays
7.1. Creation
let matrix = [
[1, 2],
[3, 4],
[5, 6]
];
7.2. Access Elements
console.log(matrix[1][0]); // 3
7.3. Convert to 1D Array
let flatMatrix = matrix.flat(); // [1, 2, 3, 4, 5, 6]
8. Performance & Optimization
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]));
9. Best Practices
9.1. Use const if array isn't reassigned
const colors = ['red', 'blue'];
9.2 Verify array type with isArray
console.log(Array.isArray(colors)); // true
9.3 Avoid copying large arrays
// Bad
let copy = arr.slice();
// Good (ES6)
let copy = [...arr];
10. Practical Examples
10.1. API Data Processing
// 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"]
10.2. Merge Arrays Without Duplicates
let arrA = [1, 2, 3];
let arrB = [3, 4, 5];
let merged = [...new Set([...arrA, ...arrB])]; // [1, 2, 3, 4, 5]Fundamentals, Methods