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())[https://sinonjs.org/releases/latest/stubs/#stubcallsfakefakefunction] 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);
console.log(message);
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 toString.call(myFunc).

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

There's a bunch of Web APIs that are pretty usable today:

  1. Detect page visibility
  2. Detect online state
  3. Vibration
  4. Detect orientation

...and more! clipboard, ambient light detection, battery status, etc.

Read more
Subscribe to Javascript