What is Array
Muhammad Rizwan Ashiq
Posted on June 13, 2023
What is Array?
Array is a type of object
that represents an ordered list of values. Each value in an array is called an element
, and the elements are separated by commas (,
), and enclosed in square brackets ([]
). Here's an example of an array of numbers:
const numbers = [1, 2, 3, 4, 5];
You can also create an array of strings:
const words = ["apple", "banana", "mango"];
Or an array of mixed data types:
const values = [true, "hello", 42, null];
You can also create an array of arrays:
const values = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
Accessing Array Elements
You can access the elements of an array using the []
operator and the index of the element you want to access. The index of the first element is 0
, and the index of the last element is array.length - 1
,
Note: array.length
is the number of elements in the array.
const numbers = [1, 2, 3, 4, 5];
console.log(numbers[0]); // 1
console.log(numbers[1]); // 2
console.log(numbers[2]); // 3
console.log(numbers[3]); // 4
console.log(numbers[numbers.length - 1]); // 5
Iterating Over Array Elements using loops
Can iterate over the elements of an array using the for
loop.
const numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
It will print the following output:
1
2
3
4
5
You can also use the for...of
loop to iterate over the elements of an array.
const numbers = [1, 2, 3, 4, 5];
for (const number of numbers) {
console.log(number);
}
It will print the following output:
1
2
3
4
5
Array Methods
There are many functions that you can use to manipulate arrays in JavaScript. Some of the most common ones are:
push()
Adds one or more elements to the end of an array and returns the new length of the array.
const numbers = [1, 2, 3];
numbers.push(4);
// the array is now [1, 2, 3, 4]
numbers.push(5, 6);
// the array is now [1, 2, 3, 4, 5, 6]
Check the following code:
const numbers = [1, 2, 3];
numbers[6] = 7;
console.log(numbers.length); // 7
console.log(numbers); // [1, 2, 3, , , , 7]
The length
of the array is 7
, but the array has only 4
elements.
pop()
Removes, and returns the last element from an array. If the array is empty, it returns undefined
.
const numbers = [1, 2, 3, 4, 5];
const last = numbers.pop();
// the array is now [1, 2, 3, 4] and last is 5
shift()
Removes the first element from an array and returns that element. If the array is empty, it returns undefined
.
const numbers = [1, 2, 3, 4, 5];
const first = numbers.shift();
// the array is now [2, 3, 4, 5] and first is 1
unshift()
Adds one or more elements to the beginning of an array and returns the new length
of the array.
const numbers = [4, 5];
numbers.unshift(3);
// the array is now [3, 4, 5]
numbers.unshift(1, 2);
// the array is now [1, 2, 3, 4, 5]
slice()
Extracts a section of an array and returns a new array. You can specify the starting index and the ending index (not inclusive) of the section you want to extract.
const numbers = [1, 2, 3, 4, 5];
const middle = numbers.slice(1, 4);
// middle is [2, 3, 4]
splice()
Can be used to remove or replace elements from an array. It takes at least two arguments: the starting index and the number of elements to remove.
const numbers = [1, 2, 3, 4, 5];
const removed = numbers.splice(1, 2);
// numbers is now [1, 4, 5] and removed is [2, 3]
sort()
Sorts the elements of an array in place and returns the sorted array.
const numbers = [5, 2, 4, 1, 3];
numbers.sort();
// the array is now [1, 2, 3, 4, 5]
By default, the sort()
method sorts ascendingly, but you can also sort descendingly by passing a function to the sort()
method.
const numbers = [5, 2, 4, 1, 3];
numbers.sort(a => -a);
// the array is now [5, 4, 3, 2, 1]
Here's how the sort()
method works:
- The
sort()
method compares the first element with the second element (like here:a
withb
). - If you want to sort ascendingly, the
sort()
then checks ifa
is greater thanb
usinga - b
.- If
a
is greater thanb
, it returns a positive number. - If
a
is less thanb
, it returns a negative number. - If
a
is equal tob
, it returns0
.
- If
- If it returns:
- A positive number, the
sort()
method will swap the two elements. - A negative number, or zero, the
sort()
method will not swap the two elements.
- A positive number, the
- The
sort()
method will then compare the second element with the third element, and so on, and will repeat this process until the array is sorted. - If you want to sort descendingly, then you will need to return
b - a
instead ofa - b
. - If you want to sort strings, you can use
a.localeCompare(b)
instead ofa - b
, like this:
const names = ["John", "Mary", "Bob"];
names.sort((a, b) => a.localeCompare(b));
// the array is now ["Bob", "John", "Mary"]
- If you want to sort objects, you can use
a.property - b.property
instead ofa - b
, like this:
const people = [
{ name: "John", age: 20 },
{ name: "Mary", age: 30 },
{ name: "Bob", age: 25 },
];
people.sort((a, b) => a.age - b.age);
// the array is now sorted by age
reverse()
Reverses the order of the elements in an array in place and returns the reversed array.
const numbers = [1, 2, 3, 4, 5];
numbers.reverse();
// the array is now [5, 4, 3, 2, 1]
concat()
Creates a new array by merging (concatenating) existing arrays.
const numbers = [1, 2, 3];
const letters = ["a", "b", "c"];
const numbersAndLetters = numbers.concat(letters);
// numbersAndLetters is [1, 2, 3, "a", "b", "c"]
join()
Creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string.
const numbers = [1, 2, 3];
const numbersString = numbers.join();
// numbersString is "1,2,3"
const numbersStringWithSpaces = numbers.join(" ");
// numbersStringWithSpaces is "1 2 3"
indexOf()
Returns the first index at which a given element can be found in the array, or -1
if it is not present.
const numbers = [1, 2, 3, 4, 5];
numbers.indexOf(3); // returns 2
numbers.indexOf(10); // returns -1
lastIndexOf()
Returns the last index at which a given element can be found in the array, or -1
if it is not present.
const numbers = [1, 2, 3, 4, 5, 3];
numbers.lastIndexOf(3); // returns 5
numbers.lastIndexOf(10); // returns -1
includes()
Determines whether an array includes a certain value among its entries, returning true or false as appropriate.
const numbers = [1, 2, 3, 4, 5];
numbers.includes(3); // returns true
numbers.includes(10); // returns false
There are many other useful functions as well like foreach()
, map()
, filter()
, find()
, etc. I will explain them in detail in the next chapters.
Conclusion
In this chapter, we learned about arrays and how to use them. We learned about the different ways to create an array, how to access elements in an array, how to add and remove elements from an array, and how to use some of the most useful array methods.
Posted on June 13, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.