Be careful inside try-catch blocks in Javascript async functions. If you don't use await, an error that's thrown might not stop the execution of subsequent code.

Read more

The innerText property magically converts newline characters to <br> elements. If you want to just set the text content of an element, you should use, well, textContent.

Apparently, the difference is that "innerText is aware of the rendered appearance of the text, while textContent is not."

Read more

You can use a Sinon.JS stub with the (callsFake())[] method, passing it an existing function, to effectively "wrap" the function so that it registers each time you call and with which arguments, but in a way that it also seemingly works the same way as the original function does.

Read more

You can send data with the application/x-www-form-urlencoded content type (the one that encodes values similar to a query string, e.g. first=1&second=2) using a URLSearchParams object, like so:

fetch(url, {
  method: "POST",
  body: new URLSearchParams({first: 1, second: 2})
Read more

There's an API in Chrome and Firefox (that I know of) that lets you get localized strings with variable replacements from a JSON file that you provide.

var message = browser.i18n.getMessage("messageContent", target.url);
Read more

Arrays can be copied using spread syntax, introduced in ES6. To illustrate:

let a = [1, 2, 3];

// This won't work.
let b = a;
b[0] = 99;
console.log(a[0], b[0]); // prints "99 99"

// But this will.
let c = [...a]; // before ES6 there was an even uglier way of doing this using "slice", but let's never talk about that
c[0] = 12345;
console.log(a[0], c[0]); // prints "99 12345"
Read more

There are different types of functions in modern-ish JavaScript: regular, async, and generator functions. However, typeof returns "function" for all of them. One way (the only?) to differentiate between them is by using

Read more

Due to a bug in the original C code for the implementation of Javascript, this awesome thing happens:

const a = null;
console.log(typeof a); // prints "object"
Read more

Here's yet another one of Javascript's endless oddities: the switch statement uses strict comparison (think === instead of ==).

Read more
Subscribe to Javascript