DEV Community

Muhammad Rizwan Ashiq
Muhammad Rizwan Ashiq

Posted on • Updated on

What is Array

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];
Enter fullscreen mode Exit fullscreen mode

You can also create an array of strings:

const words = ["apple", "banana", "mango"];
Enter fullscreen mode Exit fullscreen mode

Or an array of mixed data types:

const values = [true, "hello", 42, null];
Enter fullscreen mode Exit fullscreen mode

You can also create an array of arrays:

const values = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
];
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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]);
}
Enter fullscreen mode Exit fullscreen mode

It will print the following output:

1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

It will print the following output:

1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

Check the following code:

const numbers = [1, 2, 3];

numbers[6] = 7;

console.log(numbers.length); // 7
console.log(numbers); // [1, 2, 3, , , , 7]
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

Here's how the sort() method works:

  1. The sort() method compares the first element with the second element (like here: a with b).
  2. If you want to sort ascendingly, the sort() then checks if a is greater than b using a - b.
    1. If a is greater than b, it returns a positive number.
    2. If a is less than b, it returns a negative number.
    3. If a is equal to b, it returns 0.
  3. If it returns:
    1. A positive number, the sort() method will swap the two elements.
    2. A negative number, or zero, the sort() method will not swap the two elements.
  4. 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.
  5. If you want to sort descendingly, then you will need to return b - a instead of a - b.
  6. If you want to sort strings, you can use a.localeCompare(b) instead of a - b, like this:
   const names = ["John", "Mary", "Bob"];
   names.sort((a, b) => a.localeCompare(b)); 
   // the array is now ["Bob", "John", "Mary"]
Enter fullscreen mode Exit fullscreen mode
  1. If you want to sort objects, you can use a.property - b.property instead of a - 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
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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"]
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)