Skip to content
jshacks.dev
Fundamentals

The Complete Guide to Modern JavaScript for Developers

A complete guide to modern JavaScript on Node.js 24: the syntax, types, functions, classes, modules, async code and tools a working developer uses, with output.

30 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, Node.js and npm logos.

Modern JavaScript is the language as it exists in ES2025 and ES2026, running on a current engine, written as ES modules, and tested with the tools that ship in Node.js. It is a different language from the one in a ten-year-old tutorial: var and callbacks have given way to const, modules and async functions, and a long list of small built-in methods has replaced the helper functions that every project used to carry. This guide is the map of that language. Each section shows the feature in code with the exact output, says when to use it and when not to, and links to the post that goes deeper. The examples run on Node.js 24, which embeds V8 13.6, and they are written as .mjs files or as a project with "type": "module" in its package.json.

You do not need to read it in order. Read the sections whose names you cannot explain, skim the ones you can, and use the links at the end of each section for the topic you are about to work with. If you are starting from nothing, the learning roadmap gives a sequence with exercises, and this page is the reference to keep open beside it.

What modern means

"Modern" is easy to define in practical terms: it is the code you would write today if no compatibility with the past were needed. The language is versioned by year. Each June, Ecma International publishes a new edition of ECMA-262 containing the proposals that reached stage 4 in the TC39 process, and engines usually ship a feature well before the edition is final. How a proposal becomes JavaScript describes the stages. For a working developer the edition number matters less than two facts: which features your runtime supports, and which of them you can rely on in the places your code runs.

On a server the answer is simple, because you choose the runtime. Node.js 24 is the current long-term support line from October 2025, and it supports the whole of ES2025 and part of ES2026, such as Array.fromAsync and Error.isError. In a browser you depend on your audience's browsers, and a feature that is supported in current Chrome, Firefox and Safari is safe for most sites. The sections below mark the features that are newer than that baseline.

EditionFeatures a working developer meets every day
ES2015let, const, arrow functions, classes, template literals, destructuring, modules, promises, Map, Set, symbols, iterators
ES2017async and await, Object.entries, padStart
ES2018Object spread and rest, async iteration, named capture groups
ES2019flat, flatMap, Object.fromEntries, optional catch binding
ES2020?., ??, BigInt, dynamic import(), globalThis, Promise.allSettled
ES2021replaceAll, the logical assignment operators, numeric separators, Promise.any
ES2022Class fields and private # members, static blocks, top-level await, at(), Object.hasOwn, error cause
ES2023toSorted, toReversed, toSpliced, with, findLast
ES2024Object.groupBy, Promise.withResolvers, resizable ArrayBuffer, isWellFormed
ES2025Iterator helpers, Set methods such as union, Promise.try, RegExp.escape, JSON modules with import attributes
ES2026Array.fromAsync, Error.isError, Math.sumPrecise, base64 for Uint8Array, Iterator.concat, Map getOrInsert

The table is a selection and is not the specification, and the three edition posts have the full lists: ES2024, ES2025 and ES2026. The next edition, ES2027, is expected to bring Temporal and explicit resource management, covered in what is coming in ES2027.

Values and types

JavaScript has seven primitive types, undefined, null, boolean, number, string, bigint and symbol, and one non-primitive type, the object, which includes arrays, functions, dates and everything else. The typeof operator reports the type as a string, with one famous mistake.

JavaScript
console.log(
  typeof 42,
  typeof 42n,
  typeof "42",
  typeof true,
  typeof undefined,
  typeof null,
  typeof Symbol("id"),
  typeof {},
  typeof (() => {}),
);
Text
number bigint string boolean undefined object symbol object function

typeof null is "object", a bug from the first version of the language that cannot be fixed without breaking existing code, so test for null with value === null. [The post on typeof](/library/typeof-works-including-typeof-null-bug) lists every case, and the seven primitive types covers what each holds.

Two ideas separate primitives from objects. A primitive is immutable and compared by value, so "a" === "a". An object is compared by identity, so {} === {} is false, and assigning an object to another variable copies the reference, not the object. Most bugs about "my data changed somewhere else" come from forgetting the second rule, which primitives versus objects explains.

Numbers

A number is a 64-bit IEEE 754 double. There is no separate integer type, so 1 and 1.0 are the same value, and the decimal fractions that cannot be written exactly in binary carry a small error.

JavaScript
console.log(0.1 + 0.2);
console.log(0.1 + 0.2 === 0.3);
console.log(Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON);
console.log(Number.MAX_SAFE_INTEGER);
console.log(2 ** 53 === 2 ** 53 + 1);
console.log(9007199254740993n + 1n);
console.log(1_000_000 * 3);
Text
0.30000000000000004
false
true
9007199254740991
true
9007199254740994n
3000000

Compare floating-point results with a tolerance and never with ===. Beyond Number.MAX_SAFE_INTEGER, whole numbers lose exactness, which is where bigint comes in: it holds integers of any size and never mixes silently with number, so 9007199254740993n + 1 throws a TypeError. A _ inside a literal, as in 1_000_000, is only for reading. For money, store the smallest unit as an integer, such as cents, and format for display. The posts on why 0.1 + 0.2 is not 0.3, how doubles work and BigInt go through the details.

Strings and templates

A string is a sequence of UTF-16 code units, which is the cause of most Unicode surprises: length counts units, so characters outside the Basic Multilingual Plane, such as most emoji, count as two.

JavaScript
const label = "emoji 😀";
console.log(label.length, [...label].length);

const user = { name: "Mei", orders: 3 };
console.log(`${user.name} has ${user.orders} order${user.orders === 1 ? "" : "s"}`);

console.log("a-b-c".replaceAll("-", "+"), "7".padStart(3, "0"), "  pad ".trim());
Text
8 7
Mei has 3 orders
a+b+c 007 pad

Template literals, written with backticks, interpolate any expression and can span lines. Spread, [...label], iterates by code point, giving the count a reader would expect for most text, but not for every visible character, since a family emoji is several code points joined together. For that, Intl.Segmenter counts graphemes. See strings are UTF-16 and Unicode in JavaScript. Tagged templates, which call a function with the pieces of a template, are the basis of safe query and HTML builders, covered in template literals and tagged templates.

Truthiness and equality

Conditions convert their value to a boolean. Eight values are falsy: false, 0, -0, 0n, "", null, undefined and NaN. Everything else is truthy, including an empty array and the string "0".

JavaScript
console.log(0 == "", 0 === "", null == undefined, null === undefined);
console.log(NaN === NaN, Object.is(NaN, NaN), Number.isNaN("abc"), isNaN("abc"));
console.log([] ? "truthy" : "falsy", "0" ? "truthy" : "falsy");
Text
true false true false
false true false true
truthy truthy

== converts types before comparing and === does not, so use === everywhere except one idiom, value == null, which is true for both null and undefined. NaN is the one value not equal to itself, so Number.isNaN() is the test, and the global isNaN() converts its argument first and gives true for any text that is not a number. The full rules are in truthy and falsy values, loose equality and type coercion.

Declarations and scope

Use const for every binding that is not reassigned and let for the ones that are. Do not use var. A const binding cannot be reassigned, but the object it points to can still change, which is a point many beginners confuse with immutability.

JavaScript
const settings = { theme: "dark" };
settings.theme = "light";
console.log(settings);

try {
  settings = {};
} catch (error) {
  console.log(error.name + ": " + error.message);
}

for (var i = 0; i < 3; i += 1) {}
for (let j = 0; j < 3; j += 1) {}
console.log(i, typeof j);
Text
{ theme: 'light' }
TypeError: Assignment to constant variable.
3 undefined

var is scoped to the function and leaks out of blocks, so i is still readable after its loop, while let and const are scoped to the block, so j does not exist outside it. let and const also exist from the start of their block but cannot be read before the line that declares them, a stretch called the temporal dead zone, and the error it throws is a ReferenceError. var, let and const, block and function scope, hoisting and the temporal dead zone cover the cases. Scope itself is lexical: a function sees the variables of the scope where it was written, which lexical scope and the scope chain explains, and which is the basis for closures later in this guide.

Modules and classes run in strict mode automatically. Classic scripts do not, and a "use strict" directive at the top of a file turns several silent mistakes into errors, such as assigning to an undeclared name. New code in modules never needs the directive, as the post on strict mode explains.

Operators that replaced boilerplate

A small group of operators removes most of the if checks that older code needed. They are worth learning exactly, because two of them look like older operators and behave differently.

JavaScript
const user = { profile: { name: "Mei", address: null }, tags: [] };

console.log(user.profile?.name);
console.log(user.profile?.address?.city);
console.log(user.settings?.theme ?? "light");
console.log(user.tags.length || "no tags");
console.log(user.tags.length ?? "no tags");

const options = { retries: 0, verbose: undefined };
options.retries ||= 3;
options.verbose ??= false;
options.timeout ??= 5000;
console.log(options);
Text
Mei
undefined
light
no tags
0
{ retries: 3, verbose: false, timeout: 5000 }

Optional chaining, ?., stops and gives undefined when the value on its left is null or undefined, and it works for property access, a?.[key] and calls a?.(). Nullish coalescing, ??, supplies a default only for null and undefined, so it keeps 0 and "", which || would replace. That difference is why user.tags.length || "no tags" printed text for an empty array and the ?? line printed 0. Use ?? for defaults and || only when every falsy value really should be replaced. The logical assignment operators ||=, &&= and ??= assign only when the test passes, and they short-circuit, so no write happens otherwise.

Optional chaining belongs where a value may legitimately be missing, such as a field in a response. Where a value must exist, a?.b turns an error you would want to see into a silent undefined, so let it throw. The posts on optional chaining, [?? versus ||](/library/nullish-coalescing-vs-logical-compared-operator) and logical assignment have the details, and operator precedence covers why a ?? b || c is a syntax error.

Destructuring, spread and rest

Destructuring unpacks an array by position or an object by name into variables. Spread expands a value into separate items, and rest, written with the same three dots, collects the remaining items.

