Getting Started with Node.js REPL

Node.js Read-Eval-Print-Loop (REPL) is an easy-to-use command-line tool, used for processing Node.js expressions. It captures the user’s JavaScript code inputs, interprets, and evaluates the result of this code. It displays the result to the screen, and repeats the process till the user quits the shell.

It is also important to note that this tool does not require file creation to write code. REPL comes ready to use with the Node.js development environment.

A REPL has the following:

  • A read function, which accepts an expression from the user and parses it into a data structure in memory.
  • An eval function, which takes the data structure and evaluates the expression.
  • A print function, which prints the result.
  • A loop function, which runs the three commands above until termination

In this tutorial, we will learn the basics of Node.js REPL and how we can use this amazing tool to run scripts without creating .js files.

1. Prerequisites

This tutorial requires:

  1. Having Node.js installed in your development local machine.
  2. Basic knowledge of JavaScript and Node.js.

2. Objectives

At the end of this tutorial, you should be able to:

  1. Understand the basics of the Node.js REPL tool.
  2. Perform various arithmetic operations.
  3. Create and use functions within the REPL.
  4. Create global variables.

3. Getting started with REPL

Enter the following in the terminal:

node

Output:

> 

Entering the command node in the terminal starts the REPL command-line tool indicated by the > symbol. This symbol acts as an indicator that JavaScript is ready to read and evaluate your code.

We can test the functionality by printing hello world using REPL as shown below:

node
> let hello = 'hello world';
undefined
> hello
'hello world'  // output
> 

In the script, we assign the text hello world to a variable called hello. Now, on calling this variable hello, we get hello world as the output on the command shell. You will also notice that upon pressing ENTER, undefined is printed.

JavaScript functions always return something. If you don’t specify something to return in the function, ‘undefined’ is returned by default. This doesn’t affect anything, you can ignore it.

To exit the REPL, press Ctrl+C on your keyboard.

Output:

> let hello = 'hello world';
undefined
> hello
'hello world'
> 
(To exit, press Ctrl+C again or Ctrl+D or type .exit)
> 

As shown in the output, you can use Ctrl+D or type .exit as well.

4. Executing code using REPL

As discussed previously, this tool simplifies work by providing a quick way to test Node.js code without creating files.

It’s also important to note that any valid JavaScript code can be executed using REPL.

4.1. Performing Arithmetical operations in REPL

In the previous example, we printed hello world string on the screen, in this section let’s dive in and look at arithmetics:

In your terminal, start REPL:

node
> 

Let’s perform basic addition, subtraction, modulus, division and multiplication respectively:

Output:

> 2+2
4
> 5-2
3
> 10%3
1
> 20/2
10
> 10*2
20
> 

4.2. Performing operations using Node.js’s Math library

Math library is an object with defined methods and properties. We can therefore use these features to perform some arithmetics.

Example:

> function getRandomNumber(maximum) {
... let result = Math.random()*maximum;
... return Math.floor(result);
... }
undefined

Output:

> console.log(getRandomNumber(20));
12
undefined
> 

In REPL, we define getRandomNumber(args) and pass it a maximum number. The method uses Math.floor() to return a large random integer less than or equal to a given number.

It’s important to note that Math.random() does not provide secure random numbers. Do not use them on security-related tasks.

4.3. Calling methods (Functions) using REPL

Normally, we write functions to handle specific tasks. REPL provides an easy way to handle these methods. In JavaScript, we commonly use the console.log() global method to print messages.

Let’s enter the following in the prompt:

node
> console.log('Hello world');

Output:

Hello world
undefined # this is the return value of this method, console.log()
> 

When you press ENTER, the output is displayed as shown above.

Next, let’s create a function to add two numbers:

> function addTwoNumbers(firstNumber,lastNumber) {
... console.log(firstNumber + lastNumber)
... }
undefined

We have a function addTwoNumbers(arguments) which takes two arguments, firstNumber and lastNumber. This function, whenever it’s called, logs out the addition of these two numbers.

Output:

> addTwoNumbers(20,40);
60
undefined
> 

We call this method and pass it two parameters, addTwoNumbers(20,40) (you’re free to pass any integer value). By pressing ENTER, the result will be displayed on the screen as shown above.

4.4. Creating variables using REPL

Creating variables works the same as it would in your.js file.

Let’s look at an example:

node
> let name = 'john doe';

Output on calling name and pressing ENTER:

undefined
> name
'john doe'
> 

This variable name will remain active until you exit the REPL window session. This implies that you can even concatenate this string to another.

For instance:

node
> let name = 'john doe';
undefined
> name
'john doe'
> name+ ' is a student at Stanford';
'john doe is a student at Stanford'
> 

5. Conclusion

In this tutorial, we’ve seen how we can use the interactive Node.js REPL tool environment. We have performed various arithmetic operations using REPL.

We also imported the Math library into our REPL environment and accessed several methods to perform arithmetic operations such as generating a random number.

We learned how to create and use various methods and variables in the REPL. We noted that these are defined the same way as they would be in the .js files. We also observed that the variables created remain accessible until the REPL session is terminated.

6. Further reading

You can follow these links to learn more about Node.js REPL:

Happy coding!!

Related posts:

Introduction to hapi.js Framework
Getting Started with EJS Templating Engine
Agora Cloud Recording with Node.js
React To The Future With Isomorphic Apps
Creating A Continuous Integration Test Workflow Using GitHub Actions
Documenting a Node.js REST API using Swagger
Getting Started with billboard.js charts
Using Slack To Monitor Your App
Build a Ticketing App with Adonis.js and Vue.js
React Server Side Rendering With Node And Express
Getting Started with HTTP/2 in Node.js
API Authentication with Node.js
Implementing a GraphQL server using Prisma, SQLite, and Nest.js with Typescript
Why Static Typing & Why is TypeScript so popular?
Creating a Weather app in Node.js using the Openweathermap API
Open-sourced node.js modules at Browserling
Implementing AWS S3 Functionalities on a Node.js GraphQL API
Deploying RESTful APIs using Node.js, Express 4 to Kubernetes clusters
An Absolute Beginner Guide to Node Package Manager
Implementing Lipa na Mpesa Online using Node.js
Building a RESTful API with Adonis.js
Creating Secure Password Flows With NodeJS And MySQL
How to Perform Custom Ranking for Records from a MongoDB Database in Node.js
Introduction to Sequelize ORM for Node.js
Working with Moment.js Date Libraries
Session Management in Node.js using ExpressJS and Express Session
Sharing Code Between Projects: Lessons Learned In The Trenches
Open-source packages & Code Security using NPM
Building A Node.js Express API To Convert Markdown To HTML
Why is Node.js wildly popular among developers?
Node.js vs. PHP – Which is better for Backend development?
Debugging a Node.Js app using Chrome Dev Tools