Skip to content

Instantly share code, notes, and snippets.

@sean-roberts
Created June 20, 2013 17:04
Show Gist options
  • Save sean-roberts/5824569 to your computer and use it in GitHub Desktop.
Save sean-roberts/5824569 to your computer and use it in GitHub Desktop.
Function Parameter and Arguments in JS: There are special things to consider when you pass a function more or less parameters than expected because JavaScript does not consider type nor does it worry about length. When you pass 2 parameters to a function expecting 4, the last two in the arguments are set to undefined. When you pass more paramete…
//this foo function is really saying,
//"Hey, I am expecting about 3 arguments but give me what you can"
function foo(a, b, c){
console.log(a,b,c);
}
//lets ask foo to take more and less parameters than expected
foo("anArg"); // logs in console => anArg undefined undefined
foo("I", "Am", "anArg", "asWell", ":)"); // logs in console => I Am anArg
//just like foo, i am not really worried about how many parameters you pass
//in fact, it will use the arguments[] object to loop over any and all of the arguments you decide to send
function baz(){
var output = [];
//code below loops through all of the arguments individually - adding them to an array
for(var i = 0; i < arguments.length; i++){
output.push(arguments[i]);
}
//combine their values and output them in one string
console.log(output.join(" "));
}
baz("one", "two"); // logs in console => one two
baz("one"); // logs in console => one
baz("one", "two", "three"); // logs in console => one two three
//this function is really saying,
//"Hey, I am expecting 2 arguments and I will throw an error if you dont"
function bar(d, e){
if(arguments.length !== 2){
throw new Error("You can only pass 2 parameters to bar(a,b). You passed " + arguments.length);
}
console.log(d,e);
}
bar("one", "two"); // logs in console => one two
bar("one"); //throws an error
bar("one", "two", "three"); //throws an error
/*
Note: when you have parameters defined like the "d,e" in the bar function what happens when bar is invoked is the
paramters are evaluated and their resulting values are added to the arguments of the function. If you defined an alias
to these values, such as "d", and "e" in bar(d,e), these aliases are assigned the value of the argument in the order
they are defined. So, in bar(d,e) - the value passed as d is evaluated and assigned to both arguments[0] AND
the local variable d, then e is evaluated and assigned to both arguments[1] and the local variable e. That is all
to say that arguments[0] == d and arguments[1] == e.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment