5

While I was just playing around with JS, I wrote following snippet:

function checkArgs(abc,nbn,jqrs){
    console.log("overloaded " +arguments.length);
}

function checkArgs(abc){
    console.log(arguments.length);
}

checkArgs("aa","lll","pp");

I see output as " 3 " , however I was expecting out put as "overloaded 3". But I does not happen , however if I just swap the postions of those method, it does happen.

 function checkArgs(abc){
        console.log(arguments.length);
    }


  function checkArgs(abc,nbn,jqrs){
        console.log("overloaded " +arguments.length);
    }    

    checkArgs("aa","lll","pp");

Whats the rationale behind it?

Orion
  • 81
  • 1
  • 3

2 Answers2

5

There is no function overloading in javascript.

The latest method declaration always overwrites the previous one with the same name. No error thrown.

Also functions in javascript are all variadic. Any number of arguments can be passed regardless of the function signature.

eltonkamami
  • 5,134
  • 1
  • 22
  • 30
0

In JavaScript there is no overloading, declaration of function gets hoisted and it gets overridden by overloaded methods. Last method in sequence override all other definitions.

Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110