Node js REPL

Learn via video courses

Overview

REPL is an abbreviation for Read Evaluate Print Loop, which is a programming language environment (essentially a console window) that accepts a single expression as user input, executes it, and returns the result to the console after execution. The REPL session allows you to quickly test and execute basic JavaScript programmes. Independent parts of code can be tested on REPL easily.

Prerequisites

  • Node.js must be locally installed in your system.
  • Basic knowledge of javascript.

Introduction

Node.js is a server-side Javascript run-time environment that is open source and based on Chrome's JavaScript Engine (V8). Node.js is based on an event-driven, non-blocking I/O architecture that can be used for constructing fast and scalable applications.

REPL (READ, EVAL, PRINT, LOOP) is a command-line environment equivalent to Shell in Unix/Linux. Node comes with the REPL environment when it is installed. The system communicates with the user by displaying the results of instructions executed by it. It is handy for both the development and debugging processes. All the parts of REPL have a specific task.

  • Read: The input provided by the user is read. After necessary parsing, the information is saved in the memory.
  • Eval: The data structure with the parsed information is evaluated, and a result is generated.
  • Print: The result generated after the evaluation is displayed to the user.
  • Loop: All the above three steps are looped until the user presses ctrl+c twice to get out of the loop.

The REPL comes with every Node.js installation and allows the instant testing and exploration of the JavaScript code without any need to save it in a file.

REPL Environment

The repl.REPLServer class is exported by the node:repl module. When repl.REPLServer instances are running, they will take individual lines of user input, evaluate them using a user-defined evaluation function, and print the result. Input and output can come via stdin and stdout, respectively, or from any Node js stream.

Repl.REPL Server instances include features such as multi-line inputs, automatic input completion, ANSI-styled output, completion preview, simplistic Emacs-style line editing, ZSH-like reverse-i-search, saving and restoring current REPL session state, ZSH-like substring-based history search, error recovery, and customizable evaluation functions.

How To Use the Node.js REPL?

Step 1 — Starting and Stopping the REPL

If Node.js is installed in your system, then REPL is also present automatically. We use the node command to launch our Node.js scripts. You can start REPL by typing node on the shell/console without any arguments, as shown below.

This results in the REPL prompt :

The command remains in standby mode, waiting for us to enter anything. The > symbol indicates that you can insert JavaScript code. Any code entered is instantly evaluated.

For example, try writing any mathematical expression in the REPL like this.

On pressing Enter, the expression gets evaluated and the output is displayed :

To leave the REPL, type .exit or hit CTRL+D once or press CTRL+C twice. All these will make you exit the REPL and return to the shell prompt.

Now that you have seen how you can enter and exit the REPL, let's look at how you can utilize the REPL to execute simple JavaScript code.

Step 2 — Executing Code in the Node.js REPL

The REPL allows you to quickly test and evaluate JavaScript code without the need to save the code in a file. In the REPL, any kind of javascript or Node.js expression that does not contain any error can be executed easily.

Node.js Simple expressions:

You have already seen an addition operation, and you can try any other mathematical and boolean operation and checkout the output. Here are a few examples:

In the above expression, three strings have been concatenated, and the final result has been returned.

The above expression is a boolean expression that uses the === operator that compares both value and type.

Above is an arithmetic expression evaluated according to BEDMAS.

Hence the simple expressions written in javascript can be easily evaluated using Node.js REPL.

Calling Functions:

You can also call any function from the REPL. The function can be predefined or user-defined. In javascript, console.log() is commonly used to print messages in the console. You can also easily print messages with the help of console.log() in the REPL.

When writing Node.js code, it’s common to print messages via the global console.log method or a similar function. Type the following at the prompt :

Pressing ENTER key gives the following output:

The console.log() function prints the message passed in it to the stdout stream. Because console.log() outputs a string rather than returning a string, the message is shown without quotes. The undefined is logged because console.log() returns undefined.

Creating Variables:

You can store values in the variables and use them later. if the var keyword is used, the value is stored but not printed, however, If the var keyword is not used, the value is stored in the variable and printed. You can use console.log() to print the value of variables. You can create variables in the same way as in the .js files. Let's take a look at some examples :

On Pressing ENTER :

The return value of the above command is also undefined. The val variable can be used until the REPL session is not closed. For example, you can multiply val by five. As shown below

The result is:

By default, all the returned values are printed in the REPL and you are not required to use the console.log() function to print them.

Multi-line Blocks:

Multi-line code blocks are also supported in REPL. You can define functions easily with the help of multiline support. Take an example of a sum function that adds two numbers.

After pressing enter in the first line, the next line will have instead of >. The Node REPL is intelligent enough to recognize when you haven't finished writing your code and will switch to a multi-line mode to allow you to enter additional code.

Because the REPL observed an open curly bracket, it makes an assumption that you are writing multi-line of code, which must be indented. The REPL inserts three dots and a space to the next line to indent the following code.

Now you can enter the rest of the lines of the code similarly.

Now after closing the curly brace, when you will press the enter key, undefined will be printed as the return value of the function’s assignment to a variable and this time > will return as shown :

Now, you can call the sum() function with two numbers as the arguments :

The next line will have the output of the above function call as follows :

You may utilize the REPL for the testing of your Javascript codes before adding them to your projects. The REPL also contains several useful shortcuts to help with this procedure.

Underscore Variable:

In the above code, the first time _ is used, the value returned is undefined as there was no previous output.

Now, if a variable is defined, we get the return value as undefined. Hence the second time _ is used, we get undefined again.

Now when the value of x is printed, it gets stored in _. Hence the next _ gives 10.

