Skip to content

15 min read

JavaScript basics for backend beginners

In one sentence: To write a server in JavaScript you only need a little: values saved under a name, objects and lists to describe the data, functions so you don't repeat yourself, JSON to send data over HTTP and await to wait for what takes time.

What you will learn

  • Save values with const and let, and recognize text, numbers, objects and arrays.
  • Write functions and use them with filter, map and for…of to choose and transform data.
  • Turn an object into JSON and a JSON into an object, with JSON.stringify and JSON.parse.
  • Read code with async and await, and explain what a promise is and what happens if you forget the await.

Before you start, read: 01-node-js.md

Ana wants the shop’s website to have an “Under €25” section. In Phase 2, her nginx served fixed files: whatever was on the disk, as it was. But a file can’t choose. To answer “what costs less than €25?”, the server has to go through the products, compare each price, keep the ones that pass and turn the result into text to send it over HTTP.

That’s a program, and in this phase you write it in JavaScriptThe programming language of web pages, which, with Node.js, is also used outside the browser to write servers. A JavaScript program is text with instructions that run one after another.Go to definition, the language that Node.jsA program that runs JavaScript outside the browser, on your computer or on a server. It uses the same engine as Chrome and adds what a web page can’t do, like reading files or listening on a port.Go to definition runs. You don’t need the whole language: a small server uses a dozen ideas, and they are the ones in this lesson.

If you already program in JavaScript, you can skip to lesson 3, “TypeScript”. First, take the quiz at the end: if you get all six right, you won’t miss anything.

The analogy

Think of the kitchen of a café:

  • The jars on the shelf have a label, “salt” or “sugar.” The label is the name, and what’s inside is the value: that’s a variable.
  • Each dish on the menu has its card, with fixed fields: name, price, allergens. That’s an object.
  • The cards go in a binder, in order: the first, the second, the third. That’s an array.
  • The omelet recipe says what to do with some ingredients and gives you back a dish. It’s written once and works for every omelet: that’s a function.
  • The order ticket is the slip where the waiter writes down the order, in a format the kitchen understands. That’s JSON: data turned into text so it can travel.
  • If you order something that takes a while, they give you a number and you keep chatting until they call it. The number is a promise, and waiting for them to call it is await.

Where the analogy breaks down

  • You can peel the label off a jar and stick it on another one. Not a name created with const: it always holds the same value. Mind you, if that value is an object, what’s inside can change: you’ll see it with the mug.
  • A cook understands “a pinch of salt.” JavaScript does exactly what you write: with one comma missing, the program doesn’t even start.
  • In the binder, the first card is number 1. In an array, the first one is number 0.

Open the terminal in the project folder, ~/backend-course/phase-3/shop-api, and type node. The REPLREPL stands for Read-Eval-Print Loop.A way of working with a language in which you type a line of code, it runs and you see the result right away, without creating any file. In Node.js, you open it by typing node, with nothing else, in the terminal.Go to definition you met in lesson 1, “Node.js” opens: you type a line, press Enter and Node answers with its result. You leave with .exit or with Ctrl + D.

Try every example in this section in it, in order and without closing it: some use values from the earlier ones. The outputs are from Node 26.11.1; with another version, some error message may change.

Everything a program handles is a value. These are the three simplest kinds:

In the REPL: three values

Ventana de terminal
'Mug'
8.5 * 2
20 < 25

What you will see:

'Mug'
17
true
  • 'Mug' is text (a string): it goes in quotes, single or double.
  • 8.5 * 2 is an operation with numbers. Decimals use a point, and there are no commas for thousands: one thousand is 1000. * means multiply.
  • 20 < 25 is a comparison, and its result is true (or false). The comparisons are <, >, <=, >=, === (equal) and !== (not equal).

An oddity that matters in a shop: decimals aren’t always exact. 0.1 + 0.2 gives 0.30000000000000004, because the computer stores numbers in binary and some decimals don’t fit exactly. That’s why prices are usually stored in cents, as whole numbers: €8.50 is 850.

