TypeScript Arrays Tutorial

In this TypeScript tutorial we learn how to store multiple values of the same type in a single data container, called an array.

We learn how to initialize, access, mutate, add and delete elements in an array. We also discuss how to create an array object instance.

Lastly, we cover a list of helpful array object methods.

Here's a table of contents of what you'll learn in this lesson:
(click on a link to skip to its section)

Let's jump right in.

What is an array

An array is a data container that can store multiple separate values of the same type in a single container.

As an example, consider a list of groceries. It would be cumbersome to store items in our list as separate variables, as well as to access them one by one.

Example:
var groceryItem1:string = "Milk";
var groceryItem2:string = "Bread";
var groceryItem3:string = "Cheese";

Instead, we use an array that’s stored in a variable and can be accessed by a single identifier.

If we’re working with a larger number of values, it’s better to store them in an array instead of declaring many variables. Arrays are stored together, in sequence, in memory and are accessed faster.

How to initialize an array literal

The easiest, and most straightforward, way to create an array is by initializing an array literal.

To create an array literal, we start with a unique name, followed by the assignment operator and open and close square brackets.

Inside the square brackets we add one or more values, separating them with a comma.

Syntax:
 var name : type[] = [value1, value2, ...];

When explicitly specifying the array type, we add a pair of empty square brackets at the end of the type.

Example:
// array of strings
var employee : string[] = ["John", "Jane", "Jack", "Jill"];
//array of numbers
var fibonacci : number[] = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34];

The array is like a table with a single row, but multiple columns.

JohnJaneJackJill

How to access array elements with the indexer

To access an array element (a single value in the array), we use the indexer.

When we create an array, each value is assigned to a corresponding number, its index. If we think about an array as a table, we would add another row with numbers, starting at 0.

0123
JohnJaneJackJill

These numbers form the index. When we want to access a specific element, we provide the compiler with that element’s corresponding index number.

It’s important to note that any collection with a numerical index, will always start at 0, not at 1.

To use the indexer, we simply add the index number between square brackets, after the array name.

Syntax:
 array_name[2];
Example:
var employee : string[] = ["John", "Jane", "Jack", "Jill"];

console.log( employee[2] );

In the example above, we access element number 2 in the array. Because the index starts at 0, it prints the third element ‘Jack’ to the console.

How to access array elements with a loop

Arrays typically have many values and so it makes more sense to access its values within a loop.

To use an array inside a loop, we have to use a counter as the index. Let’s see an example with a while loop, then break it down.

Example:
var employee : string[] = ["John", "Jane", "Jack", "Jill"];
var i : number = 0;

while(employee[i]) {

  console.log(employee[i]);
  i++;
}

We’ll use the variable i as the counter. We start by assigning the value 0 to the counter, because arrays start at 0.

Then, in the body of the while loop, we increment the counter by 1. This means we would start at the first element of the array, element 0, and continue to 1, 2, 3 etc. as the loop runs.

The while loop is nice for an array because we can just increment the counter in the condition. When the loop sees that there are no more elements in the array, the condition becomes false and the loop stops.

In a for loop, we would have to specify the amount of elements in the array explicitly.

Example:
var employee : string[] = ["John", "Jane", "Jack", "Jill"];

for(var i:number = 0; i < 4; i++) {

  console.log(employee[i]);
}

The problem with the for loop is that we may not know how many elements there are in an array beforehand.

Luckily, TypeScript provides us with the built-in array.length property that figures it out for us. To use the property, we simply write the array name, followed by a dot operator and the keyword length .

Syntax:
var name : type[] = [value1, value2, ...];

// Get the amount of
// elements in 'name'
// arrray
name.length;
Example:
var employee : string[] = ["John", "Jane", "Jack", "Jill"];

console.log("There are", employee.length, "employees");

Now all we need to do is use the length property in the condition of the for loop.

Example:
var employee : string[] = ["John", "Jane", "Jack", "Jill"];

for(var i:number = 0; i < employee.length; i++) {

  console.log(employee[i]);
}

The for loop is a safer option than the while loop because it’s guaranteed to loop only the amount of times there are elements in the loop.

How to change array elements

Changing array elements is simple, we use the indexer to specify the element and assign a new value to it with the assignment operator.

Syntax:
 name[index] = new_value;
Example:
var employee = ["John", "Jane", "Jack", "Jill"];

console.log(employee[0]);

// mutate element
employee[0] = "John Doe";

console.log(employee[0]);

In the example above, we change the name in the first array element from “John” to “John Doe”. The compiler overwrites the previous value with the new one we provide.

How to add array elements

To add elements to an array, we use the built-in array.push() function. It will push a value onto the end of the array.

To push an element, we write the array name, followed by a dot operator and the push function. Then, we specify the value we want to add as an argument.

Syntax:
 name.push(value_to_add);
Example:
var film_list = [

  "The Godfather",
  "Star Wars: Episode V",
  "The Dark Knight",
  "Pulp Fiction"
];

// push element into array
film_list.push("Back to the future");

// print array to page
console.log("Best movies of all time:");
for (var i:number = 0; i < film_list.length; i++) {

  console.log(film_list[i]);
}

