Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the "_" (underscore) symbol in Node.js REPL mean?

I was playing in Node.js with some code when I noticed this thing:

> 'hello world'.padEnd(20);
'hello world         '
> 'hello world'.padEnd(20, _);
'hello worldhello wor'

What does the underscore symbol do here?

> _
'hello worldhello wor'
like image 604
JulyMorning Avatar asked Sep 25 '17 22:09

JulyMorning


People also ask

What does __ mean in node?

Double underscore (__) in front of a variable is a convention. It is used for global variable (The following variables may appear to be global but are not, rather local to each module) in Nodejs meanwhile Underscore(_) used to define private variable.

What is underscore in 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.

What is the use of underscore in node JS?

Underscore. js is a utility library that is widely used to deal with arrays, collections and objects in JavaScript. It can be used in both frontend and backend based JavaScript applications. Usages of this library include filtering from array, mapping objects, extending objects, operating with functions and more.

What does __ do in JavaScript?

The dollar sign ($) and the underscore (_) characters are JavaScript identifiers, which just means that they identify an object in the same way a name would.


2 Answers

_ in the node console returns the result of the last expression.

> 1 + 2
3
> _
3
like image 57
Madara's Ghost Avatar answered Oct 22 '22 21:10

Madara's Ghost


_ symbol returns the result of the last logged expression in REPL node console:

> 2 * 2
4
> _
4

As written in documentation, in 6.x and higher versions of node this behavior can be disabled by setting value to _ explicitly:

> [ 'a', 'b', 'c' ]
[ 'a', 'b', 'c' ]
> _.length
3
> _ += 1
Expression assignment to _ now disabled.
4
> 1 + 1
2
> _
4

But in older versions that feature doesn't work:

> [ 'a', 'b', 'c' ]
[ 'a', 'b', 'c' ]
> _.length
3
> _ += 1
4
> 1 + 1
2
> _
2
like image 15
Karol Selak Avatar answered Oct 22 '22 21:10

Karol Selak