devnotes.

Using the Node.js REPL

Before you build another .js file, it's worth getting comfortable with a tool that ships with Node.js by default and needs no setup at all: the REPL.

What REPL stands for

REPL is short for Read, Eval, Print, Loop — which is also exactly what it does, in order:

  • Read — it reads a line of JavaScript you type.
  • Eval — it evaluates (runs) that line.
  • Print — it prints whatever the line returned.
  • Loop — it goes back to waiting for your next line.

In plain terms: it's an interactive JavaScript playground running right inside your terminal, powered by the exact same engine that runs your .js files.

Opening it

Just type node on its own, with no filename, and press Enter:

node

Your prompt changes to >, which means Node is now waiting for JavaScript, not shell commands.

Trying it out

> const price = 250
undefined
> const quantity = 4
undefined
> price * quantity
1000

Notice undefined shows up after variable declarations — that's just the REPL printing the result of that line, and const assignments don't return a value, so it shows undefined. The moment you write an expression that actually produces something (price * quantity), it prints the result straight away, with no console.log needed.

Writing a function across multiple lines

The REPL is smart enough to know when a block isn't finished yet:

> function applyDiscount(amount, percent) {
... return amount - (amount * percent / 100);
... }
undefined
> applyDiscount(1000, 10)
900

The ... prompt means "still inside a block, keep typing" — it appears automatically for unfinished { }, ( ), or [ ].

The underscore shortcut

The REPL always keeps the result of the last thing you evaluated in a special variable: _.

> 15 * 3
45
> _ + 5
50

Handy for quick chained calculations without retyping the previous result.

Loading a core module right there

You can require built-in modules directly in the REPL, same as in a file:

> const os = require('os')
undefined
> os.platform()
'linux'

Useful dot-commands

The REPL has a few special commands, all starting with a dot:

  • .help — lists every available REPL command.
  • .clear — wipes out everything you've defined so far, resetting the context.
  • .exit — closes the REPL (you can also just press Ctrl + D, or Ctrl + C twice).
  • .save ./session.js — writes everything you typed in this session out to a file.
  • .load ./session.js — replays a previously saved session back into the REPL.

When it's actually useful

The REPL isn't meant for building applications — it's for the small, fast checks you do dozens of times a day: "does this regex actually match?", "what does this array method return exactly?", "let me just check the syntax for this one thing." Keeping it in your back pocket saves you from creating and deleting a dozen throwaway test files.

Using the Node.js REPL | DevNotes