'Undefined' output when requiring modules

时间:2016-04-15 15:09:46

标签: javascript node.js

test.js

var foo = require('./foo');
var bar = require('./bar');
console.log(foo());
console.log(bar());

foo.js

module.exports = function() {
    console.log('In foo.js');
};

bar.js

module.exports = function() {
    console.log('In bar.js');
};

After running test.js in NodeJS I get this:

 In foo.js
 undefined
 In bar.js
 undefined

Where do two 'undefined's come from?

2 个答案:

答案 0 :(得分:3)

console.log(foo());
console.log(bar());

Here foo() and bar() are not returning anything that is why it is logged as undefined.

答案 1 :(得分:3)

A function with no return statement will return undefined.

You are logging the return value of foo() and bar(), each of which has no return statement.