Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 133 ยท Getting Started

Modern JavaScript You Need

The modern JavaScript features Node.js code relies on - destructuring, spread, optional chaining, classes with private fields, iterators, groupBy, toSorted and using.

Node.js 24 runs nearly all of modern JavaScript, and real Node code uses it constantly: destructuring function arguments, optional chaining on parsed JSON, classes with private fields, Map and Set, new array methods. If you learned JavaScript years ago, or only from short snippets, this lesson fills in the features that appear on almost every page of this course. If you are new to the language, the JavaScript tutorial teaches each one in depth; here we focus on how they are used in Node programs.

Every feature below was run on Node 24. Because Node is one runtime you control, you do not need Babel or polyfills for any of it, a luxury front-end developers do not have.

const, let and template literals

Use const by default, let only when you must reassign, and never var. Template literals (backticks) build strings with ${} and can span lines.

Node.js const, let and template literals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

const protects the binding, not the object: you can still add items to a const array. It stops accidental reassignment, which is why most Node style guides default to it.

Destructuring, defaults, rest and spread

Destructuring pulls values out of arrays and objects into variables. Rest (...name) collects the remaining items; spread (...value) expands items in place. Together they replace many loops and Object.assign calls.

Node.js Destructuring, rest and spread

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Option objects with defaults, as in connect, are the standard way Node APIs take settings (fs.readFile(path, { encoding: 'utf8' })). Remember that spread makes a shallow copy: nested objects are shared. For a deep copy use structuredClone.

Optional chaining and nullish coalescing

Data from JSON files, environment variables and APIs is often incomplete. ?. stops and returns undefined if the left side is null or undefined. ?? supplies a default only for null or undefined, unlike ||, which also replaces 0, '' and false.

Node.js ?. and ?? versus ||

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Choose ?? whenever zero, an empty string or false are legitimate values, which in configuration code is most of the time.

Classes, private fields and static members

Classes give a clear shape to objects with behavior. Fields starting with # are truly private: code outside the class cannot read them, not even by accident. Getters and setters expose controlled access, and static members belong to the class itself.

Node.js A class with private state

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

You will see this pattern in events, where classes extend EventEmitter, and in streams, which are built by subclassing. Classes are not required: plain functions and objects are fine, and many Node programs use few classes.

Iterators, generators and for...of

Anything iterable (arrays, strings, Map, Set, streams) works with for...of and spread. A generator function (function*) produces values lazily with yield, so it can describe huge or even infinite sequences without holding them in memory. Node's async iterators extend the same idea to streams of data arriving over time.

Modern Node (22+) adds iterator helpers: map, filter, take, drop, toArray and more directly on iterators, so lazy pipelines no longer need arrays.

Node.js Generators and iterator helpers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Map, Set and the newer collection methods

Use Map when keys are not just strings or you need insertion order and fast add/remove; use Set for unique values. They also work with any value as key, including objects. Node 22 added set algebra methods: union, intersection, difference, symmetricDifference, isSubsetOf and more.

Node.js Map and Set

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Plain objects are fine for fixed records; prefer Map for dictionaries with dynamic keys, because an object key like __proto__ or constructor can cause surprises.

Modern array and object methods

Several newer methods remove common chores:

  • at(-1) reads from the end. findLast and findLastIndex search backward.
  • toSorted, toReversed, toSpliced and with return new arrays instead of mutating (Node 20+). Plain sort() mutates, which is a classic source of bugs.
  • Object.groupBy and Map.groupBy group items by a key function (Node 21+).
  • Object.fromEntries turns pairs into an object; Object.entries does the reverse.
  • Object.hasOwn(obj, key) replaces obj.hasOwnProperty(key).
  • flat, flatMap, includes, Array.from, Array.fromAsync (Node 22+, collects an async iterable).
  • String.prototype.replaceAll, padStart, at and Promise.withResolvers (Node 22+).
Node.js Array and object methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

If your result differs from the lines you expect, check the Node version first: these methods are missing in very old releases.

Errors with cause, and optional catch binding

Wrap a low-level error in a higher-level message while keeping the original with the cause option. If you do not need the error object in a catch, you can omit it.

Node.js Error cause and AggregateError

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Numbers, strings and small helpers

Numeric separators make big literals readable (1_000_000), BigInt handles integers beyond 2^53, Number.isInteger and friends avoid coercion, and Intl formats numbers and dates for any language. Strings have replaceAll, trimEnd, padStart, at and localeCompare. Dates are covered in the JavaScript tutorial.

Node.js Numbers and strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

using declarations: automatic cleanup

Files, database handles and locks must be closed even when code throws. Explicit resource management adds using (and await using for async cleanup): when the block ends, the object's [Symbol.dispose]() method runs automatically, like finally without the boilerplate. In Node the syntax works in version 24 (V8 13.6); Symbol.dispose and Symbol.asyncDispose have existed since Node 18.18/20, and some built-ins gain disposers over time. If your Node is older than 24, use try...finally.

Node.js using and Symbol.dispose

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Resources are released in reverse order of creation, and also when an exception is thrown. As of Node 24 many built-in objects (such as file handles) are not yet disposable by default, so check before relying on that; the syntax itself is dependable.

Some features used elsewhere in this course are covered in their own lessons: promises and async/await in Asynchronous Programming, modules in ES Modules, and top-level await in ES Modules too.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does config.port ?? 3000 return when config.port is 0?

    ?? only falls back for null and undefined. 0 is a valid value and is kept; || would have returned 3000.
  2. 2. What is true of orders.toSorted(...)?

    toSorted is the non-mutating version of sort. toReversed, toSpliced and with work the same way.
  3. 3. What does a field named #count in a class mean?

    Names starting with # are private class members; access from outside is a syntax error.
  4. 4. What does Object.groupBy(items, fn) return?

    Object.groupBy groups items by key into arrays. Map.groupBy does the same but returns a Map.
  5. 5. With two using declarations in one block, in which order are they disposed?

    Disposal is last in, first out, so dependent resources are closed before the things they rely on.

Summary

  • Use const by default, template literals, destructuring (with defaults), rest and spread.
  • ?. avoids crashes on missing data; ?? and ??= default only for null and undefined.
  • Classes support private #fields, getters, setters, static members and inheritance.
  • Iterators and generators produce values lazily; Node 22+ has iterator helpers like map, filter, take.
  • Map, Set (with union, intersection...), toSorted, with, Object.groupBy, Array.fromAsync and Promise.withResolvers are available in current Node.
  • new Error(message, { cause }) chains errors; using closes resources automatically on Node 24.

Next: ES Modules