Passing multiple Arguments to a JavaScript Function at Runtime
Today I came across with a scenario in Javascript functions that the number of parameters would change in the runtime. When I searched in google I found that, In JavaScript we can pass any number of parameter and get these parameter at run time.
JavaScript functions have a special property called arguments. This contain an array of the input parameters. We can use the length property of the array and loop through the parameters passed to the function. This enables the development of function where the number of parameters can change at runtime.
<script type=”text/javaScript”>
function myConcat(separator) {
var result = “”;
// iterate through non-separator arguments
for (var i = 1; i < arguments.length; i++) {
result += arguments[i] + separator;
}
return result;
}
</script>
This function can be called with any number of arguments at the runtime like
// returns “red, orange, blue, ”
myConcat(“, “, “red”, “orange”, “blue”);// returns “elephant; giraffe; lion; cheetah; ”
myConcat(“; “, “elephant”, “giraffe”, “lion”, “cheetah”);// returns “sage. basil. oregano. pepper. parsley. ”
myConcat(“. “, “sage”, “basil”, “oregano”, “pepper”, “parsley”);
Also, If you want to determine the number of arguments declared when a function was defined, use the Function.length property.
myConcat.length // In this case it will return 1
.
Filed under: JavaScript
PHP does this very nicely. Anyway I have written about this in little more detail in a page about Optional Function Arguments.