JavaScript arrays are ordered, zero-indexed collections of values stored under a single variable name. They are a fundamental data structure, enabling efficient storage and manipulation of lists of data. Arrays in JavaScript are dynamic, meaning they can resize and hold a mix of different data types.
- Ordered and Zero-Indexed: Elements are stored in a specific order and accessed using a numeric index, starting at
0for the first element. - Dynamic Size: Arrays can grow or shrink as elements are added or removed, without needing to define a fixed size upfront.
- Heterogeneous: A single array can contain different data types, such as strings, numbers, objects, and even other arrays.
- Objects: Arrays are special types of objects in JavaScript; the
typeofoperator returns"object"for arrays. - Shallow Copies: Built-in array-copy operations create shallow copies, meaning nested objects within the array still refer to the same object in memory.
- 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(): A versatile method for adding/removing elements at any specific position.
- Iterating: Use methods like
forEach(),map(), orfilter(), or standard loops (for,for...of) to process array elements. - Combining Arrays:
concat()merges two or more arrays into a new array without modifying the originals. - Sorting and Searching:
sort(): Sorts the elements of an array in place.find(): Returns the value of the first element that satisfies a provided testing function.includes(): Checks if an array contains a certain element and returns a boolean.
Changing an Array Element
This statement changes the value of the first element in cars:
Converting an Array to a String
The JavaScript method toString() converts an array to a string of (comma separated) array values.
Arrays are Objects
Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays.
But, JavaScript arrays are best described as arrays.
Arrays use numbers to access its "elements". In this example, person[0] returns John:
const person = ["John", "Doe", 46];
Array Methods: