JavaScript Arrays Tutorial
Arrays are an essential data structure in JavaScript that allow you to store and manipulate multiple values within a single variable. Arrays can hold a mix of different data types and are particularly useful for tasks involving collections of items.
Specifically: An array is an object that holds values (of any type) not particularly in named properties/keys, but rather in numerically indexed positions.
Creating Arrays
You can create arrays using square brackets and separating elements with commas. We are formatting the array to look just like the objects that it is:
var arrayVariable = [
"John",
"Doe",
30,
false
];
Accessing Array Elements:
Array elements are accessed using zero-based indexing:
arrayVariable[0]; // "John"
arrayVariable[1]; // Doe
arrayVariable[2]; // 30
arrayVariable[3]; // false
arrayVariable.length; // 4
Pictorially, here is how arrays are saved in memory:
We do not have to write arrays like objects, we conventionally write them on a straight line like the ones below:
const numbers = [1, 2, 3, 4, 5];
const fruits = ["apple", "banana", "orange"];
const mixed = [1, "hello", true, null];
Accessing Array Elements
Once again, array elements are accessed using zero-based indexing:
console.log(numbers[0]); // 1
console.log(fruits[1]); // "banana"
console.log(mixed[2]); // true
Modifying Array Elements
You can modify array elements by assigning new values to specific indices:
fruits[0] = "pear";
console.log(fruits); // ["pear", "banana", "orange"]
Array Length
The length
property provides the number of elements in an array:
console.log(numbers.length); // 5
Adding Elements
You can add elements to the end of an array using the push
method:
fruits.push("grape");
console.log(fruits); // ["pear", "banana", "orange", "grape"]
Removing Elements
To remove elements from an array, you can use the pop
method to remove the last element or the splice
method to remove specific elements:
fruits.pop(); // Removes "grape"
console.log(fruits); // ["pear", "banana", "orange"]
fruits.splice(1, 1); // Removes one element starting at index 1
console.log(fruits); // ["pear", "orange"]
Iterating through Arrays
You can use loops like for
or forEach
to iterate through array elements:
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
fruits.forEach(function(fruit) {
console.log(fruit);
});
Array Methods
JavaScript provides a variety of useful array methods, such as map
, filter
, and reduce
, for performing advanced operations on arrays.
const doubledNumbers = numbers.map(function(num) {
return num * 2;
});
const evenNumbers = numbers.filter(function(num) {
return num % 2 === 0;
});
const sum = numbers.reduce(function(acc, num) {
return acc + num;
}, 0);
Array Destructuring
Destructuring allows you to extract array elements into individual variables:
const [first, second, ...rest] = numbers;
console.log(first); // 1
console.log(second); // 2
console.log(rest); // [3, 4, 5]
Some JavaScript Array Methods
# | Method | Description | Example |
---|---|---|---|
1 | push() / pop() | Add/remove elements from the end of an array. |
|
2 | unshift() / shift() | Add/remove elements from the beginning of an array. |
|
3 | concat() | Merge two or more arrays to create a new array. |
|
4 | join() | Combine array elements into a string using a specified separator. |
|
5 | slice() | Create a shallow copy of an array by extracting elements based on start and end indices. |
|
6 | splice() | Add or remove elements from a specific position in an array. |
|
7 | indexOf() / lastIndexOf() | Find the index of an element (or its last occurrence) in an array. |
|
8 | includes() | Check if an array contains a specific element. |
|
9 | find() / findIndex() | Retrieve the first element (or its index) that satisfies a condition. |
|
10 | filter() | Create a new array containing elements that pass a test. |
|
11 | map() | Create a new array by applying a function to each element. |
|
12 | reduce() / reduceRight() | Apply a function to each element to accumulate a single value. |
|
13 | forEach() | Execute a function for each element in the array. |
|
14 | sort() | Sort array elements based on provided function or their default string representation. |
|
15 | reverse() | Reverse the order of elements in an array. |
|
16 | every() / some() | Check if all/some elements satisfy a condition. |
|
17 | flat() / flatMap() | Flatten nested arrays or map and flatten at the same time. |
|
18 | isArray() | Check if a given value is an array. |
|
19 | toString() / toLocaleString() | Convert an array to a string representation. |
|
20 | fill() | Fill array elements with a static value from a start to an end index. |
|
21 | copyWithin() | Copy a sequence of array elements to another position. |
|
22 | keys() / values() / entries() | Create iterators for keys, values, or key-value pairs. |
|
23 | from() | Create a new array from an iterable object or a string. |
|
24 | of() | Create a new array with individual elements as arguments. |
|