Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does require('underscore') return undefined when executed at the node.js REPL?

When I run node in my console and type var _ = require('underscore');, _ ends up undefined. If I put the same code in a file and execute it, the underscore library gets included as expected.

$ node
> var _ = require('underscore');
> console.log(_)
undefined // underscore library does not load
> var async = require('async');
undefined
> console.log(async) // async library does
{ noConflict: [Function],
  nextTick: [Function],
  forEach: [Function],
...
>

But the same code in a .js file executed as node test.js shows both libraries loading as expected. What's going on?

like image 660
jches Avatar asked May 22 '12 23:05

jches


People also ask

What is the use of underscore variable in REPL session in node JS?

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 does undefined mean in node JS?

undefined , in this context, means the statement doesn't have anything to return.

How do I run a REPL session in Nodejs?

Starting the REPL is simple - just run node on the command line without a filename. It then drops you into a simple prompt ('>') where you can type any JavaScript command you wish. As in most shells, you can press the up and down arrow keys to scroll through your command history and modify previous commands.

How do I get out of node REPL?

To exit from the REPL terminal, press Ctrl + C twice or write . exit and press Enter.


1 Answers

The Node repl binds _ to the value of the last evaluated input; which overwrites your _ binding in var _ = ...;. Also see the node.js documentation on the repl.

This is true no matter what replaces ..., for example:

$ node
> var _ = "any value";
undefined
> _
undefined
like image 82
Dan D. Avatar answered Oct 18 '22 20:10

Dan D.