Fetching JSON:

I like the fetch() function because, for me, it is what crystallized the concepts of data flow, parameters, and the implicit and explicit passing of data into callback functions. Fetch() is also important because it was the first thing that provided me with any context of how modern single page websites work efficiently.

Fetch() is a technique in AJAX development which stands for ‘Asynchronous JavaScript and XML’, a technique that allows front-end developers (those who focus on the client-side) to render a website with HTML and CSS immediately. AJAX allows allows web developers to build dynamic websites that are fast while constantly providing updates of data on the DOM. AJAX decouples the data retrieval from loading the content on the DOM.

Below is an example of a fetch() function which takes in a data source- here represented here by the variable ‘URL’. In commercial applications the fetch request is made to an API which allows developers to link their applications to other applications.

Once the fetch() request goes out and gets the data it returns a ‘promise’, which contains the response from the data source- here represented by the variable ‘res’.

We then run a .json() function on that response, which returns the data (typically structured in a ‘string-ified’ JSON format) and turns it into a parsable data structure. Only once the promise has delivered the usable data can we then (second .then()) run an operation on that data to manipulate the DOM, which in our example prints the data to the DOM’s console.

JSON is a data structure that is commonly used to send a data across the internet. However, the .json() function is not the only function that can be applied to the data source. We can run .text() which will return the data in text format. Other functions we can run on the data include:

Another interesting aspect of fetch() is how the promises are passed throughout the entire fetch() function implicitly. The example above shows the data being passed explicitly into the second .then function, but we could have just as easily written:

Studying the fetch() function has been an important part of my learning JS.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store