JavaScript
const [first, , third = "none", ...others] = ["a", "b", undefined, "d", "e"];
console.log(first, third, others);

const { id, name: label = "unnamed", ...rest } = { id: 7, role: "admin", active: true };
console.log(id, label, rest);

const merged = { ...{ a: 1, b: 2 }, ...{ b: 3, c: 4 } };
console.log(merged);

function describe({ method = "GET", path }, ...flags) {
  return `${method} ${path} [${flags.join(",")}]`;
}
console.log(describe({ path: "/orders" }, "json", "cached"));
Text
a none [ 'd', 'e' ]
7 unnamed { role: 'admin', active: true }
{ a: 1, b: 3, c: 4 }
GET /orders [json,cached]

Defaults apply when a value is undefined, and not for null, so const { a = 1 } = { a: null } gives null. Later spread entries override earlier ones, which is how options objects with defaults are written: spread the defaults first and the caller's options second. Destructuring a value that is null or undefined throws a TypeError, so guard function parameters with a default, as describe does for its second argument. The post on destructuring lists the patterns and spread versus rest separates the two jobs.

Spread copies one level. Nested objects stay shared between the original and the copy, so a change in a nested object shows through both. For an independent copy of everything use structuredClone().

JavaScript
const original = {
  when: new Date("2026-05-06T12:00:00Z"),
  tags: new Set(["a"]),
  nested: { n: 1 },
};

const shallow = { ...original };
const deep = structuredClone(original);

shallow.nested.n = 2;
console.log(original.nested.n, deep.nested.n);
console.log(deep.when instanceof Date, deep.tags.has("a"));
Text
2 1
true true

structuredClone handles dates, maps, sets, typed arrays and circular references, and it throws on functions, which cannot be cloned. See shallow versus deep copy and [structuredClone](/library/structuredclone-deep-copy-built-javascript).

Functions

Functions are values. They can be assigned, passed and returned, and they remember the scope where they were created. Arrow functions are the short form, with two differences from function: they do not have their own this or arguments, and they cannot be called with new.

JavaScript
function createCounter(start = 0, step = 1) {
  let count = start;
  return {
    next: () => (count += step),
    reset() {
      count = start;
    },
  };
}

const counter = createCounter(10, 5);
console.log(counter.next(), counter.next());
counter.reset();
console.log(counter.next());

const sum = (...numbers) => numbers.reduce((total, n) => total + n, 0);
console.log(sum(1, 2, 3, 4));
Text
15 20
15
10

createCounter returns two functions that share the private variable count. That is a closure, and no class is needed to keep state. Default parameters, start = 0, are evaluated at call time and can refer to earlier parameters. Rest parameters collect the extra arguments into a real array, which makes the old arguments object unnecessary. Scope, hoisting and closures: the complete guide covers closures at length, including the loop bug and the cases that hold memory.

this

this is decided by how a function is called, not where it is defined, except in arrow functions, where it is taken from the surrounding code.

JavaScript
const timer = {
  label: "build",
  start() {
    return [1, 2].map((n) => `${this.label}-${n}`);
  },
  broken() {
    return [1].map(function () {
      return typeof this;
    });
  },
};

console.log(timer.start());
console.log(timer.broken());

const detached = timer.start;
try {
  detached();
} catch (error) {
  console.log(error.name);
}
Text
[ 'build-1', 'build-2' ]
[ 'undefined' ]
TypeError

The arrow function inside start reads this from start, which is timer, because the method was called as timer.start(). The regular function inside broken gets its own this, and in a module, which is strict, that is undefined. Pulling the method out into detached loses the receiver, and this.label then throws a TypeError, which is the error behind the "lost this in a callback" bugs. Fix them with an arrow function, bind(), or by not passing the method around. The full rules for each call style are in [how the this keyword works](/library/keyword-works-javascript).

Objects and classes

An object is a bag of properties keyed by strings or symbols, with a link to a prototype object. Object literals have a shorthand for properties and methods, and a computed key syntax for dynamic names.

JavaScript
const key = "status";
const status = "paid";

const order = {
  id: 42,
  status,
  [`${key}Changed`]: true,
  describe() {
    return `order ${this.id} is ${this.status}`;
  },
  get isFinal() {
    return this.status === "paid";
  },
};

console.log(order.describe(), order.isFinal);
console.log(Object.keys(order));
console.log(Object.hasOwn(order, "toString"), "toString" in order);
console.log(Object.entries({ a: 1, b: 2 }).map(([k, v]) => `${k}=${v}`).join("&"));
console.log(Object.fromEntries(new Map([["x", 1], ["y", 2]])));
Text
order 42 is paid true
[ 'id', 'status', 'statusChanged', 'describe', 'isFinal' ]
false true
a=1&b=2
{ x: 1, y: 2 }

