Node.js REPL: Read, Evaluate, Print, Loop
Ever needed to prototype or debug JavaScript without creating files? The Node.js REPL lets you:
- Instantly run snippets
- Explore APIs interactively
- Debug in real time
It operates in four steps:
- Read your input
- Evaluate the code
- Print the result
- Loop back for more
Prerequisites
- Node.js installed
Getting Started
Start & Exit
You'll see:
Exit by:
.exit
- Ctrl+D (once)
- Ctrl+C (twice)
Try Simple Expressions
Variables & Functions
> let x = 10
undefined
> x * 2
20
> function sum(a, b) {
... return a + b;
... }
undefined
> sum(3, 4)
7
Special “_” Variable
The underscore _
stores the last result:
Multi‑line Mode
When you enter an incomplete statement, REPL switches to multi‑line:
REPL Shortcuts & Commands
Shortcuts:
- Up/Down arrows: Browse history
- Tab: Auto‑complete
- Ctrl+C: Cancel current input
- Ctrl+D: Exit
Built‑in commands (start with .
):
Command | Description |
---|---|
.help | Show help |
.break/.clear | Abort multi‑line input |
.editor | Enter editor mode |
.save |
Save session to <file> |
.load |
Load and run <file> |
.exit | Exit REPL |
Save & Load Example
In a new session:
Summary
- Launch with
node
. - Use REPL for quick feedback.
- Leverage
.help
,.save
,.load
. - Navigate with arrows and Tab.
- Harness
_
for the last result.
Global Objects in Node.js
What Is the Global Object?
In JavaScript, the global object holds values available everywhere.
- Browsers: window
- Node.js: global
or standardized globalThis
Browser vs. Node.js
Browser:
Node.js:
Common Globals in Node.js
Module Scope vs. Global Scope
Each file is its own module. Top‑level let
, const
, or var
stay local:
To share, attach to global
or export via module.exports
.
Using globalThis
globalThis
works uniformly across environments:
Best Practices
- Avoid polluting the global namespace.
- Prefer module exports/imports over globals.
- Use
process.env
for configuration. - Reserve globals for universal utilities (e.g., polyfills).