Monday, September 10, 2012

Function argument patterns

UPDATE:  ECMAScript 6 introduces rest parameters to help us with this and other pitfalls. Rest parameters are indicated by three dots … preceding a parameter. Named parameter becomes an array which contains the rest of the parameters. Please check official MDN documentation here.

Let's create a simple JavaScript function that takes 3 arguments to it. Inside the function, we made operation against this arguments. We add each one together and then we return resulting value. Then we execute these function three times. The first time we pass three arguments, and we expect a result of 6. But, in the second example we passing 4 arguments instead of 3 arguments, and in the final example, we pass 2 arguments instead of 3 arguments which are expected from the function. 

So, how we expect JavaScript to deal with these? 

Unlike more traditional programming languages like C# and VB, arguments in javascript are more dynamic. All variables in JavaScript arguments are untyped, and unspecified arguments become undefined. 

So in our example when we call our function with 2 arguments, the 3th argument will become undefined. So, we got output of NaN. In our second call to the function where we pass 4 arguments, we didn't get error because JavaScript ignores 4th argument.

But, sometimes you might want to access this arguments if there are specified. JavaScript provides very easy way to do this through an arguments object which exists inside every function. The arguments object is very special object in JavaScript. It's kind of like an array, but it's not array. You can access all arguments through numeral indexes. The arguments object has lenght property so you can iterate through, as an array. But it's not actually array, because you can not sortring, filtering...

That means than we can implement some intresting things, such as next code example:

Here we take the same concept, but instead of passing the arguments, we just accessing arguments object. This concept is also used quite commonly in a lot of JavaScript libraries like JQuery, where you can pass in various different number of arguments types, like string, function, dom object and JQuery will allow to operate against this.

No comments:

Post a Comment