Sarun UK Sarun UK - 3 months ago 20
Node.js Question

Overloaded function call in nodeJS

I have two js files add.js and testAdd.js

add.js



module.exports = function add(x,y) {
console.log("------Starts x+y----");
var a = x+y;
console.log(a);
return a;
}

module.exports = function add(x,y,z) {
console.log("------Starts x+y+z----");
var a = x+y+z;
console.log(a);
return a;
}


testAdd.js



var add = require('./add');

add(300,100);

add(300,100,233);


From the testAdd I am calling the add method in the add.js

What is happening is function call is always going to the add(x,y,z) as function is not selecting based on the parameters(as in java).

I am new to nodeJS. Can someone help me to understand this flow?
And also help me to fix this issue. Thanks in advance.

Attaching the console o/p:-

enter image description here

Answer

JavaScript doesn't have function overloading. If you want to have your function take an optional third argument, you can set a default value (with a recent Node version):

function add(x, y, z = 0) {
  ...
}

You can use it with two (add(300, 100)) or with three (add(300, 100, 233)) arguments.

If you don't have a recent enough Node version, you have to do some manual validation on the third argument:

function add(x, y, z) {
  z = Number.isFinite(z) ? z : 0;
  ...
}
Comments