Hey, I am trying to understand this passing arguments business in JavaScript but I just can't seem to grasp it, could someone try and explain it a bit clearer to me if you don't mind? I have tried using W3 and About.com but just don't get it, am sure it is stupidly simple too. Thanks!
Function arguments in javascript work pretty much like any other languages, a list of values between curly braces and separated by commas. Then there are just a few things you must be aware of. 1 - Arguments are not typecasted, each argument can be of any type, basically as any variable in javascript. Example: function sum(a, b) { return a + b; } alert(sum(2, 4)); //6 alert(sum('a', 7)); //a7 Code (markup): 2 - You can use any number of arguments you want, you don't need to stick to the ones defined in function definition, but obviously, your function must be prepared to deal with that. Example: function sum(a, b, c) { var total = 0; if (a) total += a; if (b) total += b; if (c) total += c; return total; } alert(sum(2,3,4)); //9 alert(sum(4,2)); //6 alert(sum(8)); //8 alert(sum()); //0 Code (markup): 3 - You can use the special array "arguments" to refer to every argument in a function. Example: function sum() { total = 0; for (var i = 0; i < arguments.length; i++) total += arguments[i]; return total; } alert(sum(1, 1, 1, 1, 1, 1, 1, 1, 1, 1)); //10 Code (markup): Hope it helps