Object.hasOwn(obj, key) asks whether the property is the object's own, and the in operator also finds inherited ones, so "toString" in order is true through the prototype chain. Object.entries and Object.fromEntries convert between objects and lists of pairs, which is how you map over the properties of an object. Property order is specified: integer-like keys ascending first, then string keys in insertion order. Objects in JavaScript, computed property names and getters and setters go further, and property descriptors explain the hidden flags that Object.freeze and Object.defineProperty change.

Classes

A class is a function with a prototype and some syntax that enforces good habits. It has fields, private members that the engine protects, accessors, static members and inheritance.

JavaScript
class Account {
  #balance = 0;
  static #opened = 0;

  static {
    Account.currency = "USD";
  }

  constructor(owner) {
    this.owner = owner;
    Account.#opened += 1;
  }

  deposit(amount) {
    if (amount <= 0) throw new RangeError("amount must be positive");
    this.#balance += amount;
    return this;
  }

  get balance() {
    return this.#balance;
  }

  static get opened() {
    return Account.#opened;
  }

  toString() {
    return `${this.owner}: ${this.#balance} ${Account.currency}`;
  }
}

class Savings extends Account {
  addInterest(rate) {
    return this.deposit(Math.round(this.balance * rate));
  }
}

const savings = new Savings("Dara");
savings.deposit(1000).addInterest(0.05);

console.log(String(savings));
console.log(Account.opened);

try {
  savings.deposit(-5);
} catch (error) {
  console.log(error.name, error.message);
}

console.log(Object.keys(savings), savings.balance, "#balance" in savings);
Text
Dara: 1050 USD
1
RangeError amount must be positive
[ 'owner' ] 1050 false

#balance is a private field: only code inside the class body can read it, and it is not a property, so Object.keys does not list it and the in check against the string "#balance" is false. static #opened is a private static counter, and the static { } block runs once when the class is defined, which is the place for setup that needs more than one statement. Savings inherits deposit and uses the balance getter, since a subclass cannot read its parent's private field directly. Returning this from deposit is what allows the chain deposit(1000).addInterest(0.05).

Classes are not a different object system. They are syntax over constructor functions and prototypes, with differences that matter: a class cannot be called without new, its body is strict, and its declaration sits in the temporal dead zone. For code that needs a prototype link without constructors, Object.create() is still there, and composition with plain objects and functions is often simpler than inheritance. The posts on classes as functions, the prototype chain, [__proto__ versus prototype](/library/proto-vs-prototype-vs-object-getprototypeof), private members and static members are the spokes for this section, and the complete guide to prototypes goes through inheritance and its hazards, including prototype pollution.

Collections and iteration

An object is a record with known fields. A Map is a dictionary, and a Set is a collection of unique values. Choose by what you store.

JavaScript
const stock = new Map([
  ["apple", 4],
  ["pear", 0],
]);
stock.set("fig", 9);
console.log([...stock.keys()], stock.get("pear") ?? "missing", stock.has("kiwi"));

const unique = new Set([3, 1, 3, 2, 1]);
console.log(unique, unique.size);

const a = new Set([1, 2, 3]);
const b = new Set([3, 4]);
console.log(a.union(b), a.intersection(b), a.difference(b));
Text
[ 'apple', 'pear', 'fig' ] 0 false
Set(3) { 3, 1, 2 } 3
Set(4) { 1, 2, 3, 4 } Set(1) { 3 } Set(2) { 1, 2 }

A Map accepts any key, keeps insertion order, has a size and does not collide with inherited names like "constructor", which an object used as a dictionary does. A Set removes duplicates in one expression, and the methods union, intersection, difference, isSubsetOf and others came with ES2025 and are available in Node.js 22 and later. Sets and maps against objects and arrays gives the decision rules, and WeakMap and WeakSet cover the collections that do not keep their keys alive.

Array methods

Arrays have grown a large set of methods. The ones that return a new array leave the original alone, and a group added in ES2023 gives non-mutating versions of the old mutating ones.

JavaScript
const orders = [
  { id: 1, status: "paid", total: 40 },
  { id: 2, status: "open", total: 15 },
  { id: 3, status: "paid", total: 50 },
];

console.log(orders.at(-1).id);
console.log(orders.findLast((order) => order.status === "open").id);

const byTotal = orders.toSorted((x, y) => y.total - x.total);
console.log(byTotal.map((order) => order.id), orders.map((order) => order.id));

const grouped = Object.groupBy(orders, (order) => order.status);
console.log(Object.entries(grouped).map(([status, list]) => [status, list.length]));

console.log([1, [2, [3, [4]]]].flat(2));
console.log([1, 2, 3].flatMap((n) => (n === 2 ? [] : [n, n * 10])));
console.log([1, 2, 3].includes(2), [NaN].includes(NaN), [NaN].indexOf(NaN));
Text
3
2
[ 3, 1, 2 ] [ 1, 2, 3 ]
[ [ 'paid', 2 ], [ 'open', 1 ] ]
[ 1, 2, 3, [ 4 ] ]
[ 1, 10, 3, 30 ]
true true -1