Now again, a variable was defined; hence the fourth _ got undefined.

Now, as the value of y is returned hence the fifth time, _ gets the value 5.

Now the sixth time, _ gets the value of x+y, which is 15.

Step 3 — Mastering REPL Shortcuts

There are some shortcuts provided by the REPL to reduce the time required to write commands wherever possible. The history of all the commands executed in the session is saved by the REPL, and we can go through them and reuse any command. For example, if you have written the following as a command previously :

Its output will be :

Now, if you would like to add the fourth word, then press the UP arrow instead of writing the whole statement until you get the previous statement written automatically. Now you can change the statement and execute it again.

It will give :

Hence to get a previously executed command, you can cycle through the command history using the up and down arrow keys and get the command without the need to rewrite it.

Autocompletion for functions, variables, and keywords is also available in the REPL. Like if you want to use the Math.round() function to calculate the nearest integer to a given value, then you can write the following.

Then, using the TAB key will make REPL automatically complete the function :

In case of multiple possibilities for a given phrase. For example, write :

And press TAB twice. You will be shown several possible autocompletion :

The result may be shown with a varied number of rows and columns depending on the size of your shell's screen. The suggestions contain the complete list of all the functions and attributes accessible in the Math module.

Knowing the various shortcuts in REPL allows you to use REPL more efficiently. Here is a list of some other useful shortcut keys :

CommandsDescription
up/down keysIt is used to see command history and modify previous commands.
ctrl + dIt terminates the node repl.
ctrl + cIt is used to terminate the current command.
ctrl + c twiceIt terminates the node repl.
tab keysIt specifies the list of the current command.

Step 4 — Using REPL Commands

The behavior of the REPL can be controlled by these commands. A . dot is used at the start of each command.

  • .help :

The .help command gives a list of all the other commands and their uses. For example, write the following:

Press Ctrl+C to abort the current expression, Ctrl+D to exit the REPL

The list of commands is not very large but these are very handy in doing certain tasks. You can always make use of the .help command whenever you forget any certain command in REPL.

  • .break/.clear:

Any multiline code block can be exited with the help of .break or .clear. For example, here is a for loop with a certain number of iterations. Write the first line as shown in the REPL

After pressing the Enter key, in the next line to stop continuing writing the multiline code you can use either .clear or .break as follows :

Now the next line will prompt > instead of ...:

Here is the complete sequence of execution :

This operation is similar to CTRL+C, the control moves to the next line and no codes are executed.

  • .save and .load:

All the code saved in the history by the REPL can be stored in a .js file with the help of the .save command.

The .load command does the reverse of this. It executes the code present in the .js file. The code is shown in the REPL along with its output. Start a new session in REPL by the node command in the terminal and write a sequence of commands as shown below :

The above code contains two variables and a command containing their sum. Executing the .save command gets the code saved to the script.js file. Now your script.js file will contain the following code :

The file will be saved in the directory in which you started the REPL session or in other words the directory open in the terminal where REPL is running.

Now exit the session with the .exit or CTRL + D command and try to use the .load command to run the code saved in the script.js file. Start a new REPL session in the same directory and write the following code in it :

This will show the following result :

The .load command reads every line of the code file one by one and executes it as a javascript interpreter does. Now all the variables used in the code file can be accessed in the session, and their values will also be the same as before.

The .load command can be used to run any code file that contains javascript. For example, create a .js file with the name demo.js and write the following code in it :

The demo.js file contains the code to print the multiplication table of 5. Now execute the following code in the Node.js REPL :

The above output will be received when the code of the demo.js file will be executed. When your REPL use exceeds your expectations, or you feel you have an intriguing code snippet worth sharing or exploring further, you may use the .save and .load commands to accomplish both of these purposes.

Performing Arithmetical Operations in REPL

Arithmetic operations can be performed very easily in the REPL Node.js. You can write the expression in the REPL and pressing the Enter key will get the evaluated result.

Here are some examples of performing arithmetic operations :

Start a REPL session and execute the following arithmetic operations :

This is a simple addition of two numbers.

This is a simple multiplication of two numbers.

The ** operator is used to return the result of raising the first operand to the power of the second operand.

Here is an expression involving several arithmetic operators.

Here is another expression that involves parenthesis also.

The arithmetic operations are executed as per the BEDMAS rule. According to BEDMAS, brackets are the most important, followed by exponents, division, and multiplication, and finally addition and subtraction. Hence the arithmetic operations can be evaluated easily in the REPL node.js .

Using Variables in REPL

You can define a variable in the REPL in the same way as you do in a javascript file. A variable can be defined using either var, let or const.

Var declarations are globally, or function scoped, whereas let and const declarations are block scoped. Within their scope, var variables can be changed and re-declared. let variables can be modified but not re-declared. and const variables cannot be changed or re-declared. When the var, let, and const are used then the value is not printed because undefined is returned by the assignment operation. But if they are not used the value is returned.

Conclusion

  • REPL is an abbreviation for Read Evaluate Print Loop, which is a programming language environment that accepts a single expression as user input, executes it, and returns the result to the console after execution.
  • You can start REPL by typing node on the shell/console.
  • The REPL allows you to quickly test and evaluate JavaScript code without the need to save it in a file.
  • There are some shortcuts provided by the REPL to reduce the time required to write commands wherever possible.
  • The behavior of the REPL can be controlled by certain commands like .break, .clear, .help, etc.
  • You can write the arithmetic expression in the REPL and pressing the Enter key will get the evaluated result.
  • You can define a variable in the REPL in the same way as you do in a javascript file.