Node.js / Basic: the Node.js runtime / Lesson 1
Node.js and the JavaScript foundations
Understand what runs a server-side JavaScript program, choose a supported release deliberately, and use values and functions without depending on browser APIs.
On this page
Lesson goals
- Explain the concepts and trade-offs behind node.js and the javascript foundations.
- Predict and verify both examples, including their outputs and cleanup behavior.
- Diagnose the three common failures and apply the worked solutions to related inputs.
A runtime has boundaries
Node.js runs JavaScript outside a browser. The V8 engine executes the language, while Node provides facilities such as files, processes, networking, and timers. A web page has document and window objects; a Node process does not automatically have a document to edit. A useful first question is therefore which environment owns an API. Keep business rules as ordinary functions and put file or network access at the edge. That separation makes the same calculation easy to test without starting a server, and it makes missing environmental assumptions visible before deployment.
Choose and identify the runtime
The official release page was reviewed on 2026-10-23: Node 24 and Node 22 are listed as LTS, Node 26 as Current, and Node 20 as end of life. These are dated facts, not permanent labels. Select an actively supported line, install its current security patch, and record the exact runtime in development and CI. The examples use stable features available in Node 22.23.3, the local verification runtime. Save each complete example as the displayed .mjs filename and execute node followed by that filename. Version managers and operating-system packages can expose different node executables, so check node --version in the actual terminal used by your project.
Values, names, and explicit conversion
Use const when a binding should not be reassigned and let when reassignment expresses the algorithm. A const object can still have mutable properties; const protects the binding rather than deeply freezing the value. Input from a terminal or environment arrives as text, even when it looks numeric. Number converts that text, and Number.isFinite rejects NaN and infinities. Reject an empty string before conversion if an empty field must not mean zero. Prefer strict equality when comparing values. These small decisions prevent accidental string concatenation and stop invalid quantities before they reach persistence or a response.
const rows = [{ active: true, quantity: 3 }, { active: false, quantity: 8 }, { active: true, quantity: 2 }];
const total = rows.filter(row => row.active).reduce((sum, row) => sum + row.quantity, 0);
console.log(total);
console.log(typeof process, typeof document);
5
object undefined
Filtering happens before addition; process belongs to Node, while document is absent. Both lines are deterministic in this standalone file.
Functions and collections tell the story
A function should receive the values it needs and return a clear result. Array map transforms every item, filter selects items, and reduce combines them into one result. Providing an initial accumulator also defines what happens for an empty array. The first example filters active items before summing their quantities; the result does not depend on console output or global mutable state. The second example makes numeric validation explicit and catches the expected failure at the program boundary. Read the input, predict the output, and then run the file. That habit develops a model of execution rather than dependence on copied syntax.
function quantity(text) {
if (text.trim() === '') throw new Error('Quantity is required');
const value = Number(text);
if (!Number.isFinite(value) || value < 0) throw new Error('Invalid quantity');
return value;
}
console.log(quantity('12') + 3);
try { quantity('many'); } catch (error) { console.log(error.message); }
15
Invalid quantity
Number conversion produces 12, so addition yields 15. Invalid text becomes NaN and is deliberately rejected before use.
From a script to a maintainable program
Run a small script to completion before adding long-lived resources. A process normally exits when no referenced work remains, but a listening server or repeating timer keeps it alive. Exit status zero indicates successful completion; a nonzero status allows shell scripts and CI to detect failure. Avoid forcing process.exit immediately after asynchronous logging or cleanup because pending work may be interrupted. Prefer setting process.exitCode after handling an error. Before moving on, distinguish syntax errors, runtime exceptions, and incorrect business results: each requires a different investigation, even if all three first appear as an unexpected terminal screen.
Common errors and fixes
ReferenceError: document is not defined
- Why it happens
- Browser DOM code was executed in Node.
- How to fix it
- Move DOM work to the browser and pass plain data to server functions.
- Prevent it next time
- Identify the owning runtime when choosing an API.
A total becomes 123 instead of 15
- Why it happens
- Text input was concatenated with a number.
- How to fix it
- Convert and validate before arithmetic.
- Prevent it next time
- Test numeric text, empty text, and nonnumeric text separately.
The wrong Node version runs
- Why it happens
- The terminal resolves another installation first.
- How to fix it
- Inspect node --version and the executable path, then select the project runtime.
- Prevent it next time
- Pin and verify runtime versions in CI and onboarding instructions.
Check your understanding
1. Compute the sum of positive values in [4, -2, 7, 0] without changing the array.
Show worked solution
Filter with value > 0, giving [4, 7], then reduce with an initial zero. The result is 11. Confirm the original array still contains four items; transformation should not silently alter caller-owned input.
2. Define behavior for quantity inputs "", "0", and "Infinity".
Show worked solution
Reject the empty string before Number, accept "0" as numeric zero, and reject "Infinity" using Number.isFinite. The order matters because Number("") is zero. Give each rejected case a clear user-facing validation message.
Key takeaways
- Node.js runs JavaScript outside a browser.
- The official release page was reviewed on 2026-10-23: Node 24 and Node 22 are listed as LTS, Node 26 as Current, and Node 20 as end of life.
- Run a small script to completion before adding long-lived resources.