1

I am trying export all the overloaded functions of a js file. So that I can reuse them in other js files. But, whenever I am trying to call any function.then the highest parameterized function is getting called every time.

reusefun.js

exports.getMessage = function(val1) {
   return val1;
}
exports.getMessage = function(val1,val2) {
   return val1+ " " +val2;
}
exports.getMessage = function(val1,val2,val3) {
   return val1+ " " +val2+ " " +val3;
}

Suppose I am using this file like below

myfile.js

const re = require('./reusefun);
console.log(re.getMessage("a"));

Then getMessage(val1,val2,val3) is getting called instead of getMessage(val1) .

Sritam Jagadev
  • 955
  • 4
  • 18
  • 46
  • Javascript doesn't really do function overloading like that. You'll have to write your own overloading logic into a single function – TKoL Dec 16 '19 at 12:12
  • js does not support overloaded functions, here you are replacing `getMessge(val1)` with `getMessage(val1,val2,val3)` – angrykoala Dec 16 '19 at 12:12
  • In this particular case, you can use `[a,b,c].join(' ');` to achieve the same result. If you're curious about rolling your own overloading logic for dealing with a variable number / type of parameters, then that's an interesting question in its own right – TKoL Dec 16 '19 at 12:13
  • In your code you are not overloaded your function you are just assign the property getMessage again and again and the last assign property is remain that's why it always calls the highest parameter function assign the function which accept two params at the end then it always calls that function so its better to use exports.getMessage = (..arr) => arr.join(" "); this works for every situtation. – Kiwi Rupela Dec 16 '19 at 12:39

2 Answers2

0

has no overloads. If you really want it use instead. Or use the below solution.

exports.getMessage = (arrayArgs) => arrayArgs.join(" ");

console.log(getMessage(["A", "B", "C"]));
// expected output: A B C
PatMan10
  • 568
  • 2
  • 5
  • 15
0

There is no such thing called function overloading in js ,all you can do is use rest param to pass different number of args in a function and apply the logic accordingly as I mentioned in snippet.

function sum(...theArgs) {
  return theArgs.reduce((acc, value) => {
    acc = `${acc} ${value} `
    return acc;
  });
}

console.log(sum(1, 2, 3));
console.log(sum(1, 2));
console.log(sum(1, 2, 3, 4));
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
Shubham Dixit
  • 9,242
  • 4
  • 27
  • 46