Sarun UK Sarun UK - 1 year ago 185
Node.js Question

Overloaded function call in nodeJS

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


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

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


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



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 Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download