JavaScript : Arrays

Variables can store only a single value at a time but what if you want to store multiple items at the same time? It is not efficient to create separate variables to store each item, right?

In JavaScript, we can store multiple items together using an array. An array is just a list-like structure or a container that is used to store multiple elements irrespective of the data type.

In JavaScript, you can create an array as given below,

let items = ["Apples", "Bananas", 2, 4, 8, "Purple", true, false]

An array is just a variable that stores a list. In the above line, we have created an items variable that contains a list of 8 items. All the items inside the array have different data types. You can create an array of strings, numbers, boolean, objects, or a combination of multiple types. An array does not care about the type of data that is stored inside it.

You can also create an array that contains another array such as,

let items = [1, 2, 3, ["Apples", "Bananas"]]

The syntax for creating an array

let/const/var arrayName = []

An array name should not begin with a number.

An array is created using square brackets.

Accessing elements from an array

Arrays are zero-indexed. It means that the first element inside an array is stored at index 0, the second element is stored at index 1, and so on.

If you want to access the third element then you can do it by using the following expression,

let items = [1, 2, 3, 4, 5]

let thirdElement = items[2]

Now, the thirdElement variable contains the value 3.

To access an element from the array you have to specify the index of the element inside the square brackets i.e arrayName[index].

Since the array is a list-like structure, you can use loops to access all elements from the array.

To get the length of an array you can use the length property of an array i.e array.length

forEach loop

let items = [1, 2, 3, 4, 5]
items.forEach(item => console.log(item))

// for each loop is used to access each element present inside the array

for loop

let items = [1, 2, 3, 4, 5]
for(let i=0; i< items.length; i++) {
    console.log(items[i])
}

// The above loop will print each item to the console
// items.length contains the value 5 because array contains 5 elements
// hence the loop will run until the value of i is less than 5

Modifying array elements

We have seen how to create and access array elements. You can also modify the elements inside the array.

let items = [1, 2, 3, 4, 5]

Suppose you want to modify the value of the third element and replace it with 10. You can do it by,

items[2] = 10

Now the array will be [1, 2, 10, 4, 5]

In this way, you can reassign a value to any index inside the array. This property of an array is called mutability. It means that you can modify the elements inside the array.

Array Methods

let items = [1, 2, 3, 4, 5]

// get length of an array
console.log(items.length) // prints 5

/*
    add and remove elements from the end of the array
    push - adds element at the end of the array
    pop - removes element from the end of the array
*/

// add element at the end of an array
items.push(6) // returns [1, 2, 3, 4, 5, 6]
items.push(7, 8) // returns [1, 2, 3, 4, 5, 6, 7, 8]

/* At this point,
    items = [1, 2, 3, 4, 5, 6, 7, 8]
*/

// remove element from the end of an array
items.pop() // returns [1, 2, 3, 4, 5, 6, 7]

let removedValue = items.pop()
console.log(removedValue) // prints 7

/* At this point,
    items = [1, 2, 3, 4, 5, 6]
*/

// check if element is present inside array or not
console.log(items.includes(10)) // prints false
console.log(items.includes(1)) // prints true

/* 
    find index of array elements
    indexOf - returns index of the first occurrence of the element
    lastIndexOf - returns index of the last occurrence of the element
*/

let box = ["pen", "pencil", "eraser", "pen", "pen"]

console.log(box.indexOf("pen")) // prints 0

console.log(box.lastIndexOf("pen")) // prints 4

/*
    add and remove elements from the beginning of the array
    shift - removes the first element from the array
    unshift - add element at the beginning of the array
*/

let items = [1, 2, 3]

items.shift() // returns [2, 3]
items.unshift(0, 1) // returns [0, 1, 2, 3]

/*
    sort - sorts an array in increasing order
    to sort array in decreasing order, you have to pass comparison function 
    to the sort
    syntax - array.sort()
*/

let items = [ 5, 4, 3, 1, 2]
items.sort() // returns [1, 2, 3, 4, 5]

// sort in decreasing order
let items = [ 5, 4, 3, 1, 2]
items.sort((a,b)=>{
    if(a<b){
        return 1;
    }else if(a>b){
        return -1;  
    }else{
        return 0;
    }
})
// returns [5, 4, 3, 2, 1]

/*
    slice - returns a portion of array without modifying the array 
    syntax - slice(start, end), slice(start)

    slice does not return element present at the end index specified
*/

let items = [ 5, 4, 3, 1, 2]
console.log(items.slice(2)) // returns [3, 1, 2]
console.log(items.slice(2,4)) // returns [3, 1]

You can learn more about array methods here.

19