Understanding NodeJS REPL

Understanding NodeJS REPL

The Node.js REPL (Read-Eval-Print-Loop) is an interactive programming environment that reads input code, parses and executes it, and prints the result, allowing users to try out small pieces of code and address issues in a debugger.

Full form of REPL is given below:

Read - Reads user's input, parses the input into JavaScript data structure, and stores it in memory.

Eval - Takes and evaluates the data structure.

Print - Prints the result.

Loop - Loops the above command until the user presses ctrl-c twice.

Using REPL in VS Code Terminal

  • To use the Node.js REPL, type "node" into a command-line interface like PowerShell or Terminal, and you should see a ">" prompt. Anything typed after this prompt will be parsed and executed as JavaScript.

       node
    
  • The REPL tool is included with Node.js and is a way to interactively run JavaScript and see the results immediately.

Actions that can be performed using REPL

NodeJS REPL can be used to do the following tasks:

  1. Mathematical Expressions: It can be used to evaluate mathematical expressions.Here's an example of evaluating JavaScript expressions in the Node.js REPL:

     >1+1
     2
     >10*5
     50
    
  2. Exposing Variables to the REPL: It is possible to expose a variable to the REPL. Here's an example:

     > const msg = 'message';
     > msg
     'message'
    
  3. Multiline Code: Multi-line Javascript code can also be written using the NodeJS REPL.

     > var x=5;
     undefined
     > x
     5
     > for(var i=0; i<x; i++){
     ... console.log("Node REPL");
     ... }
     Node REPL
     Node REPL
     Node REPL
     Node REPL
     Node REPL
     undefined
     >
    
  4. Fetch Last Result: To fetch the last result in the Node.js REPL, you can use the _ variable. This variable holds the result of the last operation in the REPL. Here is an example:

     > 2 + 2
     4
     > 'hello'
     'hello'
     > _
     'hello'
    
  5. Entering Editor Mode: To enter editor mode in the Node.js REPL, you can use the .editor command. This command allows you to write JavaScript code that goes beyond one line directly in the REPL. Write your code in the editor and save it by pressing Ctrl + D on a new line when you're done.

     $ node
     > .editor
     // Entering editor mode (^D to finish, ^C to cancel)
     function greet(name) {
       console.log(`Hello, ${name}!`);
     }
     greet('Abhinav');
     // Press Ctrl + D to save and exit editor mode