Beginner's Guide To Arrays In JavaScript

Beginner's Guide To Arrays In JavaScript

Introduction

An array is an "object" for storing sequences of values. The values are written between square brackets, separated by commas. An array can hold values of different data types e.g strings, integers, and even other arrays. If arrays did not exist, different values would have to be stored in a separate variable for each value. This would be less efficient and more error-prone, therefore arrays make life as a JavaScript developer much easier.

const mixed = ['five', 3, ['ten', false, 7], 'four'];

Creating Arrays

Arrays can be created using two methods:

  1. Array constructor method: This is by using the Array constructor.
    const pasta = new Array('Spaghetti', 'Rigatoni', 'Lasagna');
    
  2. Array literal notation method: This is by using the square brackets to wrap a comma-separated list of elements.
    const pasta= ['Spaghetti', 'Rigatoni', 'Lasagna'];
    

Accessing Array Items.

An item in an array can be accessed using bracket notation by referring to the index number. Note that array indexes start from 0 because computers start counting from 0. Therefore, the first element in an array will have an index of 0, the second will have an index of 1, e.t.c.

let animals = ['Elephant', 'Deer', ['Canary', 'Swallow'], 'Lion', 'Antelope'];

animals[0];
// returns "Elephant"

animals[animals.length - 1];
// returns "Antelope"

"animals.length" returns the number of items in the array. Since the indexes start from 0, we need to subtract 1 from the length of the array to get the last item.

We can also access items in a multidimensional array.

let birds = animals[2] // the inner array lies on the index position 2 of the animals array.
console.log(birds)

//output
['Canary', 'Swallow']

let firstBird = animals[2][0] // this gets the first item in the inner array of the animals array.
console.log(firstBird);

//output
Canary

An item in an array can also be modified using its index.

animals[1] = 'Goat';
console.log(animals);

//output
['Elephant', 'Goat', ['Canary', 'Swallow'], 'Lion', 'Antelope']

Array Manipulation Methods.

Arrays are also useful because they can be easily manipulated i.e elements can be removed, added, replaced, etc. Some of the ways in which arrays can be manipulated are as follows:

- Push()

The push() method is used to add an element to the end of an array.

let pasta= ['Spaghetti', 'Rigatoni', 'Lasagna']; 
pasta.push('Linguini');
console.log(pasta);

// output:
['Spaghetti', 'Rigatoni', 'Lasagna', 'Linguini']

- Unshift()

The unshift() method is used to add an element to the beginning of an array.

let pasta= ['Spaghetti', 'Rigatoni', 'Lasagna'];
pasta.unshift('Penne');
console.log(pasta);

// output:
['Penne', 'Spaghetti', 'Rigatoni', 'Lasagna']

- Pop()

The pop() method is used to remove an element from the end of an array. It returns the removed element.

let pasta= ['Spaghetti', 'Rigatoni', 'Lasagna'];
const lastElement = pasta.pop();
console.log(lastElement);

// output:
Lasagna

- Shift()

The shift() method is used to remove an element from the beginning of an array. It also returns the removed element.

let pasta= ['Penne’, ‘Spaghetti', 'Rigatoni', 'Lasagna'];
const firstElement = pasta.shift();
console.log(firstElement);

// output:
Penne

- Splice()

The splice() method is used to add or remove items from an array. It takes the following parameters:

  1. An integer (representing the index) that specifies at what position to add or remove items. A negative value is used to specify the position from the end of the array.
  2. The number of items to be removed. If set to 0, no items will be removed. (This is an optional parameter)
  3. The new items to be added to the array. (This is an optional parameter).
let colours= ['Yellow', 'Violet', 'Aqua', 'Pink']; 
colours.splice(2, 1, 'Teal', 'Red'); // This removes one item from position 2 and inserts the colours "Teal" and "Red" starting from position 2.
console.log(colours);

// output
['Yellow', 'Violet', 'Teal', 'Red', 'Pink']

let colours= ['Yellow', 'Violet', 'Aqua', 'Pink'];
colours.splice(-2, 1); // Remove one element from index -2

// output 
['Yellow', 'Violet', 'Pink'] // 'Aqua' was removed.

- Slice()

The slice() method (not to be confused with splice() ) is another way to remove items from an array. However, unlike the methods explained above, the slice() method is non-mutating i.e it does not change the original array. It produces a new array with the changes. The slice() method takes two parameters:

  1. The index where the copy should begin.
  2. The index where the copy should end. The end index is non-inclusive.
const colours = ['Yellow', 'Violet', 'Teal', 'Red', 'Pink', 'Blue', 'Black'];

const colours1 = colours.slice(1, 4);
console.log(colours1);

// output
['Violet', 'Teal', 'Red']

const colours2 = colours.slice(2); // This makes a copy from index 2 to the end of the array because the second parameter is not provided.
console.log(colours2);

// output
['Teal', 'Red', 'Pink', 'Blue', 'Black']

Read more about arrays here:

w3schools

MDN

Conclusion

There are many more methods that can be used in modifying arrays. JavaScript ES6 introduced more non-mutating methods for modifying arrays, and these methods will be covered in a future article.