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'
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.
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.
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.
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.
_
in the node console returns the result of the last expression.
> 1 + 2
3
> _
3
_
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With