What are Arrays?
In JavaScript, Arrays are used to store and organize data efficiently.
Arrays are ordered collections of values, where each value is called an item or element.
You can think of arrays as containers that can hold multiple items such as numbers, strings, objects, or even other arrays.
Arrays are mutable, which means their elements can be changed after the array is created. You can update, add, or remove elements without creating a new array.
Creating Arrays
You can create arrays in two ways:
-
Using array literal:
You can create arrays using array literal
[]
, i.e., by defining the array elements within square brackets[ ]
.For example:
// Array of strings const fruits = ["apple", "banana", "orange", "grapes"]; // Array of integers const numbers = [8, 9, 3]; // Array of mixed data types const data = ["apple", "banana", 9, 5.3]; console.log(fruits); // Output: ["apple", "banana", "orange", "grapes"] console.log(numbers); // Output: [8, 9, 3] console.log(data); // Output: ["apple", "banana", 9, 5.3]
-
Using the
new
keyword:The other method for creating arrays is by using the
new
keyword.For example:
const fruits = new Array("apple", "banana", "orange", "grapes"); console.log(fruits); // Output: ["apple", "banana", "orange", "grapes"]
If you do like this:
const arr = new Array(3); console.log(arr); // Output: [ <3 empty slots> ]
This creates an array of length 3, but with empty slots, not values.
The literal syntax []
is generally preferred over new Array()
because it’s simpler and less error-prone.
Finding the Length of the Array
You can find the length of the array (number of elements in an array) using the length
property.
For example:
const numbers = [1, 2, 3, 4, 5, 6, 7];
const arrLength = numbers.length;
console.log(arrLength); // Output: 7
Checking if a Value is an Array
JavaScript provides a built-in method (Array.isArray()
) to check whether a value is an array.
console.log(Array.isArray([1, 2, 3])); // Output: true
console.log(Array.isArray("hello")); // Output: false
Accessing Elements in Arrays
Each item or element in an array has a number called its index. JavaScript starts counting from 0, so the first item is at index 0, the second at 1, and so on.
You can also use negative indexes, so the last item is at index -1, the second last at -2, and so on.
Array items can be accessed and manipulated using this index.
For example:
const fruits = ["apple", "banana", "orange", "grapes"];
// Indexes: 0 1 2 3
// Negative indexes:-4 -3 -2 -1
console.log(fruits[0]); // Output: apple
console.log(fruits[1]); // Output: banana
console.log(fruits[2]); // Output: orange
console.log(fruits[3]); // Output: grapes
Accessing an Index That Doesn’t Exist
If you try to access an index that doesn’t exist in the array, JavaScript won’t throw an error, instead, it simply returns undefined
.
For example:
const fruits = ["apple", "banana", "orange", "grapes"];
console.log(fruits[10]); // Output: undefined
In this case, there is no element at index 10, so the output is undefined
.
Changing Elements in the Array
Arrays in JavaScript are mutable, so you can change elements directly using their index.
For example:
const fruits = ["apple", "banana", "orange", "grapes"];
console.log(fruits); // Output: ['apple', 'banana', 'orange', 'grapes']
// This will change the element at index 1
fruits[1] = "plum";
console.log(fruits); // Output: ['apple', 'plum', 'orange', 'grapes']
You can also add new elements by assigning a value to an index that doesn’t yet exist.
For example:
const fruits = ["apple", "banana", "orange", "grapes"];
// This will add a new element at index 4. If the index doesn’t already exist, JavaScript will create it.
fruits[4] = "plum";
console.log(fruits); // Output: ['apple', 'banana', 'orange', 'grapes', 'plum']
Effortlessly Empty an Array
You can empty an array effortlessly by using the length
property.
For example:
let numbers = [1, 2, 3, 4];
numbers.length = 0;
console.log(numbers); // Output: []
The length
property of an array determines the number of elements in the array. By setting it to 0
, you're essentially removing all elements from the array, effectively clearing it.
This method is simple and works in all browsers.
This method is efficient because it doesn't create a new array but modifies the existing one directly. However, if the array is referenced elsewhere, those references will also see the empty array, which may or may not be desirable depending on your use case.
Sparse Arrays and Assigning Values at a Far Index
If you assign a value to an index far beyond the current length of the array, JavaScript creates empty slots (called sparse array elements) in between.
For example:
const arr = [1, 2, 3];
arr[10] = 99;
console.log(arr.length); // Output: 11
console.log(arr[5]); // Output: undefined
console.log(arr); // Output: [1, 2, 3, <7 empty items>, 99]
These empty slots behave like undefined
when accessed, but they are not actual values, just uninitialized gaps in the array.
Multi-dimensional Arrays
Arrays can also hold other arrays as elements. This allows you to create multi-dimensional arrays, like a grid or matrix.
For example:
const matrix = [
[1, 2, 3], // index 0
[4, 5, 6], // index 1
[7, 8, 9], // index 2
];
console.log(matrix[0]); // Output: [1, 2, 3]
console.log(matrix[1][2]); // Output: 6 (3rd element in 2nd array)
When you're writing matrix[1][2]
, you're first accessing the item at index 1
of the matrix
array, which is the second row: [4, 5, 6]
. Then, you're accessing the item at index 2
of that row (i.e., matrix[1]
), which is the number 6
.
Multi-dimensional arrays are useful for representing tables, game boards, or any nested data structure.
Remove Duplicate Elements from an Array
You can use the Set
object to remove duplicate elements from an array and create a unique collection of elements.
For example:
const numbers = [1, 2, 2, 3, 4, 4, 5];
const uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers);
// Output: [1, 2, 3, 4, 5]
Here,
Set
: Automatically removes duplicate elements from the array.- Spread Operator (
...
): Converts theSet
back into an array.
Benefits of using Set
Set
handles duplicates automatically and requires fewer lines of code.
Note: A Set keeps the order of items as they first appear, so the unique array keeps the original order of elements.
You can also use the filter()
method to remove duplicates.
For example:
const numbers = [1, 2, 2, 3, 4, 4, 5];
const uniqueNumbers = numbers.filter(
(item, index) => numbers.indexOf(item) === index
);
console.log(uniqueNumbers);
// Output: [1, 2, 3, 4, 5]
Here,
filter()
: Loops through each element and includes it in the new array only if it passes the condition.- Condition:
numbers.indexOf(item) === index
ensures only the first occurrence of an element is kept:indexOf(item)
finds the first occurrence of the element.- If the current index matches this, the element is unique at that point and is included.
This works well for small arrays but may be slower for large ones. Use Set
for better performance.