What is Array
Tags: webdev, javascript, beginners, programming
Published: 2023-06-13 15:28:34

## 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:

```js
const numbers = [1, 2, 3, 4, 5];
```

You can also create an array of strings:

```js
const words = ["apple", "banana", "mango"];
```

Or an array of mixed data types:

```js
const values = [true, "hello", 42, null];
```

You can also create an array of arrays:

```js
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.

```js
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.

```js
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:

```js
1
2
3
4
5
```

You can also use the `for...of` loop to iterate over the elements of an array.

```js
const numbers = [1, 2, 3, 4, 5];

for (const number of numbers) {
	console.log(number);
}
```

It will print the following output:

```js
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.

```js
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:

```js
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`.

```js
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`.

```js
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.

```js
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.

```js
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.

```js
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.

```js
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.

```js
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:

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:
   ```js
   const names = ["John", "Mary", "Bob"];
   names.sort((a, b) => a.localeCompare(b)); 
   // the array is now ["Bob", "John", "Mary"]
   ```
7. If you want to sort objects, you can use `a.property - b.property` instead of `a - b`, like this:
   ```js
   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.

```js
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.

```js
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.

```js
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.

```js
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.

```js
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.

```js
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.