Contact Information

KodeBlog

We're Available 24/ 7. Drop us an email.

JavaScript Arrays

An array is a variable that is capable of storing multiple values using a single variable. For example, if you want to store a list of available colors that you would like to present to the user, you can either create separate variables for each color which is very cumbersome or you can create a single array variable then populate it with available colors.

This lesson will show you how to work with arrays in JavaScript

Topics to be covered

We will cover the following topics in this lesson

Lesson Prerequisites

For you to successfully complete this lesson, you should have the following requirements

  • NodeJS - we will be executing JavaScript files directly using NodeJS from the command line. Alternatively you can execute the files in the web browser but that takes a a little more time and involves working with multiple programs.
  • Web Browser - a web browser can be used as an alternative to executing JavaScript files that we will be working with.
  • Visual Studio Code - we will be using it as the code editor. It comes with a built-in terminal that will allow us to easily execute JavaScript code from within the text editor. You can also use any code editor that you prefer.
  • JavaScript Basics - this is an added advantage and not mandatory. We will explain every piece of code covered in these lessons.

Lesson Practical Examples Project Setup

This is a practical based lesson. For you to successfully work out the examples given in this lesson, you will need to setup the following directories and files

Create a new directory called javascript-arrays

Open the directory javascript-arrays in Visual Studio Code or your favorite code editor

Create the following files inside your project folder.

  • arrays.js - this file will be used to for code dealing with the switch statement

The following visualizes our project setup

javascript-arrays
-arrays.js

How to declare array variables

JavaScript provides two ways of declaring arrays. You can either do it by using square brackets [...] or you can create an instance of the Array object. The square brackets method is the most commonly used one. Let us now look at a practical example.

let colors = ['red','green','blue','black','pink'];

console.log(colors);
console.log(typeof colors);

HERE,

  • let colors = ['red','green','blue','black','pink']; defines an array variable colors that contains a number of string values.
  • console.log(colors); prints the contents of our variable to the terminal.
  • console.log(typeof colors); prints the type of the variable colors

Open the terminal and run the following command

node arrays.js

You should be able to get the following results

[ 'red', 'green', 'blue', 'black', 'pink' ]
object

Let's now look at the other way of declaring arrays in JavaScript using the Array object.

Add the following code to arrays.js

let cars = new Array('BMW','Benz','Ford');

console.log(cars);
console.log(typeof cars);

HERE,

  • let cars = new Array('BMW','Benz','Ford'); initializes the variable cars to an instance of the object Array and passes in the values that we want to store as arguments to the object constructor. A constructor is simply a method that is called when a new instance of an object is created.
  • console.log(cars); prints the value of the variable cars to the console
  • console.log(typeof cars); prints the type of the variable cars

Accessing Array Elements

In this section, we will work with the colors variable that we created in the above section and learn how we can access the individual elements that are in the array. JavaScript assigns each element an index number that we can use to access it. This is done automatically. Index numbers start from the value 0 to n - 1.

For example, if you have an array with 5 items, then the first index is 0 and the last index is gotten using the formula total items count minus 1. So in our case, 5 - 1 gives us 4 which will be the index number of the last item.

let colors = ['red','green','blue','black','pink'];

console.log('The first element is ' + colors[0]);

HERE,

  • console.log('The first element is ' + colors[0]); prints the first element in the array using colors[0] the variable name colors and then square brackets with an index number [0] to access the value

Open the terminal then run the following command

node arrays.js

You should be able to get the following results

The first element is red

Let's now try to access an index of a number that does not exist.

let colors = ['red','green','blue','black','pink'];

console.log('The Nth element is ' + colors[33]);

Executing the above code gives us the following results

The Nth element is undefined

Let's now look at how we can access all of the elements in the array using a for loop.

let colors = ['red','green','blue','black','pink'];

for (let i = 0; i < colors.length; i++){
    console.log(colors[i]);
}

HERE,

  • for (let i = 0; i < colors.length; i++){..} we initialize the variable i to the value 0, we then set a condition i < colors.length which basics checks if the value of i is less than the total elements in the array. Finally, we increment the value of the variable i by 1 using i++.
  • console.log(colors[i]); prints out the value of the element are the index value of the variable i.

Running the above code gives us the following results

red
green
blue
black
pink

Array Methods

Arrays are objects that come with built-in methods that make working with arrays real easy. We will continue working our example of colors variable

Converting Arrays to Strings

You can convert an array to a string using the built-in method toString like so

let colors = ['red','green','blue','black','pink'];

console.log('toString() Method:',colors.toString());

HERE,

  • colors.toString() calls the toString() on our array object

