Introduction to APIs

A brief overview of APIs as they relate to JavaScript data structures.

Throughout the following exercises, we are going to create and implement various data structures in JavaScript. As a reminder, a data structure is a way to store information, with each one having different pros and cons. A data structure that you are already familiar with is an array. Instead of having seven variables for each day of the week:

const Sunday; const Monday; const Saturday;

we can have one array that stores all of them:

const daysOfWeek = [Sunday, Monday, …, Saturday];

This is beneficial as it’s more concise, and also links the related variables.

What is an API?

Arrays also have an API, or an application programming interface. An API allows you to access properties and methods of data structures easily and without needing to do the “behind the scenes” work yourself. For example, if you want to find the length of an array, you don’t need to loop through the entire array yourself counting how many elements there are. Instead, you can just call myArray.length which will return the internal length property of the array. This makes your code simpler, more readable, and safer.

Being able to call the .length property of the array also makes it easier for someone who is not familiar with how arrays work to be able to use the array data structure. The .push() method is another example of the array API. Instead of looping through the entire array and manually adding a new element to the end of the array, you can simply call myArray.push(newElement). You don’t need to worry about accidentally adding the element to the wrong part of the array as you can rely on the .push() method to add the element accurately, which makes your code safer.

Creating Your Own APIs

You will be creating your own data structures in the coming exercises, which means you will be creating your own APIs again. Each internal property and method that your data structure has is part of the API. Some of your data structures will be built using arrays or other data structures you have already created, meaning that you will also be using the past APIs as you go.

Other Uses for APIs

APIs are also used to help applications communicate with each other, and are especially prevalent in web programming.