a blog for those who code

Friday 27 June 2014

Use of Underscore (_) in Nodejs

This post will help you to understand the use of Underscore (_) in Nodejs. To access the last expression, we have to use the (_) underscore/underline character.
Lets take an example,

> x = 2;
2
> _ --;
1

In the above code we have first assigned 2 to 'x' and then we have used ' _ -- ' to actually get the last expression and decremented it by 1.

> ['a','b','c']
['a','b','c']
> _.length
3

From the above code we can see that it actually access the full last expression rather than a value of it.

Suppose accidently you have used something like

> var a = 2;
undefined
> _--

Then you will get NaN because the result of 'var a = 2' expression is undefined as a variable assignment doesn't return a result when evaluated. So when you are accessing the last expression you will get NaN.

Please Like and Share the Blog, if you find it interesting and helpful.

3 comments:

  1. Maybe you can help me with this then?

    I am working through the "stream adventure" on nodeschool and I am looking at the through2 facility. The suggested answer uses this syntax. Notice the function arguments passed to through2. What is the "last expression" here? the value the value that split() has put out would be 'line', so what does the '_' refer to?

    thanks !

    var split = require('split');
    process.stdin
    .pipe(split())
    .pipe(through2(function (line, _, next) {
    console.dir(line.toString());
    next();
    }))
    ;

    ReplyDelete
  2. The special '_' variable that refers to the last expression only exists in the Node REPL, calling "console.log(_)" in a regular Node problem would say "variable undefined".

    In your case the '_' is just a variable name like 'line' or 'next'. It's a convention (borrowed from Erlang) to say we don't care about the value of that argument. Since it's an actual variable, you could could still refer to it using '_' though.

    ReplyDelete
  3. so is it optional then? would "through2(function (line, next)" function the same way? because saying "we don't care" is different than saying nothing at all is it not?

    ReplyDelete