1

I got 2 functions in javascript (Chrome and IE):

function call(param1, param2){
   console.log("call param - 2");
}

and

function call(param1){
   console.log("call param - 1");
}

I called like this:

call(1,2);

But I receive this on console:

call - param - 1
kyun
  • 9,710
  • 9
  • 31
  • 66
JorgeParada
  • 573
  • 3
  • 11
  • 29
  • how should javascript know which one you mean? oh, c++/c#/java background is it – Jaromanda X Oct 11 '17 at 08:27
  • 1
    AFAIK you can't use function overloading in JavaScript. The function you created last is the one that is called. (if you switch the function declarations, your outcome will be "call param - 2". See https://stackoverflow.com/questions/456177/function-overloading-in-javascript-best-practices – Ivar Oct 11 '17 at 08:28

7 Answers7

3

What you are trying to do is called function overloading. Unfortunately, it's not available in JavaScript.

But you can always try to kind of simulate it if you need.

Please check this link where there's a discussion about the best way to do it:

Function overloading in Javascript - Best practices

Javier Cobos
  • 1,172
  • 10
  • 22
2

There is no function overloading in JavaScript.

Joe Clay
  • 33,401
  • 4
  • 85
  • 85
marvel308
  • 10,288
  • 1
  • 21
  • 32
1

You can use arguments.

function call(){
   console.log("call param - " + arguments.length);
}

call(1);

call(1,2);

call(1,2,3);
kyun
  • 9,710
  • 9
  • 31
  • 66
1

Solution is to use a single function with conditions inside.

function call(param1, param2){
  if(param2){
    console.log("call param - 2");
  } else if(param1) {
    console.log("call param - 1");
  } else {
    console.log("call invalid");
  }
}
rrk
  • 15,677
  • 4
  • 29
  • 45
0

You are trying to overload your 'call' function. Javascript does not support function overloading.

A solution could be to make to seperate functions, with different names for each usecase.

Niels Meima
  • 119
  • 1
0

firstly, js do not check argument count : you can call any function with any amount of arguments.

Secondly, declaring a function means the same thing as declaring , so for a js engine, your code is

var call = fun1
var call = fun2

is the same as

var call
......
call = fun1
call = fun2

For function definitions, the value will also be hoisted, so it is actually

var call = fun2
......

so, it will always be the later one.

If you want to access all arguments in a normal function, you can use arguments, or do this

function f(foo, bar, ...args) {...}

in arrow function there is no arguments

0

If call(param1) is defined after call(param1, param2) if is reassigned to call reference. So when you call call(1,2), call(param1) is invoked. There is no such thing as function overloading in JS. YOu can either utilise arguments object to achive function that accpets variable arguments.

Andrzej Smyk
  • 1,684
  • 11
  • 21