35

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'
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
JulyMorning
  • 531
  • 1
  • 4
  • 8
  • https://nodejs.org/docs/latest/api/repl.html#repl_assignment_of_the_underscore_variable – Bergi Sep 26 '17 at 07:42
  • See also [In the Node.js REPL, why does this happen?](https://stackoverflow.com/q/17073290/1048572) – Bergi Sep 26 '17 at 07:43

2 Answers2

29

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

> 1 + 2
3
> _
3
Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
  • 12
    Wow, what a wildly unexpected behavior. – canon Sep 25 '17 at 22:03
  • 19
    This happens ***only*** in the REPL (interactive console), and it is [fully documented](https://nodejs.org/api/repl.html#repl_assignment_of_the_underscore_variable). In normal code, the underscore is just another variable identifier. – josh3736 Sep 25 '17 at 22:13
  • 8
    @canon, I once had a professor who, after filling a board with equations, said "and so obviously-" and began filling a second board. I held up my hand. "Dr. Goldman, are you sure it's obvious?" This stopped him. He stared silent at his own work for a good minute. "Yes," he concluded. "It's obvious." When I saw this question in the sidebar, I thought, "It probably means the result of the last expression." – Michael Lorton Sep 25 '17 at 23:54
  • 6
    This is not wildly unexpected-- in fact, it's not even unique to node.js or even JavaScript. It's in Python and Ruby interactive environments and probably even more languages that I haven't used. – Yet Another User Sep 26 '17 at 00:06
  • 1
    @YetAnotherUser I think this might have originated with Perl. – Bob Sep 26 '17 at 01:31
  • 4
    "This is not wildly unexpected" - all sigils are wildly unexpected. For example, if instead it were `__previousResult__` then this question never would have been asked. – aaaaaa Sep 26 '17 at 03:12
15

_ 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
Karol Selak
  • 4,248
  • 6
  • 35
  • 65