Executing the above code produces the following command separated string

toString() Method: red,green,blue,black,pink

Joining Array Elements Together

You can also join all the elements in an array using the join method. The join methods also allows you to set a separator between the individual elements like so.

let colors = ['red','green','blue','black','pink'];

console.log('join() Method:',colors.join(' * '));

HERE,

  • colors.join(' * ') calls the join() method of our array object. The argument * is used to separate the various elements as we join them together.

Executing the above code produces the following results

join() Method: red * green * blue * black * pink

How to Pop The Last Element from an Array

The method pop method is used to remove the last item from the array variable like so.

let colors = ['red','green','blue','black','pink'];

console.log('colors before popping:',colors);
console.log('popped color:',colors.pop());
console.log('colors after popping:',colors);

HERE,

  • console.log('colors before popping:',colors); prints all elements before popping
  • console.log('popped color:',colors.pop()); pops the last element then its the returned value in the console
  • console.log('colors after popping:',colors); prints our our array after we have removed the last element from it.

Executing the above code produces the following results

colors before popping: [ 'red', 'green', 'blue', 'black', 'pink' ]
popped color: pink
colors after popping: [ 'red', 'green', 'blue', 'black' ]

How to Push an Element to the Array

The push method is used to an a append an item to the the elements and then return the total length. Let's add a new color brown to our array of colors

let colors = ['red','green','blue','black','pink'];

console.log('elements before pushing:',colors);
console.log('push new element, array length is:',colors.push('brown'));
console.log('elemts after pushing',colors);

HERE,

  • console.log('elements before pushing:',colors); prints the colors before we push an element to it
  • console.log('push new element, array length is:',colors.push('brown')); pushes the color brown to our elements
  • console.log('elemts after pushing',colors); prints the value of color after pushing to it.

Executing the above code produces the following results

elements before pushing: [ 'red', 'green', 'blue', 'black', 'pink' ]
push new element, array length is: 6
elemts after pushing [ 'red', 'green', 'blue', 'black', 'pink', 'brown' ]

How to Remove the First Element from an Array

The shift method is used to remove the first element from the list. The following example demonstrates how to do that.

let colors = ['red','green','blue','black','pink'];

console.log('colors before shifting:',colors);
console.log('shifted color:',colors.shift());
console.log('colors after shifting:',colors);

HERE,

  • console.log('colors before shifting:',colors); prints the value of colors before shifting
  • console.log('shifted color:',colors.shift()); removes the first element then returns it
  • console.log('colors after shifting:',colors); prints the value of colors after removing the first element using the shift method.

Executing the above code produces the following results

colors before shifting: [ 'red', 'green', 'blue', 'black', 'pink' ]
shifted color: red
colors after shifting: [ 'green', 'blue', 'black', 'pink' ]

How to add a new item as the first element to an array

In this section, we will look at how we can add a new item as the first element then push the index numbers of the existing elements using the unshift command.

let colors = ['red','green','blue','black','pink'];

console.log('colors before unshifting:',colors);
console.log('unshift color:',colors.unshift('yellow'));
console.log('colors after unshifting:',colors);

HERE,

  • console.log('unshift color:',colors.unshift('yellow')); uses the unshift function to add a new item yellow at the beginning of the array.

Executing the above code produces the following results

colors before unshifting: [ 'red', 'green', 'blue', 'black', 'pink' ]
unshift color: 6
colors after unshifting: [ 'yellow', 'red', 'green', 'blue', 'black', 'pink' ]

How to Sort an Array

In this section, we will use the sort method to sort the values of the array colors

let colors = ['red','green','blue','black','pink'];

console.log('colors before sorting:',colors);
console.log('colors after sorting:',colors.sort());

HERE,

  • colors.sort() calls the sort method which sorts the elements in the array in ascending order.

Executing the above code produces the following results.

colors before sorting: [ 'red', 'green', 'blue', 'black', 'pink' ]
colors after sorting: [ 'black', 'blue', 'green', 'pink', 'red' ]

Summary

Arrays allows us to store related values in a single variable that can be accessed using index numbers. Index numbers for array elements start from 0 to total elements minus 1. Arrays are objects and they come with a number of built-in methods that make it easy for us to work with arrays. Examples of common methods include shift,push,pop,sort etc.

Author: Rodrick Kazembe

Rodrick is a developer who works on Desktop, Web and Mobile Applications. He is familiar with Python, Java, JavaScript, C++, C#, Kotlin, PHP, Python and the list goes on. Rodrick enjoys sharing knowledge especially when it comes to technology.

JavaScript Objects

JavaScript JSON

Leave A Reply