at(-1) reads from the end. toSorted returns a sorted copy, where sort() sorts the array itself, and toReversed, toSpliced and with do the same for their older siblings. Object.groupBy returns an object whose prototype is null, and Map.groupBy returns a Map when keys are not strings. flatMap maps and flattens one level, so returning an empty array drops an item. includes finds NaN and indexOf does not, because the two use different equality rules. Each method has a post of its own, starting with [at()](/library/javascript-array-at), [filter()](/library/javascript-array-filter), [find()](/library/javascript-array-find), [flatMap()](/library/javascript-array-flatmap) and [includes()](/library/javascript-array-includes), and the traps are real: fill() shares one object across every slot, forEach ignores await, and filter(Boolean) drops zeros.

Iterators and generators

A for...of loop works on any iterable: an object with a [Symbol.iterator]() method that returns an iterator. Arrays, strings, maps, sets and generators are iterable. A generator function, written function*, produces values lazily, and iterator helpers, new in ES2025, let you transform them without building arrays.

JavaScript
function* naturals() {
  let n = 1;
  while (true) {
    yield n;
    n += 1;
  }
}

const firstEvenSquares = naturals()
  .filter((n) => n % 2 === 0)
  .map((n) => n * n)
  .take(4)
  .toArray();

console.log(firstEvenSquares);

for (const [index, letter] of ["x", "y"].entries()) {
  console.log(index, letter);
}

const ranges = {
  from: 1,
  to: 3,
  *[Symbol.iterator]() {
    for (let n = this.from; n <= this.to; n += 1) yield n;
  },
};
console.log([...ranges]);
Text
[ 4, 16, 36, 64 ]
0 x
1 y
[ 1, 2, 3 ]

naturals() is an infinite sequence, and take(4) ends it, so the chain does four units of work and builds no intermediate arrays. The object ranges is made iterable by defining a generator under Symbol.iterator, after which spread, for...of and Array.from all work on it. Use for...of to loop over values, for...in only for the string keys of an object, and not forEach when you need await, break or return. Iterators and iterables, [for...in versus for...of](/library/vs-vs-foreach) and symbols cover the protocol.

Text, patterns and data formats

Regular expressions, JSON and the Intl formatters handle most of the text a program touches.

JavaScript
const log = "2026-05-06: build ok; 2026-05-07: build failed";
const days = [...log.matchAll(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/g)].map(
  (match) => match.groups.day,
);
console.log(days);

const unsafe = "price (USD) = 5.00";
const pattern = new RegExp(RegExp.escape("(USD)"));
console.log(pattern.test(unsafe));

console.log(JSON.stringify({ a: 1, b: undefined, c: [undefined, 2], d: new Date(0) }));
console.log(JSON.parse('{"n":1,"list":[1,2]}', (key, value) => (key === "n" ? value + 1 : value)));

const money = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
console.log(money.format(7996 / 100));
console.log(new Intl.ListFormat("en", { type: "conjunction" }).format(["pen", "pad", "ink"]));
Text
[ '06', '07' ]
true
{"a":1,"c":[null,2],"d":"1970-01-01T00:00:00.000Z"}
{ n: 2, list: [ 1, 2 ] }
$79.96
pen, pad, and ink

Named groups, written (?<name>...), make a match readable, and matchAll returns every match of a global pattern. RegExp.escape(), added in ES2025, escapes text so that it can be placed inside a pattern, where a dot or a parenthesis would otherwise be syntax. JSON.stringify drops undefined and functions from objects, writes them as null inside arrays, and turns a date into its ISO string through toJSON. The reviver passed to JSON.parse can convert values as the text is read. Intl provides locale-aware formatters for numbers, currencies, dates, lists, plurals and relative times without a dependency. The spokes are regular expressions, JSON and the Intl API.

Dates

Date is the oldest and weakest part of the language: months start at zero, setters mutate, and a date-only string is parsed as UTC while a date-time string is parsed as local time. Temporal is the replacement, expected in ES2027, with separate immutable types for instants, calendar dates, times and zoned date-times. Until it is native everywhere, use Date with ISO strings and UTC getters for instants, keep calendar dates as text, and use the @js-temporal/polyfill package where you need real zone arithmetic. The complete guide to dates and times covers both, the Date pitfalls lists the traps, and getting started with Temporal is the short introduction.

Modules

An ES module is a file with its own scope, and it shares code with export and import. Modules are the standard in Node.js and browsers, and the format for any new project. Node.js treats a .mjs file, or any .js file in a package whose package.json has "type": "module", as an ES module.

JavaScript
// src/pricing.js
export const TAX_RATE = 0.2;

export function withTax(net) {
  return Math.round(net * (1 + TAX_RATE));
}

export default function describe() {
  return "pricing module";
}

A config.json file next to it holds { "name": "shop" }, and the entry point imports both files.

JavaScript
// src/main.js
import describe, { withTax } from "./pricing.js";
import config from "./config.json" with { type: "json" };

console.log(describe(), withTax(100), config.name);

const { TAX_RATE } = await import("./pricing.js");
console.log(TAX_RATE);

console.log(import.meta.dirname.endsWith("src"));
Text
pricing module 120 shop
0.2
true

