# JavaScipt Arrays

*An array is a special variable, which can hold more than one value.*

or

an array is a data structure used to store multiple values in a single variable. It is an ordered collection of elements, where each element can be accessed by its index or position within the array.

## Different ways to create Arrays

**Using Assignment operator**: It is most common way to create an array in JavaScript would be to assign that array to a variable like this

```javascript
const cars = ["Saab", "Volvo", "BMW"];
console.log(cars); // ["Saab", "Volvo", "BMW"]
```

**<mark>Using Array constructor</mark>:** Another way to create an array is to use the `new` keyword with the `Array` constructor. the output will same

```javascript
const cars = new Array("Saab", "Volvo", "BMW");
console.log(cars); // ["Saab", "Volvo", "BMW"]
```

`Using Array.of()`**:** Another way to create an array is to use the `Array.of()` method. This method takes in any number of arguments and creates a new array instance.

```javascript
const cars = Array.of("Saab", "Volvo", "BMW");
console.log(cars); // ["Saab", "Volvo", "BMW"]
```

**<mark>Using split() method:</mark>** The `split()` method splits a string into an array of substrings.

```javascript
const cars = "Saab Volvo BMW";
console.log(cars.split(" ");  // [ 'saab', 'volvo', 'bmw' ]
```

### Accessing Array Elements

You access an array element by referring to the **index number**:

```javascript
const cars = ["Saab", "Volvo", "BMW"];
console.log(cars[0]); // "Saab"
```

> **Note:** Array indexes start with 0.
> 
> \[0\] is the first element. \[1\] is the second element.

### Changing an Array Element

This statement changes the value of the first element in `cars`:

```javascript
const cars = ["Saab", "Volvo", "BMW"];
 cars[0]="Audi";
console.log(cars); //  ["Audi", "Volvo", "BMW"]
```

### Arrays are Objects

Arrays are a special type of objects. The `typeof` operator in JavaScript returns "object" for arrays.

But, JavaScript arrays are best described as arrays.

Arrays use **numbers** to access its "elements".

### Adding Array Elements

```javascript
const cars = ["Saab", "Volvo", "BMW"];
cars.push("Audi");
console.log(cars); // ["Saab", "Volvo", "BMW","Audi"]
```

In JavaScript, **arrays** always use **numbered indexes**.  

```javascript
const person = [];
person[0] = "John";
person[1] = "Doe";
person[2] = 46;
person.length;    // Will return 3
person[0];   // "John"
console.log(person) // [ 'John', 'Doe', 46 ]
```
