Duplicate Function Parameters in JavaScript

2016-06-20

Did you know that you could have a function with 2 parameters with the same name in JavaScript ? This is one of the latest weird part of JavaScript that I just discovered.

Example

The following code is legal and executes without any warning:

1
2
3
4
5
function log(x,y,x) {
console.log(x);
}

log(1,2,3); // Will print out 3

Fix It

There are several ways to avoid the issue:

  • use strict

By adding a 'use strict'; statement at the beginning of the function, you will get an error thrown:

1
2
3
4
5
6
function log(x,y,x) {
'use strict';
console.log(x);
}

log(1,2,3);

Will throw

1
"SyntaxError: Duplicate parameter name not allowed in this context
  • JSHINT and JSLINT

Both Linters will throw a warning and let you know that x is already defined.