Imports are live read-only bindings to the exporting module's variables, so a later change inside the exporter is visible to importers. A relative import in Node.js needs the full file name with its extension, ./pricing.js. A JSON file is imported with an import attribute, with { type: "json" }, which makes the loader treat it as JSON, and the attribute is required in Node.js. Top-level await is allowed in a module, so the import() call above needs no wrapper function, and import() is the way to load a module lazily, conditionally or by a computed name. import.meta.dirname and import.meta.filename replace the CommonJS __dirname and __filename from Node.js 20.11.

A module is evaluated once, and every importer gets the same instance, so a module is a natural singleton. Circular imports work when the code only uses the imported names after both modules have finished evaluating, and they fail with a ReferenceError when a module reads a name that is not yet initialized. ES modules explained, [dynamic import() and top-level await](/library/dynamic-import-top-level-await) and import attributes have the details. The older CommonJS format, require() and module.exports, still works and a large body of packages still ships it, and since Node.js 22.12 a CommonJS file can require() an ES module that has no top-level await, which has made mixed projects far easier.

Asynchronous code

Most JavaScript waits on something: a file, a request, a timer. A promise is the object that stands for a result that has not arrived yet, and async and await are the syntax for writing code that waits as if it were sequential. The mechanism underneath is the event loop, and how JavaScript actually runs explains the engine, the call stack, microtasks and the loop's phases, which is the right companion to this section.

JavaScript
import { setTimeout as sleep } from "node:timers/promises";

const wait = (ms, value) => new Promise((resolve) => setTimeout(resolve, ms, value));

const settled = await Promise.allSettled([
  wait(20, "a"),
  Promise.reject(new Error("down")),
  wait(10, "c"),
]);
console.log(settled.map((result) => result.status));

console.log(await Promise.any([wait(30, "slow"), wait(5, "fast")]));

const { promise, resolve } = Promise.withResolvers();
setTimeout(resolve, 5, "released");
console.log(await promise);

console.log(await Promise.try(() => JSON.parse('{"ok":true}')));

const controller = new AbortController();
setTimeout(() => controller.abort(), 10);

try {
  await sleep(1000, "late", { signal: controller.signal });
} catch (error) {
  console.log(error.name, error.message);
}
Text
[ 'fulfilled', 'rejected', 'fulfilled' ]
fast
released
{ ok: true }
AbortError The operation was aborted

The four combinators answer four questions. Promise.all succeeds when everything succeeds and rejects at the first failure. Promise.allSettled waits for everything and reports each outcome, as the status list shows. Promise.any takes the first success and ignores failures unless all fail. Promise.race takes whichever settles first, success or failure. Promise.withResolvers() returns a promise with its resolve and reject functions, which removes the outer variables people used to declare for an event that will settle a promise later. Promise.try() runs a function that may throw synchronously or return a promise and gives a promise either way.

An AbortController produces a signal, and aborting it makes the pending sleep from node:timers/promises reject with an AbortError. The same signal can be passed to fetch and to many Node.js APIs for cancellation, and AbortSignal.timeout(ms) builds a signal that aborts by itself after a delay, which suits a request. Pass one into any operation that can take unbounded time.

async and await in practice

An async function returns a promise. await pauses it until a promise settles and returns the result, or throws the rejection, so try and catch work as they do in synchronous code.

JavaScript
async function fetchOrder(id) {
  if (id < 0) throw new RangeError("id must not be negative");
  await new Promise((resolve) => setTimeout(resolve, 5));
  return { id, total: id * 10 };
}

try {
  const one = await fetchOrder(1);
  console.log(one);
  await fetchOrder(-1);
} catch (error) {
  console.log(error.name);
}

const started = [fetchOrder(2), fetchOrder(3), fetchOrder(4)];
const orders = await Promise.all(started);
console.log(orders.map((order) => order.total));

async function* pages() {
  for (const n of [1, 2, 3]) {
    await new Promise((resolve) => setTimeout(resolve, 1));
    yield [n, n * 2];
  }
}

for await (const [n, doubled] of pages()) {
  console.log(n, doubled);
}

console.log(await Array.fromAsync(pages(), ([n]) => n));
Text
{ id: 1, total: 10 }
RangeError
[ 20, 30, 40 ]
1 2
2 4
3 6
[ 1, 2, 3 ]

Awaiting in a loop runs the calls one after another, and starting them first and awaiting Promise.all, as in the started line, runs them concurrently. Choose by dependence: sequential when each call needs the previous result or you must limit the load, concurrent when the calls are independent. Async generators, async function*, produce values over time and are consumed with for await...of. Array.fromAsync collects an async iterable into an array and is part of ES2026. A frequent defect is a forgotten await, which returns a pending promise where code expects a value, and a lint rule for floating promises catches it.

Callback-style APIs, such as the older functions in node:fs, are wrapped with util.promisify, or you use the promise versions in node:fs/promises. fetch is built into Node.js and returns a promise for the response, and a non-2xx status does not reject, so check response.ok.

Errors

