2

Can someone explain what happens in the below scenario:(this was an interview question)

function test(a){
    alert(a);
}

function test(a,b){
    alert(a,b);
}

function callTest(){
    test(a);
    test(a,b);
}

I was asked how the javascript calls the methods, and what happens behind the scenes in this scenario

2
  • What do you mean "behind the scenes"? Sounds like a pretty intense interview question. I would expect that maybe they would ask what the contents of the alert dialog would be... Commented Nov 10, 2014 at 3:37
  • alert only takes one argument, so the second will be ignored. Commented Nov 10, 2014 at 3:47

2 Answers 2

3

If you run it in that order, test(a) will be replaced by test(a,b)

When callTest() is run, then test(a) will alert(a, undefined), then test(a,b) will alert(a,b)

Sign up to request clarification or add additional context in comments.

1 Comment

Agreed - JS don't have the concept of method overloading.
1
function test(a){     // f1. never called.
    alert(a);
}

function test(a,b){   // f2. overwrite f1 function because name of two functions is same.
    alert(a,b);
}

function callTest(){
    test(1);     // called f2 with (1, undefined)
    test(1,2);   // called f2 with (1, 2)
}
callTest();

1 Comment

Thank you, this was explained well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.