JavaScript Array Data Type
Array Basics
Arrays are special objects used to store multiple values in a single variable. They are ordered collections that can hold any data type and are zero-indexed.
1// Array declaration examples
2let colors = ["red", "green", "blue"];
3let numbers = [1, 2, 3, 4, 5];
4let mixed = ["hello", 42, true, null];
5
6console.log(colors); // Output: ["red", "green", "blue"]
7console.log(numbers); // Output: [1, 2, 3, 4, 5]
8console.log(mixed); // Output: ["hello", 42, true, null]
9
10// Accessing array elements
11console.log(colors[0]); // Output: "red" (first element)
12console.log(colors[1]); // Output: "green" (second element)
13console.log(colors[2]); // Output: "blue" (third element)
14
15// Array length
16console.log(colors.length); // Output: 3Array Characteristics
Ordered Collection- Elements maintain their order and positionZero-Indexed- First element at index 0, second at index 1, etc.Dynamic Size- Can grow or shrink automaticallyMixed Types- Can store different data types in same array
Array Creation Methods
Arrays can be created using array literals, constructors, or from other data structures.
1// Method 1: Array literal (most common)
2let colors = ["red", "green", "blue"];
3let empty = [];
4
5// Method 2: Array constructor
6let numbers = new Array(1, 2, 3);
7let emptyArray = new Array(5); // Creates array with 5 empty slots
8
9// Method 3: Array.of() - creates from arguments
10let array1 = Array.of(1, 2, 3); // [1, 2, 3]
11let array2 = Array.of(5); // [5] (not array with 5 empty slots)
12
13// Method 4: Array.from() - creates from array-like objects
14let fromString = Array.from("hello"); // ["h", "e", "l", "l", "o"]
15let fromSet = Array.from(new Set([1, 2, 2, 3])); // [1, 2, 3]
16
17// Method 5: Using spread operator
18let copied = [...colors]; // ["red", "green", "blue"]
19
20console.log(colors); // Output: ["red", "green", "blue"]
21console.log(numbers); // Output: [1, 2, 3]
22console.log(emptyArray); // Output: [empty × 5]
23console.log(array1); // Output: [1, 2, 3]
24console.log(array2); // Output: [5]
25console.log(fromString); // Output: ["h", "e", "l", "l", "o"]Creation Methods
Array Literal- [] - simplest and most common methodConstructor- new Array() - less common, can be confusingArray.of()- Creates array from arguments reliablyArray.from()- Converts array-like objects to real arrays
Basic Array Methods
Arrays have built-in methods for adding, removing, and accessing elements.
1let fruits = ["apple", "banana"];
2
3// Adding elements
4fruits.push("orange"); // End: ["apple", "banana", "orange"]
5fruits.unshift("grape"); // Start: ["grape", "apple", "banana", "orange"]
6
7// Removing elements
8let last = fruits.pop(); // Removes "orange", returns it
9let first = fruits.shift(); // Removes "grape", returns it
10
11// Accessing elements
12console.log(fruits[0]); // "apple"
13console.log(fruits.at(-1)); // "banana" (negative index)
14
15// Finding elements
16console.log(fruits.indexOf("apple")); // 0
17console.log(fruits.includes("banana")); // true
18
19// Slicing and splicing
20let colors = ["red", "green", "blue", "yellow"];
21let slice1 = colors.slice(1, 3); // ["green", "blue"] (doesn't modify original)
22colors.splice(1, 2, "purple"); // Replaces 2 elements at index 1 with "purple"
23
24console.log(fruits); // Output: ["apple", "banana"]
25console.log(colors); // Output: ["red", "purple", "yellow"]
26console.log(slice1); // Output: ["green", "blue"]Basic Operations
push/pop- Add/remove from end - fast operationsunshift/shift- Add/remove from start - slower operationsindexOf/includes- Search for elements in arrayslice/splice- Extract or modify portions of array
Array Iteration Methods
JavaScript provides powerful methods for iterating over arrays and transforming data.
1let numbers = [1, 2, 3, 4, 5];
2
3// forEach - execute function for each element
4numbers.forEach(num => console.log(num * 2)); // 2, 4, 6, 8, 10
5
6// map - create new array with transformed elements
7let doubled = numbers.map(num => num * 2); // [2, 4, 6, 8, 10]
8
9// filter - create new array with elements that pass test
10let even = numbers.filter(num => num % 2 === 0); // [2, 4]
11
12// find - find first element that passes test
13let firstEven = numbers.find(num => num % 2 === 0); // 2
14
15// findIndex - find index of first element that passes test
16let firstEvenIndex = numbers.findIndex(num => num % 2 === 0); // 1
17
18// some - check if at least one element passes test
19let hasEven = numbers.some(num => num % 2 === 0); // true
20
21// every - check if all elements pass test
22let allEven = numbers.every(num => num % 2 === 0); // false
23
24// reduce - reduce array to single value
25let sum = numbers.reduce((total, num) => total + num, 0); // 15
26
27// reduceRight - reduce from right to left
28let rightSum = numbers.reduceRight((total, num) => total + num, 0); // 15
29
30console.log(doubled); // Output: [2, 4, 6, 8, 10]
31console.log(even); // Output: [2, 4]
32console.log(firstEven); // Output: 2
33console.log(hasEven); // Output: true
34console.log(sum); // Output: 15Advanced Array Methods
Modern JavaScript provides additional methods for array manipulation and transformation.
1let numbers = [3, 1, 4, 1, 5, 9];
2
3// Sorting
4let sorted = [...numbers].sort(); // [1, 1, 3, 4, 5, 9]
5let sortedDesc = [...numbers].sort((a, b) => b - a); // [9, 5, 4, 3, 1, 1]
6
7// Reversing
8let reversed = [...numbers].reverse(); // [9, 5, 1, 4, 1, 3]
9
10// Concatenation
11let arr1 = [1, 2];
12let arr2 = [3, 4];
13let combined = arr1.concat(arr2); // [1, 2, 3, 4]
14let spreadCombined = [...arr1, ...arr2]; // [1, 2, 3, 4]
15
16// Joining
17let joined = colors.join(", "); // "red, green, blue"
18
19// Flat - flatten nested arrays
20let nested = [1, [2, [3, [4]]]];
21let flat1 = nested.flat(); // [1, 2, [3, [4]]]
22let flat2 = nested.flat(2); // [1, 2, 3, [4]]
23let flatInf = nested.flat(Infinity); // [1, 2, 3, 4]
24
25// FlatMap - map then flatten
26let sentences = ["hello world", "good morning"];
27let words = sentences.flatMap(sentence => sentence.split(" ")); // ["hello", "world", "good", "morning"]
28
29// Fill - fill array with value
30let empty = new Array(3).fill(0); // [0, 0, 0]
31
32// CopyWithin - copy within array
33let arr = [1, 2, 3, 4, 5];
34arr.copyWithin(0, 3); // [4, 5, 3, 4, 5]
35
36console.log(sorted); // Output: [1, 1, 3, 4, 5, 9]
37console.log(joined); // Output: "red, green, blue"
38console.log(flat1); // Output: [1, 2, [3, [4]]]Common Array Patterns
Arrays are used in various patterns for data manipulation and problem solving.
1// Pattern 1: Removing duplicates
2let duplicates = [1, 2, 2, 3, 4, 4, 5];
3let unique = [...new Set(duplicates)]; // [1, 2, 3, 4, 5]
4
5// Pattern 2: Finding max/min
6let values = [10, 5, 20, 15];
7let max = Math.max(...values); // 20
8let min = Math.min(...values); // 5
9
10// Pattern 3: Chaining methods
11let products = [
12 { name: "laptop", price: 1000, category: "electronics" },
13 { name: "phone", price: 500, category: "electronics" },
14 { name: "book", price: 20, category: "education" }
15];
16
17let expensiveElectronics = products
18 .filter(product => product.category === "electronics")
19 .filter(product => product.price > 300)
20 .map(product => product.name); // ["laptop", "phone"]
21
22// Pattern 4: Array destructuring
23let [firstColor, secondColor, ...otherColors] = ["red", "green", "blue", "yellow"];
24console.log(firstColor); // "red"
25console.log(otherColors); // ["blue", "yellow"]
26
27// Pattern 5: Swapping variables
28let a = 1, b = 2;
29[a, b] = [b, a]; // a=2, b=1
30
31// Pattern 6: Creating ranges
32let range = Array.from({ length: 5 }, (_, i) => i + 1); // [1, 2, 3, 4, 5]
33
34// Pattern 7: Grouping elements
35let items = ["apple", "banana", "carrot", "date"];
36let grouped = items.reduce((groups, item) => {
37 let key = item[0]; // First letter
38 if (!groups[key]) groups[key] = [];
39 groups[key].push(item);
40 return groups;
41}, {});
42// { a: ["apple"], b: ["banana"], c: ["carrot"], d: ["date"] }
43
44console.log(unique); // Output: [1, 2, 3, 4, 5]
45console.log(max); // Output: 20
46console.log(expensiveElectronics); // Output: ["laptop", "phone"]Array Best Practices
Following best practices when working with arrays leads to more efficient and maintainable code.
1// Use const for arrays that won't be reassigned
2const COLORS = ["red", "green", "blue"];
3// COLORS = []; // Error - cannot reassign
4COLORS.push("yellow"); // OK - modifying content is allowed
5
6// Prefer array methods over loops
7const numbers = [1, 2, 3, 4, 5];
8
9// GOOD - using array methods
10const doubled = numbers.map(n => n * 2);
11const even = numbers.filter(n => n % 2 === 0);
12
13// AVOID - using traditional loops
14// let doubled = [];
15// for (let i = 0; i < numbers.length; i++) {
16// doubled.push(numbers[i] * 2);
17// }
18
19// Use descriptive variable names for arrays
20const userEmails = ["alice@test.com", "bob@test.com"]; // GOOD
21const productIds = [101, 102, 103]; // GOOD
22
23const arr = ["alice@test.com", "bob@test.com"]; // BAD
24const stuff = [101, 102, 103]; // BAD
25
26// Use spread operator for copying arrays
27const original = [1, 2, 3];
28const copy = [...original]; // GOOD
29// const copy = original.slice(); // OK but less clear
30
31// Avoid sparse arrays
32const dense = [1, 2, 3]; // GOOD
33const sparse = [1, , 3]; // AVOID
34
35// Use Array.isArray() for type checking
36const maybeArray = [1, 2, 3];
37console.log(Array.isArray(maybeArray)); // true - GOOD
38// console.log(typeof maybeArray); // "object" - BAD
39
40// Use destructuring for clean code
41const [first, second] = [1, 2, 3];
42const [head, ...tail] = [1, 2, 3, 4];
43
44// Use appropriate methods for the task
45const items = [1, 2, 3];
46
47// Check existence: includes() over indexOf()
48console.log(items.includes(2)); // GOOD - clear intent
49// console.log(items.indexOf(2) !== -1); // OK but less clear
50
51// Transform data: map() over forEach() when creating new array
52const squares = items.map(x => x * x); // GOOD - returns new array
53// const squares = [];
54// items.forEach(x => squares.push(x * x)); // AVOID - imperative
55
56// Use flatMap() for map + flat operations
57const data = [[1], [2, 3]];
58const flattened = data.flatMap(arr => arr); // [1, 2, 3] - GOOD