In the example above, we push a single value into a new element at the end of the array.

We can push more than one element into the array by separating the values we want to push with a comma. The values will be added in the same order we specify.

Syntax:
 name.push(value1, value2, ...);
Example:
var film_list = [

  "The Godfather",
  "Star Wars: Episode V",
  "The Dark Knight",
  "Pulp Fiction",
  "Back to the future"
];

// push multiple elements into array
film_list.push("Alien", "Fight Club", "Die Hard", "Jarassic Park", "Inception");

// print array to page
console.log("Best movies of all time:");
for (var i:number = 0; i < film_list.length; i++) {

  console.log(film_list[i]);
}

In the example above, we add 5 more elements to the array.

When we look at the list printed in the console, we can see that the elements were added in the same order we specified in the code.

Output:
Best movies of all time:
The Godfather
Star Wars: Episode V
The Dark Knight
Pulp Fiction
Back to the future
Alien
Fight Club
Die Hard
Jarassic Park
Inception

How to remove array elements

TypeScript provides us with three functions to remove elements from an array, depending on where the element is.

  • pop() removes an element from the end of the array.
  • shift() removes an element from the start of the array.
  • splice() removes an element at a specific index.

To remove an element from the end of an array, we use the array.pop() function without any arguments.

Example:
var employee : string[] = ["John", "Jane", "Jack", "Jill"];

// remove element from
// the end of the array
employee.pop();

for (var i:number = 0; i < employee.length; i++) {

  console.log(employee[i]);
}

An added benefit is that the pop() function will return the value of the element which it just removed.

Example:
var employee : string[] = ["John", "Jane", "Jack", "Jill"];

// remove element from
// the end of the array
// and print to the page
console.log( employee.pop() );

This is useful if you want to do something with the value before completely discarding it.

To remove an element from the start of an array, we use the array.shift() function, without any arguments.

It will work exactly the same as the pop() function, except for removing the element at the start instead of the end. It will also return the value that it removed.

Example:
var employee : string[] = ["John", "Jane", "Jack", "Jill"];

// remove element from
// the start of the array
// and print to the page
console.log( employee.shift() );

If we want to remove an element at a specific index, or multiple elements, we use the array.splice() function.

This time, the function needs two arguments. The first argument specifies the index at which to begin removing elements. The second argument specifies the number of elements to remove.

Syntax:
 name.splice(index, num_elements_to_remove);
Example:
var employee : string[] = ["John", "Jane", "Jack", "Jill"];

// remove element from
// the start of the array
// and print to the page
console.log( employee.splice(2, 1) );

In the example above, we remove the element at index number 2, “Jack”. The array.splice() function also returns the element(s) it removed.

How to create an array instance

Because an array is an object, we can create a new array by instantiating it with either the new keyword, or the array constructor.

Syntax:
 var name = new Array();

We populate the array by assigning values to indeces.

Example:
var employee : string[] = new Array();

employee[0] = "John";
employee[1] = "Jane";
employee[2] = "Jack";
employee[3] = "Jill";

If we know the values beforehand, it’s easier to initialize the array instance by using the array constructor.

We add the values we want to populate the array with as arguments of the Array() function.

Syntax:
 var name = new Array(value1, value2, ...);
Example:
 var employee : string[] = new Array("John", "Jane", "Jack", "Jill");

Many developers feel that the extra typing is unnecessary and prefer to initialize an array with square brackets instead.

List of array object methods

Because an array is an object, TypeScript provides us with functions to perform array specific operations.

The following is a list of popular array methods.

FunctionDescription
concat()Merge two or more arrays and return the new array.
copywithin()Copy part of an array and return the new modified array.
every()Determine whether all elements in an array satisfy specific function conditions.
fill()Fill an array, or part of an array, with a single value.
filter()Return an array with the elements that satisfy specific function conditions.
find()Find the first occurance of a value in the array and return its value.
findIndex()Find the first occurance of a value in the array and return its index.
forEach()Calls a function for each element in the array.
includes()Checks if an array contains a specific element.
indexOf()Find the first occurance of a value in the array and return its index.
join()Join the elements of an array as a string.
lastIndexOf()Find the last occurance of a value in the array and return its index.
map()Calls a function for every array element and return the new array.
pop()Removes the last element of an array and return it.
push()Adds one or more elements to the end of an array.
reverse()Reverse the elements of an array.
shift()Removes the first element of an array and return it.
slice()Copy part of an array and return the new array.
sort()Return elements of an array in a specific sorted order.
splice()Adds or removes elements at a specific position in an array.
unshift()Add one or more elements to the start of an array.

Summary: Points to remember

  • An array is a data container that can store more than one value in a single container.
  • We initialize an array literal by providing it with multiple, comma separated values between square brackets.
  • We instantiate an array with the new Array() constructor.
  • We access array elements with their corresponding index number between square brackets.
  • When we access elements in a loop, we need to provide a counter to move through the elements in the array.
  • A for loop is a safer option than a while loop because it’s guaranteed to run only the length of the array.
  • To change the value of a single element, we assign a new value to it.
  • TypeScript provides us with many array specific methods to add, remove, copy, find elements etc. when working with arrays.