Search code examples
javascriptfunctionecmascript-6javascript-function-declaration

Javascript function declaration with same arguments


I am learning javascript myself. I found if I declare a function with same arguments it just working fine:

function func(a, b, a){
  return b;
}
alert(func(1,2,3));

But if I do this :

function func(a, b, a = 5){
  return b;
}
alert(func(1,2,3)); 
//Firebug error - SyntaxError: duplicate argument names not allowed in this context

Then its not working anymore. What is the logic behind that it was working for first equation but not for second one ?


Solution

  • ES2015 (the newest stable spec for the language) allows parameters to be declared with default values. When you do that, the language won't allow you to re-use a parameter name.

    When you're not doing any parameter defaults, the language allows the old "sloppy" re-use of parameter names. If you enable "strict" mode interpretation, you'll get an error for your first example too.