The proposal
I would like to have an explicit way to demonstrate that a function that has many parameters like in Python.
Context
In some normal Javascript program I would do something like this if I needed to have a lot of parameters in the functions:
case 1 - Javascript: common_algorithm_javascript.js
// function definition
function calculateTotalSum(a){
var total=0;
for(var i in a) {
total += a[i];
}
return total;
}
// values, function call
var values = [123,155,134, 205, 105];
console.log(calculateTotalSum(values)); //sums up to 722
But ... In some normal Python program I would do something like this if I needed to have a lot of parameters in the functions:
case 2 - Python: calculateTotalSum.py
# function definition
def calculateTotalSum(*arguments):
totalSum = 0
for number in arguments:
totalSum += number
print(totalSum)
# function call, values
calculateTotalSum(5, 4, 3, 2, 1)
my idea ... in Javascript: calculateTotalSum.js
// function definition
function calculateTotalSum(*args){
var total=0;
for(var i in args) {
total += a[i];
}
return total;
}
// values, function call
var values = [123,155,134, 205, 105];
console.log(calculateTotalSum(values)); //sums up to 722
example of good practice
// Inspiration in Python =)
function functionName(*argument) { ... }
function functionName(*variables) { ... }
function functionName(*vars) { ... }
function functionName(*arguments) { ... }
function functionName(*args) { ... }
example of bad practice
function functionName(var1, var2, var3, var4) { ... } // bad practice
function functionName(var1, var2, var4, var5, var6 ... var10) { ... } // error
reasons
- This allows you to bring Javascript closer to Python developers.
- Variable number of non keyword arguments passed
- Multiple arguments are passed
- Good practices and explicit arguments
Rules/Notes
- Keyword:
*arguments or *args or *parameter or *params or *values or *vars
- The * symbol is used to pass a variable number of arguments to a function. Typically, this syntax is used to avoid the code failing when we donβt know how many arguments will be sent to the function.
- The number of variables as parameter in the function cannot exceed the amount of 10 variables, above this value it would be advisable to use *args
reference
- What is Python? Executive Summary | Python.org
- Write Functions with Multiple Parameters in Python | Earth Data Science - Earth Lab
- How to pass multiple arguments to function ? - GeeksforGeeks
- GitHub - tc39/proposal-bind-operator: This-Binding Syntax for ECMAScript
- JavaScript vs. Python usage statistics, April 2022
- javascript total sum of numbers Code Example