bhylu.com

Advertisements

Node.js JavaScript Basics

Objects, arrays, functions and exceptions are enough to begin useful Node programs. Practise those language tools before mixing them with network timing.

How it works

A pure function receives values and returns a result without reading a file or changing a global variable. That makes its rules easier to test independently of a server. The example validates a requested quantity with an integer and range check, then returns an updated object rather than changing the caller’s inventory record. JavaScript syntax is shared with browsers, but the rules here do not depend on either environment.

Run the code

Run this example locally with Node.js. The exact sources are reviewed on Node 22.15.1 and Node 24.22.1 unless a specialised lab states otherwise. Save the complete source as javascript-basics.mjs in a separate empty exercises folder and run node javascript-basics.mjs. There is no Node.js browser runner on Bhylu; the plain JavaScript playground does not provide these filesystem, server or process APIs.

Download the complete source. Ordinary Node scripts need no Apache, PHP or MySQL service. File examples own their temporary folders; network fixtures use loopback and available temporary ports.

Example

javascript-basics.mjs

function reserve(kit, quantity) {
  if (!Number.isSafeInteger(quantity) || quantity < 1 || quantity > kit.available)
    throw new RangeError('Unavailable quantity');
  return { ...kit, available: kit.available - quantity };
}
const source = { name: 'tripod', available: 3 };
console.log(reserve(source, 2).available);
console.log(source.available);
try {
  reserve(source, 4);
} catch (error) {
  console.log(error.message);
}

Expected result

1
3
Unavailable quantity

The returned inventory has one unit available while the input still has three. The rejected request shows a domain rule, not a promise that concurrent reservations are safe. A real shared inventory will need atomic persistence as well.

Use the Node.js API reference for the precise version contract.