Scope. Modern JavaScript. includes arrived in ES2016; find, findIndex, fill and spread syntax are ES2015 features. Methods such as fill, sort and splice mutate the original array.
This page provides a detailed guide to JavaScript array methods, including common array operations, ES6 new features, performance optimization, and more.
Array Creation
JavaScript provides several ways to create arrays:
Using Array Literals
let arr = [1, 2, 3];
Using Constructor
let arr = new Array(1, 2, 3);
Using Array.of Method
let arr = Array.of(1, 2, 3);
Using Array.from Method
let arr = Array.from('123'); // ['1', '2', '3']
Array Operations
Arrays provide a rich set of methods for data manipulation (CRUD):
Adding Elements
push: Adds one or more elements to the end of an array.unshift: Adds one or more elements to the beginning of an array.
Removing Elements
pop: Removes the last element from an array.shift: Removes the first element from an array.splice: Removes any number of elements starting from a specific index.
Finding Elements
indexOf: Returns the index of a specific element in the array.includes: Checks if the array contains a specific element.
Iterating over Arrays
forEach: Executes a provided callback function once for each array element.map: Creates a new array with the results of calling a provided function on every element in the calling array.filter: Creates a new array with all elements that pass the test implemented by the provided function.
Array Transformation
join: Joins all elements of an array into a single string.slice: Returns a shallow copy of a portion of an array.concat: Merges two or more arrays.
ES2015 and Later
ES6 introduced many enhancements for array manipulation:
Spread Operator
let arr = [1, 2, 3];
let arr2 = [...arr, 4, 5]; // [1, 2, 3, 4, 5]
Array.prototype.find
const arr = [1, 2, 3];
let result = arr.find(item => item > 2); // 3
Array.prototype.findIndex
const arr = [1, 2, 3];
let index = arr.findIndex(item => item > 2); // 2
Array.prototype.fill
const arr = [1, 2, 3];
arr.fill(0); // [0, 0, 0]
Array.prototype.includes
const arr = [1, 2, 3];
arr.includes(2); // true
Performance Optimization
Performance optimization is crucial when handling large arrays:
- Choose
map,filteror a loop for clarity, then measure with representative data; native methods are not universally faster. - For frequently manipulated arrays, consider using
Typed Arrays. - Avoid DOM operations within loops; instead, collect the necessary DOM changes and apply them all at once.
Conclusion
Through this guide, you should have a deeper understanding of JavaScript array operations. For more information, please refer to MDN Web Docs.