Just like any other language, JavaScript with the help of the NodeJS runtime provides a REPL interface that can be accessed by running node
from the command line without any scripts.
REPL is an acronym that stands for Read Evaluate Print Loop
- Read - Reads user's input or expression then goes on to parse it into JavaScript data-structure and stores in memory.
- Evaluate - It accepts and evaluates the data-structure.
- Print - Prints the result.
- Loop - Loops the command until the user exits by pressing ctrl-c or ctrl-d twice. The loop terminates when the program is closed.
A REPL allows you to write snippets of code and to get immediate results as each statement is written and executed. it serves many purpose such as running simple tests or even debugging.
By running the node
command, we start a REPL session in the terminal.
node
By clicking the enter key, this is what appears on our terminal
❯ node
>
the >
is the REPL command prompt where you can type any Node.js command and it stays in idle waiting for us to enter something.
Don't know how to open your terminal on your operating system? click here
At this point, the REPL is waiting for us to enter some JavaScript code.
Simple Expression
Let's try a simple mathematical expression
❯ node
> 4 + 5
9
> 2 + (3 * 4) - 5
9
>
Using Variables
Since variables are used to store values and print later like any conventional script. If var keyword is used, then the value is stored but not printed but if the var keyword is not used, then the value is stored in the variable and printed. You can print variables using console.log()
❯ node
> x = 5
5
> var y = 10
undefined
> x + y
15
>
❯ node
> console.log('Hello World')
Hello World
undefined
>
The value, Hello World
is the output we told the console to print, then we get undefined
which is the return value of running console.log()
. Node read this line of code, evaluated it, printed the result and then went back to waiting for more lines of code, hence >
.
Node will loop over these three steps for every piece of code we execute in the REPL until we exit the session. Wondering where the name REPL was gotten? there you have it.
If you have been following, you will notice node automatically prints the result of any line of JavaScript code without the need to instruct it to. Here is an example to try out and press enter:
❯ node
> 3 === '3'
false
>
The difference between the last two outputs we got is that the former is a JavaScript statement so the node REPL printed undefined
after executing console.log()
while the latter is a JavaScript expression so it printed the result of 3 === '3'
Multi-line Blocks
Multi-line blocks of code are supported as well, for example, lets create a function that adds 5 to a given number.
const add5 = (num) => {
Once we hit enter
, the prompt changes to
...
The REPL noticed an open curly bracket and assumes we are writing more than a line of code, which needs to be indented. For easy readability, the REPL adds 3 dots(ellipsis) and a space so the code appears to be indented.
Proceed by hitting enter
after every completed line of code.
... return num + 5;
... }
Pressing enter
after the closing curly bracket will display an undefined
which is the "return value" of the function assignment to a variable. Then, notice the ...
prompt is gone and replaced back with the >
prompt.
... }
undefined
>
Now, call add5()
on a value:
> add5(10)
15
>
As expected, the output is 15
REPL Shortcuts
The _ special variable
If after some code, you type _
, it is going to print the result of the last operation.
> _
The Up arrow key
if you press the up
arrow key, you get access to the previous lines of code in the current and even the previous REPL sessions.
For example, enter the string:
> "I will graduate summa cum laude in 2023"
This results in:
'I will graduate summa cum laude in 2023'
If you'd like to edit the string and change the "2023" to "2024" due to something like a school strike or you deferred, at the prompt, use the UP
arrow key to return to the previous command:
> "I will graduate summa cum laude in 2023"
Move the cursor to the left, delete 3
, enter 4
, and press the enter
again
'I will graduate summa cum laude in 2024'
If you keep pressing the UP
arrow key, you'll go further back through your history until your first used command in the current REPL session. In contrast, pressing DOWN
will iterate towards the more recent commands.
When you are done editing previous strings in the command history, press DOWN
repeatedly until you've exhausted your recent command history and seeing the prompt >
once again.
Autocompletion
The REPL being interactive makes it much easier to work with. For example, lets say you want to find the square root of a particular number using the Math.sqrt
function, enter the first few letters like i have below:
> Math.sq
Then hit the TAB
key and the REPL autocompletes the function for you:
> Math.sqrt
In some cases, there are multiples possibilities for autocompletion, you're prompted with the every available options. For example, enter just Math.
and press TAB
twice, and it presents us the possible autocompletions.
> Math.
Math.__proto__ Math.constructor Math.hasOwnProperty Math.isPrototypeOf Math.propertyIsEnumerable Math.toLocaleString
Math.toString Math.valueOf
Math.E Math.LN10 Math.LN2 Math.LOG10E Math.LOG2E Math.PI
Math.SQRT1_2 Math.SQRT2 Math.abs Math.acos Math.acosh Math.asin
Math.asinh Math.atan Math.atan2 Math.atanh Math.cbrt Math.ceil
Math.clz32 Math.cos Math.cosh Math.exp Math.expm1 Math.floor
Math.fround Math.hypot Math.imul Math.log Math.log10 Math.log1p
Math.log2 Math.max Math.min Math.pow Math.random Math.round
Math.sign Math.sin Math.sinh Math.sqrt Math.tan Math.tanh
Math.trunc
The screen size of the shell determines the number of rows and columns displayed as an output. It contains the list of all the functions and properties that are available in the Math
module.
You can press CTRL+C
to go to a new line in the prompt without executing what is in the current line.
Knowing the REPL shortcuts is good but so is knowing the REPL commands.
Using REPL Commands
To control the REPL behavior, we use specific keywords and each command begins with a dot .
which is something they have in common.
.help
The .help
command lists all available commands.
> .help
.break Sometimes you get stuck, this gets you out
.clear Alias for .break
.editor Enter editor mode
.exit Exit the REPL
.help Print this help message
.load Load JS from a file into the REPL session
.save Save all evaluated commands in this REPL session to a
file
Press Ctrl+C to abort current expression, Ctrl+D to exit the REPL
>
.clear/.break
Using .clear
or .break
is to exit from a multiline expression. Lets use a for loop
as a case study:
for (let i = 0; i < 10000; i++) {
To exit from inputting any more line of code, we can use the .break
or .clear
to break out:
.break
Then we get back the prompt
>
This is similar to using the CTRL+C
because we just made the REPL move to the next line without executing any line of code.
.save and .load
The .save
command stores the codes you ran since starting the REPL into a file and the .load
command runs all the JavaScript code from a file inside the REPL.
You can decide to quit the session by simply using the .exit
command or with the CTRL+D
shortcut.
Let's practice with an example 😃 Create an array with countries:
> countries = ['Nigeria', 'Canada', 'France']
In the next line, the REPL displays:
[ 'Nigeria', 'Canada', 'France' ]
Lets then save to a new file, countries.js
:
> .save countries.js
we're greeted with the confirmation:
Session saved to: countries.js
But note that, the file is saved in the same directory where you opened the Node.js REPL. For example, if you opened the Node.js REPL in your home directory, then your file will be saved in your home directory.
You can choose to exit the current session and start a new REPL with node
. Also, at the prompt, load the countries.js
file by entering:
> .load countries.js
This results in:
countries = ['Nigeria', 'Canada', 'France']
[ 'Nigeria', 'Canada', 'France' ]
Clearly, the .load
command reads each line of code and executes it which is what is expected of a JavaScript interpreter. You can then go ahead and use the countries
variable as if it was available in the current session.
Type the following command and hit ENTER
> countries[2]
The REPL will output:
'France'
Conclusion
The REPL is an interactive environment that allows you to execute JavaScript code without first having to write it in a file. And when we run a command line without any script, we start a REPL session.