Open In App

What is the use of underscore variable in REPL ?

Last Updated : 30 Nov, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In the previous Node.js REPL post, we’ve discussed what is Node.js REPL and how to use it on your command prompt. We’ve also discussed how to perform arithmetical operations, how to use node library functions, and how to use loops in REPL. In this article, we’re going to discuss what is the use of the underscore (_) variable in Node.JS REPL. 

Underscore Variable in REPL: The underscore variable in REPL is a special variable that is used to store the result of the last evaluated expression. That means you can access the result of the last expression using this variable. Let’s see an example to have a better understanding. 

Step 1: To start the REPL environment, open your terminal and write node. You’ll see the following screen.

Node REPL

REPL Environment

Step 2: Now, Evaluate any expression e.g, 4 + 7. You’ll get 11 on the screen as expected. Now just give an underscore and hit enter. You’ll again see 11. Since 11 was the result of the last expression that’s why the underscore _ variable returned 11. 

Evaluation of 4+7 in REPL

Step 3: Let’s evaluate another expression 3*6-4. Again type underscore and see the result. You can evaluate any expression. Go ahead and try to evaluate some expressions. 

Step 4:  Underscore variable is not limited to maths expressions only. You can store the result of any data type. Here’s an example with string. 

Underscore with String

Note:

  1. If we try to access the underscore variable just after starting the REPL, we will get the result as undefined.
  2. Explicitly setting any other value for the underscore variable will disable this behavior. This is only applicable in node version 6.x and above.

Disabled Underscore Feature


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads