ThatJsDev

🤯 5 Things You Didn't Know Javascript Could Do!

This post exposes a few Javascript hidden gems that many developers are unaware of. Hopefully, this would save some of your development/debugging time.

Get or set query arguments in a URL

// url.searchParam
let url = new URL("https://thatjs.dev/?q=Learn%20Javascript&page=2");
let query = url.searchParams.get("q"); // is the string "Learn Javascript"
let query = url.searchParams.get("page"); // is the number 2

url.searchParams.set("page",3);
// url.href = https://thatjs.dev/?q=Learn%20Javascript&page=3

I guess we need same for cookies 🙄

Super useful API which gives us localized formatting of relative times (e.g. "yesterday", “3 seconds ago", "in 2 weeks"

// Intl.RelativeTimeFormat 

const rtf = new Intl.RelativeTimeFormat("en");

rtf.format(3.14, "second");
// → "in 3.14 seconds"

rtf.format(-15, "minute");
// → "15 minutes ago"

const rtf = new Intl.RelativeTimeFormat("es");

rtf.format(3.14, "second");
// → "dentro de 3,14 segundos"

rtf.format(-15, "minute");
// → "hace 15 minutos"
// Available in Chrome for Android, iOS Safari & Safari

if (navigator.share) {
 navigator.share({
   title: "thatjs.dev",
   text: "Accessibility tips for web development",
   url: "https://thatjs.dev/hidden-gems-of-javascript"
 }).then(() => console.log("Successful share"))
   .catch((error) => console.error(error)) //Error 
}

// -- //

DevTools Console API for querying heap objects

// queryObjects(Constructor) in Chrome dev tools console gets all objects of a given constructor or class 

const storeThis = [];

class Movie {
    constructor (name) {
        this.name = name;
    }
    myReview() {
        console.log(`${this.name} was awesome!`);
    }
}
storeThis.push(new Movie("Toy Story 4"));
storeThis.push(new Movie("Star Wars"));

queryObjects(Movie) 
/** Array(2)
    0: Movie {name: "Toy Story 4"}
    1: Movie {name: "Star Wars"}
**/

Storage for the web

// A new guide to your options for storing data in the browser & checking quotas
if (navigator.storage.estimate) {
    const quota = await navigator.storage.estimate();
    // quota.usage -> Number of bytes used.
    // quota.quota -> Maximum number of bytes available.
    const percentageUsed = (quota.usage/quota.quota) * 100;
    console.log(` You've used ${percentageUsed}% of the available storage.`);
    const remaining = quota.quota - quota.used;
    console.log(` You can write up to ${remaining} more bytes.`);
}

---

Subscribe

Get access to exclusive updates.

---

Bookmark

Unlike life, keyboards do have shortcuts, press COMMAND+D to make this an easily accessible resource by bookmarking it.