What is a formData Object in JavaScript?

In JavaScript, a FormData object is a common way to create a bundle of data to send to the server using XMLHttpRequest or fetch.

It replicates the functionality of the HTMLHyperText Markup Language form element.

We can think of it as an array of arrays. There is one array for each element that we want to send to the server.

Each element consists of the following three things:

  • name: The name of the field.

  • value: The value of the field. It can be a String or Bloba file-like object of immutable, raw data.

  • filename: The file’s name to be saved on the server when a Blob is passed as the second parameter.

Syntax


const formData = new FormData([form]);

Parameter

The formData constructor creates and returns a new FormData object.

If an HTML form element is provided, it automatically captures its fields. This parameter is optional.

Additional data can be added in the FormData object using the formData.append() method.


formData.append(name, value, filename);

Code

1. FormData object with an HTML form

Console

Explanation

We have created an HTML form that has two input fields for name and age respectively. Then we have created an onSubmit function of this form.

In that function, we pass the id of the form element to the FormData constructor. It returns an object consisting of the data filled in the HTML form as name-value pairs.

2. FormData object without an HTML form.

Console

Explanation

We created a FormData object using an empty FormData constructor. Then, we added some data in the form of name-value pairs using the append() method.

A FormData object is simply an array-like iterable structure that holds many name-value pairs or potentially an HTML form.