JavaScript
The programming language that runs on Web pages. Designed by Brendan Eich in ten days in 1995 for writing simple scripts for the Web. Over the course of the early 21st century it rose from its benighted origins to become a decently respectable language, though it has not been able to shed all of its historical baggage.
Modern browsers accelerate JavaScript with just-in-time compilation (e.g., V8 for Chrome), which makes it significantly faster than Python.
Cheatsheet
Variadic function
function (...args) {
// ...
}
Clone an object
// 2022 or later
structuredClone(obj)
Number of keys in an object
Object.keys(obj).length
URL query params
const params = new URLSearchParams(window.location.search);
if (params.get("whatever") != null) {
// ...
}
Spread syntax
[1, 2, 3, ...theRest]
Sorting
// sort numbers ascending
array.sort((a, b) => a - b);
// sort strings ascending
array.sort((a, b) => {
if (a < b) {
return -1;
}
if (a > b) {
return 1;
}
return 0;
});
Maps
const map = new Map();
map.set(key, value);
map.get(value); // undefined if not found
const entries = Array.from(map.entries());
Datetime
const today = new Date();
const yesterday = new Date(today);
yesterday.setDate(yesterday.getDate() - 1);
// WARNING: toISOString() converts from local time to UTC
function iso8601(d) {
const mm = (d.getMonth() + 1 + "").padStart(2, "0");
const dd = (d.getDate() + "").padStart(2, "0");
return `${d.getFullYear()}-${mm}-${dd}`;
}
Check object type
if (typeof x === 'string') {
// ...
}
Regex
See: regex
See also
- Mithril.js – my favorite JS front-end framework