Async looping

Imagine you want to run a loop of async requests.. here is a useful snippet that saves the day! You can use for..of loop with async await.

async function processItems(items) {
  for (const item of items) {
    await processItem(item);
  }
}

Query Params

Parsing the URL, and trying to manage the query params is a tedious task you say? We now have URLSearchParams to automatically manage this as shown below. By the way, you can also update it, and see the url href value getting updated seen in couple of snippets below.

const url = new URL("https://example.com?name=Alice&age=30");
const params = new URLSearchParams(url.search);
const age = params.get("age");

Custom array from

We all know Array.from can create an array out of an iterable. But do you also know it can take an optional function, that can modify what would be the value for the output array? Check this out

const str = "123";
const nums1 = Array.from(str); // ['1', '2', '3']

// modify while creating array
const nums2 = Array.from(str, (num) => num * num); // [2, 4, 6]

Array of items

This is one of strange utility methods but not sure if it’s quite useful to us in our day to day tasks. Nevertheless, thought of sharing as it felt unique.

const arr = Array.of(1, 2, 3, 4);

Using Symbols for inaccessible/ hidden / private properties

If you wanted to create some private properties that are hidden from enumeration, here is a simple trick to store some important info into JavaScript objects using Symbols. By the way, each symbol value, even though you used same input string is unique and different from each other. So people cannot get a hold of existing one.

const sym = Symbol("secretkey");
const obj = { [sym]: "secretval" };

Manipulating URLs

Like previously mentioned, using search params object makes life easier around URLs and query params. Updating the js object automatically updates the url href value too.

const url = new URL("https://sample.com/path?k1=v1");
url.searchParams.set("k2", "v2");
console.log(url.href);

Will share some more, as I keep learning! Have fun!