Friday, November 16, 2012

Function Overloading in Javascript

Some of the concepts in "JavaScript" is really difficult to get. What make them more difficult is the fact that we except it to behave like true object oriented programming language.

What would you expect from the following piece of code:-
      
             //Function 1
             function fun(arg1,arg2){
              alert("Fun_1");
             }
            
             //Function 2
             function fun(arg){
              alert("Fun_2");
             }

             fun();//Call 1
             fun("Hello_1","Hello_2");//Call 2

I bet most of us will think "Call 1" will fail and "Call 2" will invoke "Function 1".

The fact is both calls will invoke "Function 2"....Surprised????

To understand why javascript shows this behavior , we have to consider that even though the above mentioned functions seems like two different functions (Because we are very much familiar with C++ or Java). The fact is they are not as javascript does not support function overloading . What is being done in the above code snippet is that the second function i.e Function2 just overwrites the Function1.

Hence in nutshell. Javascript does not support function overloading and as it is not a compiled programming language there is no compiler to warn you when you write two function with same name but different argument.

The interpreter which  comes with the browser just follows "Last One Wins" principle and leave us all surprised and puzzled when we see that all calls (With different argument) invokes only one of the function which is declared at last in the execution flow.



4 comments:

  1. Interesting. Glad to see you back to sharing your knowledge.

    Good luck with your new blog. :)

    ReplyDelete
  2. Won't both the function calls will invoke Function 2? By "Last one wins" principle, wouldn't Function 2 win?

    ReplyDelete
  3. @ Alexander . Yes there was a typo . As i explained last one will win. So if you have wrote the code in the same sequence as mine ,Function 2 will get called.

    Thanks a lot for pointing it out.

    ReplyDelete