JS – Multiple parameters with the same name?

I was looking at the PHP 7.0.0 Beta 1 change log the other month wondering how much the language would *ahem* improve in this new, major release. As I was reading, I was surprised to come across this change:

It is no longer possible to define two function parameters with the same name.
For example, the following method will trigger a compile-time error:

public function foo($a, $b, $unused, $unused) {
    // ...

Code like this should be changed to use distinct parameter names, for example:

public function foo($a, $b, $unused1, $unused2) {
     // ...

To be honest, I was quite puzzled by the entry. Why would have alike named parameters been allowed in the first place? I started out in Python, where such actions are considered a full-fledged SyntaxError.

def foo(a, b, unused, unused):
>>> SyntaxError: duplicate argument 'unused' in function definition

I was also confused why this duplicate named parameter “feature” even existed as it was affected by variable assignment order. If 'Hello' was passed into the first $unused parameter and 'World!' into the second, echoing out the value would reveal the first parameter is totally lost. The entire behavior is illogical.

The next day, an article entitled Seven Surprising JavaScript ‘Features’ by Luke Page appeared in my Twitter feed. As a JavaScript developer and one who likes to hear about a programming language’s “features” (that is, inconsistencies, crazy behavior, and lack of foresight), I read the article with eagerness and surprise when I came to the section “Same Name Parameters”, exampling that in non-strict mode, JavaScript supports this too!

function foo(a, b, unused, unused) {
     // The second unused parameter overwrites the first!

I did not think this was possible in JavaScript. I know JavaScript ignores (well, not technically ignores, but effectively) extra parameters and sets unpassed parameters to undefined, but I did not expect it to support illogical, same-named parameters as well!

The More You Know



2 thoughts on “JS – Multiple parameters with the same name?

    1. We may never know exactly why, but we do know the initial language was written in one week and it was until ECMAScript 5 in 2009 were many bugs, issues, and grievances were corrected and addressed and desired features (of the time) added. So it probably supports same-named parameters (which are illogical as explained) in oversight and still does in non-strict mode (which was added in ECMAScript 5).

Triangular Reactions

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s