JavaScript signals failure by throwing, and any value can be thrown, though only Error objects carry a stack trace. A custom error class gives callers something to test with instanceof, and the cause option keeps the original failure when a lower-level error is wrapped.

JavaScript
class ConfigError extends Error {
  constructor(message, options) {
    super(message, options);
    this.name = "ConfigError";
  }
}

function loadConfig(text) {
  try {
    return JSON.parse(text);
  } catch (cause) {
    throw new ConfigError("invalid config file", { cause });
  }
}

try {
  loadConfig("{oops");
} catch (error) {
  console.log(error.name, error.message);
  console.log(error.cause.name);
  console.log(error instanceof ConfigError, Error.isError(error));
}

try {
  throw "just a string";
} catch (value) {
  console.log(typeof value, value instanceof Error);
}
Text
ConfigError invalid config file
SyntaxError
true true
string false

try runs code, catch handles what it throws and finally runs afterward, even after a return. Error.isError(), from ES2026, tells real errors from lookalikes even across realms, where instanceof Error fails for an error created in another iframe or worker. Throw Error objects, never strings, so that every handler has a message and a stack. Catch only what you can handle, and let the rest propagate to a boundary that logs it. Error handling with try, catch and finally and [custom error classes and cause](/library/custom-error-classes-error-cause) are the two spokes.

Cleanup with using

Releasing a resource, such as a file handle or a lock, used to need try and finally around every use. The using declaration, from the explicit resource management proposal that Node.js 24 already runs, calls the resource's [Symbol.dispose]() method when the block exits, by finishing, return or an exception, and it disposes in reverse order.

JavaScript
class Connection {
  constructor(name) {
    this.name = name;
    console.log(`open ${name}`);
  }

  [Symbol.dispose]() {
    console.log(`close ${this.name}`);
  }
}

function run() {
  using first = new Connection("a");
  using second = new Connection("b");
  console.log("working");
}

run();
Text
open a
open b
working
close b
close a

await using does the same with [Symbol.asyncDispose]() for resources that close asynchronously. Safari has not shipped the syntax, so browser code needs a transpiler for now, and server code on Node.js 24 can use it directly. The full treatment is in explicit resource management.

Metaprogramming, carefully

Three features let code inspect and change how objects behave. Symbols are unique keys, used by the language for protocols such as Symbol.iterator. Property descriptors control whether a property is writable, enumerable and configurable. A Proxy intercepts operations on an object, and Reflect offers the default behavior for each.

JavaScript
const guarded = new Proxy(
  {},
  {
    set(target, key, value, receiver) {
      if (key === "age" && !Number.isInteger(value)) {
        throw new TypeError("age must be an integer");
      }
      return Reflect.set(target, key, value, receiver);
    },
  },
);

guarded.age = 30;

try {
  guarded.age = "thirty";
} catch (error) {
  console.log(error.message);
}

console.log(guarded.age);

const config = Object.freeze({ mode: "strict", limits: { max: 3 } });

try {
  config.mode = "loose";
} catch (error) {
  console.log(error.name);
}

config.limits.max = 9;
console.log(config.mode, config.limits.max, Object.isFrozen(config.limits));
Text
age must be an integer
30
TypeError
strict 9 false

The proxy runs its set trap for every assignment, checks the value and forwards valid writes with Reflect.set. Object.freeze makes the object's own properties read-only, and in a module, which is strict, the failed write to mode throws a TypeError. Freezing is shallow, so config.limits.max still changed. These tools are for libraries, validation layers and frameworks. Application code rarely needs them, and a Proxy has a cost on every intercepted operation. See Proxy and Reflect.

Memory and performance

You do not allocate or free memory. The engine allocates objects on a managed heap and its garbage collector frees an object when nothing reachable still refers to it. What you control is what stays reachable: a cache without a limit, a listener never removed or a closure holding a large array keeps memory alive. WeakMap and WeakRef hold objects without keeping them alive, and they are for caches and metadata and not for application logic.

For speed, the habits that matter are not micro-optimizations. Pick the right data structure, so a Map or Set replaces repeated find or includes calls on a large array. Keep object shapes stable by creating objects of one kind in one place, which helps the engine's optimizer. Do not block the single thread with long synchronous work, because every other callback waits. Measure with a profiler before changing code, since a guess about the slow part is wrong often enough to cost more time than it saves. Garbage collection and memory management explain what the engine does.

The tools around the language

Modern JavaScript development uses fewer tools than it used to, because Node.js now ships what projects used to install.

JSON
{
  "name": "shop-reports",
  "private": true,
  "type": "module",
  "engines": { "node": ">=24" },
  "scripts": {
    "start": "node --env-file=.env src/main.js",
    "dev": "node --watch --env-file=.env src/main.js",
    "test": "node --test"
  }
}

"type": "module" makes .js files ES modules. --env-file=.env loads variables from a file with no package, --watch restarts the process when a file changes, and node --test runs the built-in test runner. The runner finds files named *.test.js and files in a test directory.

JavaScript
// src/pricing.test.js
import { test } from "node:test";
import assert from "node:assert/strict";
import { withTax } from "./pricing.js";

