Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new function using require doesn't return value instead returns "add {}"

//add.js    
    module.exports = function add(a,b) {
    return a+b
    }
//request.js
    var request = require("add.js")
    var request1 = new request('5','5')
    console.log(request1)

this method returns "add {}" instead of 10

like image 948
j.doe Avatar asked Dec 15 '25 02:12

j.doe


2 Answers

You do not need to use new. Remove that and it works:

var request = require("add.js");
var request1 = request('5','5');
console.log(request1);

We use new when we are exporting a class. At that time we use new to create a instance of a class.

//animal.js
class Animal {

}

module.exports = Animal;

//index.js
var animal = require('animal.js');
//creates a instance of animal
var animalObj = new animal();
like image 191
Ankit Agarwal Avatar answered Dec 16 '25 17:12

Ankit Agarwal


You don't need the new keyword.

The new operator creates an instance of a user-defined object type or of one of the built-in object types that has a constructor function.

To achieve the required module import, in order to use this method, you can do the following:

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

// request.js
var add = require("./add.js");

add(5, 5) // 10;

Important In your example you're passing two strings, so the result would yield the following as the + operator will concatenate the values.

add('5','5') // "55"
like image 38
Matt D. Webb Avatar answered Dec 16 '25 18:12

Matt D. Webb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!