Sarun UK
Sarun UK

Reputation: 6746

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

Upvotes: 1

Views: 944

Answers (2)

vkstack
vkstack

Reputation: 1644

Javascript does not support function overloading. Although robertklep 's solution is great. There is one more way you can use.That is arguments object.

arguments is very good when you have unknown number of parameters to be passed into the function. see more here.

Below is how will it look.

//add.js
function add() {
  var args=Array.prototype.slice.call(arguments);
  console.log(arguments);
  console.log(args);
  console.log("------Starts x+y+z+.....and so on----");
  var ans = args.reduce(function(prev,curr){return prev+curr;});
  console.log(ans);
  return ans;
}
var sum = add(1,8,32,4);
module.exports = add;//to make it available outside.

On executing the above.(as node add.js),The output is as follows.

{ '0': 1, '1': 8, '2': 32, '3': 4 }
[ 1, 8, 32, 4 ]
------Starts x+y+z+.....and so on----
45

Upvotes: 1

robertklep
robertklep

Reputation: 203359

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;
  ...
}

Upvotes: 5

Related Questions