test("adds tax and rounds to whole units", () => {
  assert.equal(withTax(100), 120);
  assert.equal(withTax(0), 0);
});

test("tax disappears on very small amounts", () => {
  assert.deepEqual([1, 2].map((net) => withTax(net)), [1, 2]);
});
Text
✔ adds tax and rounds to whole units (0.7ms)
✔ tax disappears on very small amounts (0.1ms)
ℹ tests 2
ℹ suites 0
ℹ pass 2
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 41.3

The second test pins down a boundary the first misses: withTax(1) is Math.round(1.2), which is 1, so the tax disappears on very small amounts. That is a property of rounding to whole units, and a test should record it so that a product decision can change it on purpose. The timing figures differ on every run.

For the rest of a project: a linter such as ESLint catches mistakes the language allows, a formatter such as Prettier ends style arguments, and TypeScript adds types that are checked at build time and erased at run time. Node.js 24 can run a .ts file directly when it uses only erasable syntax, which strips the type annotations and does not support constructs that emit code, such as enum. For a library or an application with several contributors, a type checker is worth adding early, and it checks plain JavaScript too when you add JSDoc comments. Dependencies come from npm, and the habits that keep them manageable are a lock file committed with the project, npm audit in CI, and a short list of direct dependencies, because each one is code you did not write that runs with your permissions.

A worked example

The pieces fit together in small programs. This one reads a list of orders, groups them by customer, totals each group in cents, formats the totals and lists the products sold, using destructuring, spread, reduce, Object.groupBy, Intl, Set, flatMap and toSorted.

JavaScript
const orders = [
  {
    id: "A-100",
    customer: "Mei",
    items: [
      { sku: "pen", qty: 3, cents: 250 },
      { sku: "pad", qty: 1, cents: 899 },
    ],
  },
  { id: "A-101", customer: "Dara", items: [{ sku: "pen", qty: 10, cents: 250 }] },
  { id: "A-102", customer: "Mei", items: [{ sku: "ink", qty: 2, cents: 1200 }] },
];

const money = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });

const totalCents = (order) =>
  order.items.reduce((sum, { qty, cents }) => sum + qty * cents, 0);

const byCustomer = Object.groupBy(orders, ({ customer }) => customer);

for (const [customer, list] of Object.entries(byCustomer)) {
  const cents = list.map(totalCents).reduce((a, b) => a + b, 0);
  console.log(`${customer.padEnd(5)} ${String(list.length).padStart(2)} orders ${money.format(cents / 100)}`);
}

const skus = new Set(orders.flatMap(({ items }) => items.map(({ sku }) => sku)));
console.log([...skus].toSorted().join(", "));
Text
Mei    2 orders $40.49
Dara   1 orders $25.00
ink, pad, pen

Mei's two orders come to 750 plus 899 plus 2400 cents, which is 4049 and prints as $40.49. Dara's one order is ten pens at 250 cents. The money stays in integer cents until the last moment and is divided by 100 only for display, so no floating-point error accumulates. The same program in ES5 needs helper functions for grouping, a manual loop for the set, and a hand-rolled currency formatter, and the difference is not the line count. It is that every step now names what it does.

Habits to drop

Some code written in older styles is still found in tutorials and in answers copied from them, and each has a modern replacement.

Instead ofWrite
var x = 1const x = 1, or let when it changes
function () { ... }.bind(this)an arrow function
argumentsrest parameters, ...args
x !== undefined && x !== null ? x : dx ?? d
a && a.b && a.b.ca?.b?.c
Object.assign({}, a, b){ ...a, ...b }
arr.indexOf(x) !== -1arr.includes(x)
arr[arr.length - 1]arr.at(-1)
Object.prototype.hasOwnProperty.call(o, k)Object.hasOwn(o, k)
new Promise around a callback API for a core modulethe node:fs/promises style APIs
require("./file") in new codeimport ... from "./file.js"
JSON.parse(JSON.stringify(x)) to copystructuredClone(x)
a constructor function and Foo.prototype.bar = ...a class
for (var i...) with callbacksfor (const item of items)

Do not rewrite working code only to match the table, since every change risks a bug, and a rewrite deserves its own tests. Use it for what you write next.

Where this guide stops

The language has areas this guide only touches. Typed arrays and ArrayBuffer handle binary data and are the basis of streams, files and WebAssembly. WeakRef and FinalizationRegistry exist for rare caching problems and are unreliable by design. Workers give you parallel JavaScript with message passing. Regular expressions have a feature set, with lookbehind, Unicode properties and the v flag, that deserves its own study. Each of these has a post: typed arrays, WeakRef, regular expressions and realms and workers.

A language guide also cannot tell you which framework to use or how to structure an application. React, Vue, Svelte, Express, Fastify and the rest are libraries written in this language, and the more fluent you are in it, the easier their documentation reads. The best use of this page is as a checklist: when a codebase uses a feature you cannot explain, read the section and its post, write the example yourself, and change one thing to see what breaks. That habit, repeated, is how the language stops being a list of features and becomes something you can reason about.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.