0

I am learning JavaScript / Node.js. Looking at bot.js from botkit-starter-web line 33, it shows:

var db = require(__dirname + '/components/database.js')({});

My question is, what is ({}) represent in that line? I can't Google the answer for it.

Jabongg
  • 2,099
  • 2
  • 15
  • 32
Hadi
  • 19
  • 3
  • 14
    Presumably, the `require` returns a function, which is then called with an empty object. – CertainPerformance Jan 15 '19 at 09:32
  • If you look at the [file](https://github.com/howdyai/botkit-starter-web/blob/master/components/database.js) you can see the function: `module.exports = function(config) { ... }` The parameter `config` is never used, so you can pass whatever. The author decided to pass an empty object literal. –  Jan 15 '19 at 09:34
  • All your comments are super helpful, thank you for helping me! – Hadi Jan 17 '19 at 02:58

3 Answers3

4

require(...) is used to load a module, the return value of require is the module, which can be any javascript value (depends on the module being loaded).

In this case it is presumed to be a function.

Adding ({}) is calling that function and passing an empty object {} as the first and only argument.

The return value of that function call, being stored in the variable db.

It is equivalent to doing this:

var database = require(__dirname + '/components/database.js');
var db = database({});
Austin France
  • 2,381
  • 4
  • 25
  • 37
0

At the first you know in database.js exists this code :

module.exports = function (object) {
  // . . .
  // some thing on object
  return object;
};

when you require this JS file you can send to above function object data (empty or not empty)

var db = require(__dirname + '/components/database.js')({});
mohammad javad ahmadi
  • 2,031
  • 1
  • 10
  • 27
0

When a module is loaded ( In other words load a javascript file using require(..) ), it returns whatever is assigned to module.exports, for example

    //javascript file add.js 
      module.exports = function(a,b){
        return a+b;
      }

    //Usage in app.js
      var add = require("add.js");
      var result = add(2+2);//result would be 4
    //Similarly 
      var result = require("add.js")(2+2);//result would be 4

In your case database.js returns a function in its module.exports and that function takes one paramter which is an object.

var db = require(__dirname + '/components/database.js')({});

In the above snippet you are passing an empty object to the function.The creators of database.js have given you options to customize some values, something like this

var db = require(__dirname + '/components/database.js')({
   port:3306,
}); 
//or 
var options = {};
options.port = 3306;
var Database = require(__dirname + '/components/database.js')
var db = Database(options);
Madan
  • 31
  • 4