Arrays in js
Arrays in js
Contents
1 Introduction to Arrays 1
1.1 Key Characteristics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Creating Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
4 Multidimensional Arrays 3
6 Best Practices 4
7 Conclusion 5
1 Introduction to Arrays
Arrays in JavaScript are ordered, list-like objects used to store multiple values
in a single variable. They are dynamic, meaning their size can change, and can
hold elements of any data type (numbers, strings, objects, etc.).
4 // Array constructor
5 let numbers = new Array(1, 2, 3, 4, 5);
6
1
Listing 3: Modifying Elements
2
1 let arr = [’a’, ’b’, ’c’, ’d’];
2 let sliced = arr.slice(1, 3); // [’b’, ’c’]
3 let combined = arr.concat([’e’, ’f’]); // [’a’, ’b’, ’c’, ’d’, ’e’,
’f’]
4 let str = arr.join(’-’); // ’a-b-c-d’
5 console.log(arr.indexOf(’c’)); // 2
Listing 6: Accessor Methods
3 // forEach
4 nums.forEach(num => console.log(num * 2)); // 2, 4, 6, 8
5
6 // map
7 let doubled = nums.map(num => num * 2); // [2, 4, 6, 8]
8
9 // filter
10 let evens = nums.filter(num => num % 2 === 0); // [2, 4]
11
12 // reduce
13 let sum = nums.reduce((acc, num) => acc + num, 0); // 10
Listing 7: Iteration Methods
4 Multidimensional Arrays
Arrays can contain other arrays, creating multidimensional structures.
1 let matrix = [
2 [1, 2, 3],
3 [4, 5, 6],
4 [7, 8, 9]
5 ];
6 console.log(matrix[1][2]); // Output: 6
Listing 8: Multidimensional Array
3
5 Common Use Cases
Arrays are used in various scenarios, such as data manipulation and algorithm
implementation.
13 console.log(highScores);
14 // Output: [{ name: ’Bob’, score: 92 }, { name: ’Alice’, score: 85
}]
Listing 9: Filtering and Sorting
6 Best Practices
• Use const for arrays to prevent reassignment, though array contents can
still be modified.
• Prefer array methods over manual loops for readability and maintainabil-
ity.
• Be cautious with methods like splice() and pop() as they mutate the orig-
inal array.
• Use Array.isArray() to check if a value is an array.
1 let arr = [1, 2, 3];
2 console.log(Array.isArray(arr)); // true
3 console.log(Array.isArray({})); // false
Listing 11: Checking Array Type
4
7 Conclusion
JavaScript arrays are versatile and powerful for managing collections of data.
Understanding their methods and best practices enables efficient coding and ro-
bust applications. For further learning, explore the MDN Array documentation.