JulyMorning
JulyMorning

Reputation: 531

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'

Upvotes: 35

Views: 13905

Answers (2)

Karol Selak
Karol Selak

Reputation: 4774

_ 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

Upvotes: 15

Madara's Ghost
Madara's Ghost

Reputation: 174977

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

> 1 + 2
3
> _
3

Upvotes: 29

Related Questions