JavaScript Essentials for Node: Destructuring, Closures, Promises and the Event Loop

Node.js and Express: Build a Back End API from Scratch · JavaScript and Node Core in Depth · 6 min read · Updated

One thread, many users

  1. Requests arrive. Node runs your handler on a single thread.
  2. When the handler starts slow work, it is handed over and the loop carries on.
  3. The operating system does the disk or network work in the background.
  4. When it finishes, the loop runs your callback or resumes your await.

Node.js is JavaScript outside the browser, so everything you know about the language applies. Express code, though, uses a particular slice of it again and again: pulling values out of objects, copying objects without changing the original, functions that return functions, and asynchronous code written with promises. If one of these feels shaky, backend code will feel confusing. This lesson is a fast review of exactly those parts, with one small file that you can run.

If you are new to JavaScript, read this lesson slowly and try each line in the REPL. If you already know the language well, skim the headings and read the last section on the event loop, because it explains why Node can serve many users at once.

Destructuring, spread and rest

Destructuring takes values out of an object or array and gives them names. In Express you will write const { title, price } = req.body hundreds of times. Spread (...) copies the items of an object or array into a new one, which is how you change data without changing the original. Rest is the same three dots used the other way round, to collect the remaining items. The rule that decides which is which is simple: on the left of an assignment or in a function's parameter list it collects (rest), and everywhere else it expands (spread).

  1. Make a folder and open it in a terminal. Run npm init -y, then open package.json and add "type": "module" so that import works.
  2. Save the code below as essentials.js and run it with node essentials.js.
// JavaScript you need before Node: destructuring, spread, closures, higher-order functions, promises.
const user = { name: 'Asha', age: 29, city: 'Pune', skills: ['js', 'sql'] };

// Destructuring pulls values out by name or position.
const { name, city } = user;
const [first, ...others] = user.skills;
console.log(name, city, first, others);

// Spread copies; rest collects.
const older = { ...user, age: user.age + 1 };
const sum = (...numbers) => numbers.reduce((total, n) => total + n, 0);
console.log(older.age, user.age, sum(1, 2, 3));

// A closure remembers the variables around it.
function counter() {
  let count = 0;
  return () => ++count;
}
const next = counter();
next();
console.log('count', next());

// A higher-order function takes or returns a function.
const double = (n) => n * 2;
const numbers = [1, 2, 3, 4, 5, 6];
const result = numbers.filter((n) => n % 2 === 0).map(double);
console.log(result);

// Callbacks, then the same idea with promises and async/await.
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));

async function main() {
  try {
    const [a, b] = await Promise.all([wait(20, 'A'), wait(10, 'B')]);
    console.log(a, b);
    await Promise.reject(new Error('Something failed'));
  } catch (error) {
    console.log('Caught:', error.message);
  }
}
main();
node essentials.js
Asha Pune js [ 'sql' ]
30 29 6
count 2
[ 4, 8, 12 ]
A B
Caught: Something failed

Look at the second line: older.age is 30 and user.age is still 29. Spread made a new object, so the original is untouched. This matters in servers, because code that quietly changes shared objects causes bugs that appear only under load.

Closures and higher-order functions

A closure is a function that remembers the variables around the place where it was created. The counter function returns an inner function that still sees count, even after counter has finished. Closures are how middleware factories work: rateLimit({ max: 5 }) returns a function that remembers max. A higher-order function is a function that takes another function as input or returns one. filter, map and reduce take functions. Express itself is built on this idea: you hand app.get a function and Express calls it later.

Callbacks, promises and async/await

Slow things, such as reading a file or asking a database, must not freeze the server, so Node starts them and carries on. When the result is ready, it calls a function you provided, a callback. Nested callbacks quickly become hard to read, so JavaScript added promises: an object that stands for a value that will arrive later. async and await let you write promise code in a straight line. In the example, Promise.all waits for two promises at the same time, which is much faster than waiting for one and then the other. A rejected promise becomes an exception that try/catch can handle.

  • Always await a promise, or return it. A promise you forget about can fail silently.
  • Use Promise.all when the tasks do not depend on each other, and await one by one when they do.
  • Wrap awaited code in try/catch, or let Express 5 pass the error to your error handler.

JSON and modules

JSON is text in the shape of JavaScript objects, and it is the language of APIs. JSON.stringify turns an object into text and JSON.parse turns text back into an object. Remember that JSON has no functions, no undefined, and no dates: a date becomes a text string. For code organisation, ES modules use export and import, which this course uses throughout. Older code uses require, which you will still meet in many projects.

The event loop in one picture

JavaScript runs your code on one thread, which means one thing at a time. Node serves many users because slow work, such as network and disk, is handed to the operating system, and your code is called again when it finishes. The event loop is the part that keeps checking for finished work and runs the waiting callbacks. The practical rule is: never block the loop. A long calculation or a synchronous file read inside a request handler stops every other user until it ends. Lesson 18 shows how to move heavy work to other threads.

Your task

  1. Change the example so that counter takes a starting number and a step.
  2. Write a function pick(object, ...keys) that returns a new object with only those keys.
  3. Make one of the two wait promises reject, and see what Promise.all and Promise.allSettled do.

How to check it worked

  • Your output matches the output shown above.
  • You can say whether ... is spread or rest in any line.
  • You can explain why a long synchronous loop in a handler hurts every user.

Frequently asked questions

Is JavaScript really single-threaded?

Your code runs on one thread, but Node uses other threads inside for things such as file and network work, and you can start more with worker threads.

Should I use callbacks, promises or async/await?

Use async/await in new code. Callbacks still appear in older libraries, and util.promisify can turn many of them into promises.

What is the difference between spread and rest?

They look the same. Rest collects the remaining items into one variable. Spread expands items out of a variable.

Practise with interview questions