Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Am I allowed to repeat function parameter names in Javascript?

Tags:

javascript

Is the following function legal and portable?

function(_, _, x){
    return x;
}

Sometimes I want to write a callback that doesn't use the leftmost parameters so I wonder what is the most concise way to do so.


Conclusion:

function(_1, _2, x) is probably as short as it gets then.

like image 750
hugomg Avatar asked Jul 27 '11 23:07

hugomg


People also ask

What are the function parameter rules in JavaScript?

Parameter RulesJavaScript function definitions do not specify data types for parameters. JavaScript functions do not perform type checking on the passed arguments. JavaScript functions do not check the number of arguments received.

Can a function have multiple parameters JavaScript?

Functions can accept more than one argument. When calling a function, you're able to pass multiple arguments to the function; each argument gets stored in a separate parameter and used as a discrete variable within the function.

Can you reassign a parameter JavaScript?

In JavaScript, you can reassign values to variables you declared with let or var .

What happens to any extra parameters passed in to a JS function?

You can call a Javascript function with any number of parameters, regardless of the function's definition. Any named parameters that weren't passed will be undefined.


1 Answers

It is valid in non-strict mode code, but invalid in strict mode code:

It is a SyntaxError if any Identifier value occurs more than once within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression.

Source: http://es5.github.com/#x13.1

Therefore, you may want to avoid this, since at one point in the future you will want to move on to strict mode...

like image 188
Šime Vidas Avatar answered Oct 13 '22 05:10

Šime Vidas