Working with URLs in JavaScript can be a pain. Collecting the form data too? However, JavaScript constructors for data handling make these tasks much easier. Let’s examine these built-in constructors that make handling complex data structures more manageable. Let’s check some of the most useful ones.
Wait, what’s a constructor?
A constructor in JavaScript is a special function that creates and initializes an object. When we use new URL()
, we’re telling JavaScript to create a new URL object with all its built-in properties and methods ready to use. We can use all those predefined properties out of the box.
URL and URLSearchParams: The Dynamic Duo
The URL constructor helps you pull apart any web address into its pieces:
const myUrl = new URL('https://spotify.com/playlist?mood=happy&genre=pop');
// Easy access to URL parts
console.log(myUrl.hostname); // "spotify.com"
console.log(myUrl.pathname); // "/playlist"
Note, that not only hostname and pathname exist as properties, there are many other useful ones such as protocol, host, origin, search, port, searchParams, hash, check them all out here: https://developer.mozilla.org/en-US/docs/Web/API/URL/hash
URLSearchParams handles everything after the question mark (?) in your URL – this is perfect for working with search filters or query parameters:
// Working with URL parameters
const params = new URLSearchParams('mood=happy&genre=pop');
params.append('tempo', 'upbeat'); // Add a new parameter
console.log(params.get('mood')); // "happy"
Imagine if you were dealing only with strings, you wouldn’t have all this available.
FormData Constructor: Form Handling Made Easy
FormData packages all your form information. It’s super helpful when handling things like contact forms or file uploads.
// The sign-up form
const signupForm = document.querySelector('#signup-form');
// FormData can automatically collect all form fields
const formData = new FormData(signupForm);
// Need to add something extra? No problem!
formData.append('joinDate', new Date().toISOString());
// Send it to your server
fetch('/api/signup', {
method: 'POST',
body: formData
});
The cool thing about FormData is that it handles all types of form fields (text, files, checkboxes – you name it). It automatically collects the full data from the form fields, it saves time!
Text Encoding Constructors
The TextEncoder and TextDecoder are part of the Encoding API.
TextEncoder converts text to binary, it packs your message into a format that safely travels anywhere on the web in a universal format that any computer can understand, while TextDecoder converts the binary to text, the opposite, so it unwraps it back into readable text.
// Let's say you're building a multilingual comment system
const encoder = new TextEncoder();
const comment = encoder.encode('Welcome to Madrid! Bienvenidos a Madrid!'); // you can pass here whatever, such as chinese letters 你好 or even emojis
// Later, when you need to display the comment
const decoder = new TextDecoder();
const displayText = decoder.decode(comment);
console.log(displayText); // "Welcome to Madrid! Bienvenidos a Madrid!"
We can practically use them as a pair of translators that help when you’re building international websites or handling user comments in different languages, they ensure everything arrives exactly as intended.
Most modern browsers support these constructors natively so you are safe to go.
These JavaScript constructors for data handling simplify common tasks and help you handle URLs, process form data, and manage text encoding with minimal code, use them only when they fit your needs, sometimes simpler solutions work just fine!
Learn more:
- Another related article I wrote: https://front-end.tips/mastering-intl-listformat-javascript-format-lists-with-ease/