A VariableA name that holds a value to use later, such as price = 8.5. In JavaScript it’s created with const, if it won’t be swapped for another value, or with let, if it will.Go to definition is a name that holds a value so you can use it later. You create it with const if you won’t give it another value, and with let if you will:

In the REPL: const and let

Ventana de terminal
const price = 8.5
price * 2
price = 9
let quantity = 1
quantity = 3

What you will see:

undefined
17
Uncaught TypeError: Assignment to constant variable.
undefined
3

One output per line. Creating a variable has no result, and the REPL says so with undefined, “no value.” After that, price is 8.5 in any calculation.

price = 9 fails: price was created with const, and that’s what the error says: you can’t assign a new value to a constant. With let quantity, on the other hand, you can change the value as many times as you want, and the REPL shows you the new one, 3.

The = only means “store this here.” To compare, you use ===. Use const whenever you can: if you see let, you know that value is going to change. (In old code you’ll see var, the way it was done before 2015: you don’t need it.)

If you write text between backticks (`), you can put values inside it with ${…}. They’re called template strings:

In the REPL: text with a gap

Ventana de terminal
`Two mugs: ${price * 2} €`

What you will see:

'Two mugs: 17 €'

Node works out what’s inside ${…} and puts it in its place. On a US keyboard, the backtick is the key in the top-left corner, under Esc and to the left of the 1.

A product isn’t a single value: it has a number, a name and a price. An ObjectA value that groups several pieces of data, each with its own name, such as { name: "Mug", price: 8.5 }. Each piece is read with a period and its name, such as product.price.Go to definition puts them together, each with its name:

In the REPL: the mug

Ventana de terminal
const mug = { id: 2, name: 'Mug', price: 8.5 }
mug.name
mug.price = 9
mug

What you will see:

undefined
'Mug'
9
{ id: 2, name: 'Mug', price: 9 }
  • The braces { … } create the object. Inside, each piece of data is a name, a colon and its value, separated by commas. Each piece of data is called a property.
  • mug.name reads a property: the object’s name, a period and the property’s name.
  • mug.price = 9 changes one, even though mug is const. The name mug still points to the same object; what changes is what’s inside.

An ArrayA list of values in order, such as [20, 8.5, 35]. Each value is read by its position, which starts counting at 0: prices[0] is the first one.Go to definition is a list of values in order, between square brackets. This is how products.js, the first file of this lesson, begins:

products.js
// The shop's products: a list (an array) of objects.
const products = [
{ id: 1, name: 'T-shirt', price: 20 },
{ id: 2, name: 'Mug', price: 8.5 },
{ id: 3, name: 'Hoodie', price: 35 },
];
  • The first line is a comment: it starts with //, and Node doesn’t read it. It’s for whoever reads the code.
  • const products = [ … ] creates an array of three objects, separated by commas. The comma after the last one is optional.
  • The line breaks only help reading: for JavaScript it’s a single instruction, which the ; at the end closes.

You read each element by its position, which starts at 0:

In the REPL: positions

Ventana de terminal
const prices = [20, 8.5, 35]
prices[0]
prices[3]
prices.length

What you will see:

undefined
20
undefined
3

prices[0] is the first one, and prices[3] would be the fourth, which doesn’t exist: JavaScript doesn’t give an error, it returns undefined. length is how many elements it has, so the last one is always the one at position length - 1.

A FunctionA named piece of code that takes some data, does something with it and returns a result. It’s written once and used as many times as needed.Go to definition is a piece of code with a name that takes data and returns a result. This one works out what several units of a product cost:

products.js
// A function: it takes a product and a quantity, and returns what they cost.
function total(product, quantity) {
return product.price * quantity;
}

Word by word:

  • function total creates a function called total.
  • (product, quantity) are its parameters: the names that the data it receives will have inside the function.
  • What goes between the braces is what it does each time it’s used.
  • return gives the result back to whoever called it.

Writing it doesn’t run anything. It runs when you call it, with its name and the data in parentheses: total(products[1], 2) gives 17. The same function works for the T-shirt, the hoodie and the products that arrive tomorrow.

Choosing and transforming a list: filter and map

Section titled “Choosing and transforming a list: filter and map”

Now, Ana’s section:

products.js
// filter keeps the ones that meet a condition; map transforms each one.
const cheap = products.filter((product) => product.price < 25);
const names = cheap.map((product) => product.name);
console.log(`Under 25 €: ${names.join(', ')}`);
  • (product) => product.price < 25 is an arrow function: a short function with no name. To the left of =>, what it receives; to the right, what it returns. Here it returns true or false.
  • products.filter(…) calls that function with each product and returns a new array, only with the ones that gave true: the T-shirt and the mug.
  • cheap.map(…) calls its function with each element and returns an array of the same size, with what it returned each time: ['T-shirt', 'Mug'].
  • names.join(', ') joins the pieces of text in the list into one, with a comma and a space between them.
  • console.log(…) writes a line in the terminal.

Neither filter nor map changes products: both create a new array.

Deciding with if and repeating with for…of

Section titled “Deciding with if and repeating with for…of”

if runs a block only if a condition is met, and else runs the other one. The condition goes in parentheses, and each block, in braces:

In the REPL: if and else

Ventana de terminal
if (mug.price < 25) { console.log('Cheap') } else { console.log('Expensive') }

What you will see:

Cheap
undefined

The mug costs 9, so the first block runs. Cheap is written by console.log, and undefined is the REPL saying that the if has no result.

And for…of repeats a block once for each element of an array:

products.js
for (const product of products) {
console.log(`Two ${product.name}s: ${total(product, 2)} €`);
}

It reads “for each product of products.” On each pass, product is the next element, and the line inside calls total with it. This is called a loop: three products, three passes, three lines in the terminal.

An object lives in the program’s memory. To send it over HTTP you have to turn it into text, and the format almost every APIAPI stands for Application Programming Interface.The way a program offers its services to other programs, that is, what you can ask it for and how it answers. The frontend talks to the backend through an API.Go to definition uses is JSONJSON stands for JavaScript Object Notation.A format for writing data as text, with braces, quotes and colons: {"product":"mug","quantity":2}. People can read it, and so can almost any programming language, and it’s the most common format for the data that travels between a frontend and a backend.Go to definition, the one you saw in the body of requests in Phase 2:

products.js
// JSON: the text that data travels in over HTTP.
const text = JSON.stringify(products[1]);
console.log(text);
const cap = JSON.parse('{"id":4,"name":"Cap","price":15}');
console.log(`From text to object: ${cap.name}, ${cap.price} €`);
  • JSON.stringify(products[1]) turns the mug into text: {"id":2,"name":"Mug","price":8.5}. That’s what your server will send as a response.
  • JSON.parse('…') does the opposite: it takes a JSON text and returns an object, with its properties. That’s what your server will do with the body of a POST.

JSON looks like a JavaScript object, but it’s stricter: names and text values always go in double quotes. Otherwise, JSON.parse fails:

In the REPL: badly written JSON

Ventana de terminal
JSON.parse("{name: 'Cap'}")

What you will see:

Uncaught:
SyntaxError: Expected property name or '}' in JSON at position 1 (line 1 column 2)

It expected a property name or a } at position 1: right where the quote before name is missing (positions are counted from 0). When a client sends a body like that, your server will have to answer with a 400, as you saw in “Status codes”.

Waiting for what takes time: promises, async and await

Section titled “Waiting for what takes time: promises, async and await”

Reading a file, or waiting for another server’s response, takes time. Look at what readFile, the function from lesson 1 that reads files, returns. In the REPL you don’t need import: Node’s ModuleA code file that offers some of its pieces to other files, which bring them in with import. This way a program is split across several files and can use the pieces that come with Node.js or with a package.Go to definition are at hand, and fs.promises.readFile is that same function:

In the REPL: a promise

Ventana de terminal
fs.promises.readFile('products.json', 'utf8')

What you will see:

Promise { <pending> }

'utf8' asks for the content as text. But it doesn’t return that text: it returns a pending promise. The text isn’t there yet, but it will come.

That’s what a PromiseA value that isn’t there yet but will arrive, like the text of a file that is being read. Until it arrives, the program can go on with other things; with await, it waits for it.Go to definition is: a value that will arrive later. To use what it brings you have to wait for it, and that’s what async and awaitTwo JavaScript words for waiting for something that takes time, like reading a file or receiving a response, without stopping everything else. await waits for a promise to arrive, and async marks the function that uses it.Go to definition are for. This is the second file of this lesson, wait.js:

wait.js
// async and await: waiting for something slow (here, reading a file) without stopping the program.
import { readFile } from 'node:fs/promises';
async function countProducts(file) {
const text = await readFile(file, 'utf8');
return JSON.parse(text).length;
}
console.log('Before reading the file');
const count = await countProducts('products.json');
console.log(`The file has ${count} products`);
  • import { readFile } … brings in the function that reads files, as in lesson 1.
  • async function countProducts(file) creates a function marked as async: inside it you can use await, and whatever it returns will arrive as a promise.
  • await readFile(…) waits for the promise to bring the text, and stores it in text.
  • return JSON.parse(text).length turns the text into an array and returns how many elements it has.
  • At the bottom, await countProducts(…) waits for that function. Here await is outside a function, and that’s allowed: your files are modules, because of the "type": "module" in the package.json from lesson 1.

Waiting isn’t stopping. While an await waits for the disk or the network, Node can do other things: in a server, serve other clients. How it manages that is lesson 9, “Event loop”.

The goal: write the two files, check that they print the same lines as here, add a product, and cause the most common mistake with promises so you recognize it when it happens to you.

Open the shop-api folder in VS Code. Create products.js with the five blocks of products.js in this lesson, in the order they appear. Also create wait.js. You need the products.json from lesson 1 in the same folder.

Type them yourself: getting things wrong teaches you too. If you get stuck, download this lesson’s folder and compare it with yours:

Ventana de terminal
cd ~/backend-course/phase-3
curl -O https://backenddesdecero.com/practicas/shop-api/02-javascript.tar.gz
tar -xzf 02-javascript.tar.gz

This lesson doesn’t install any packages, so you don’t need npm install. The outputs are from Node 26.11.1.

1. The products

Ventana de terminal
node products.js

What you will see:

Under 25 €: T-shirt, Mug
Two T-shirts: 40 €
Two Mugs: 17 €
Two Hoodies: 70 €
{"id":2,"name":"Mug","price":8.5}
From text to object: Cap, 15 €

One line for each console.log, in the order of the file: the filter, the three passes of the loop and the two JSON ones. Notice that 17 comes out without decimals: for JavaScript, 17 and 17.0 are the same number.

If you get an error, the most likely cause is a missing comma, quote or bracket. This is how Node reports it if you delete the comma after the T-shirt:

2. If a comma is missing

Ventana de terminal
node products.js

What you will see:

file:///Users/ana/backend-course/phase-3/shop-api/products.js:4
{ id: 2, name: 'Mug', price: 8.5 },
^
SyntaxError: Unexpected token '{'
at compileSourceTextModule (node:internal/modules/esm/utils:355:16)
…
Node.js v26.11.1

SyntaxError is a syntax error, a mistake in how the code is written: Node didn’t understand the code and didn’t run a single line. It tells you the file, the line (:4) and, with ^, where it got lost: it didn’t expect a {. The real mistake is usually just before, here at the end of line 3.

We’ve removed nine lines of Node’s internal details (…), and the path is a Mac’s. If, after fixing it, you get Cannot find module, you’re not in the file’s folder: go back with cd ~/backend-course/phase-3/shop-api.

Challenge: a €15 cap arrives at the shop. Add it to the array with id 4. Which lines change when you run node products.js, and why didn't you have to touch anything else?Show answer

Add a line to the array, with its comma:

{ id: 4, name: 'Cap', price: 15 },

Two things change:

Under 25 €: T-shirt, Mug, Cap
Two T-shirts: 40 €
Two Mugs: 17 €
Two Hoodies: 70 €
Two Caps: 30 €
{"id":2,"name":"Mug","price":8.5}
From text to object: Cap, 15 €

The cap shows up among the cheap ones, and there’s one more pass in the loop. You didn’t touch anything else because filter, map and for…of go through the whole array, however many elements it has, and total works for any product.

3. Waiting for the file

Ventana de terminal
node wait.js

What you will see:

Before reading the file
The file has 3 products

First the line from before and, once the file has been read, the count. It’s three even if you added the cap in the challenge: wait.js reads products.json, a separate file, not the array in products.js. If you get ENOENT: no such file or directory, products.json is missing from the folder.

Now, in wait.js, delete the word await from the line const count = await countProducts('products.json');, save and run it again:

4. Without the await

Ventana de terminal
node wait.js

What you will see:

Before reading the file
The file has [object Promise] products

There’s no error, and that’s what makes it dangerous: the program carries on with the promise without waiting for the number. When you put it inside text, JavaScript writes [object Promise]. If you see that in an output or in a LogA text file where a program writes down what happens, one line for each thing. A web server’s has a line for each request it receives, and it’s the first thing you look at when something fails.Go to definition, an await is missing. Put it back before moving on.

  • In DevTools (how to open them): in the Network tab, an API’s response is a JSON text. Behind it, a server did a JSON.stringify, and the page will do a JSON.parse.
  • In the CORS lesson you wrote await fetch(…).then(r => r.json()). Now you can read it: fetch returns a promise, .then(…) tells it what to do when it’s fulfilled, r => r.json() is an arrow function that turns the response into data, and await waits for the result.
  • The spinning circle while a page loads is often an unfulfilled promise: the data hasn’t arrived.
  • = to compare. = stores a value; to compare, you use ===. And avoid ==: it converts before comparing, and 9 == '9' gives true, while 9 === '9' gives false.
  • Forgetting the await. The program carries on with a promise instead of the value, with no error: [object Promise] inside text, or undefined when reading a property.
  • Counting from 1. The first one is [0], and the last one, [length - 1]. Asking for a position that doesn’t exist gives no error: it gives undefined.
  • Prices with decimals. 0.1 + 0.2 doesn’t give 0.3. Store cents as whole numbers. And don’t store them as text: '8.5' + '20' gives '8.520', because + with text glues the pieces together.
  • JSON with single quotes or no quotes. JSON.parse only accepts double quotes, in names and in text values.
  • Thinking const freezes an object. It stops you giving the variable another value, but its properties can still change.
  • The basic values are text, numbers and true/false. You store them in variables with const or, if they’re going to change, with let.
  • An object groups data with names (mug.price), and an array puts it in order, counting from 0.
  • A function takes data and returns a result. filter chooses elements from an array, map transforms them and for…of goes through them one by one.
  • JSON.stringify turns an object into text to send it, and JSON.parse turns a JSON text into an object.
  • What takes time returns a promise, and await, inside an async function, waits for its value. Without await, you have the promise and not the value.
In a program you write const visits = 0 and, further down, visits = visits + 1. What happens when you run it?

A shop has five products in an array, products. What does products[5] return?

You want the list of names of the products under €10. What do you do?

Your server receives the text {"name":"Cap","price":15} in the body of a POST, stored in the variable body. How do you read the price?

Your program writes “The order has [object Promise] products”. What’s the most likely cause?

In the shop, a €0.10 sticker and a €0.20 badge add up to €0.30000000000000004 in the cart. How do you avoid it?

phase-3 · lesson 2/9