Optional parameters in javascript functions
When you have a javascript function that takes a lot of optional parameters, it can be hard to call the function since missing one parameter then shifts everything over and the assignments are wrong. An easy work around for this in javascript is to not send individual parameters to your functions at all -- at least, not to those that take a lot of parameters, or where you may want to change the parameter list at some point in the future.
Instead, you set up the javascript function to accept a single object. And that object contains attributes which are the input parameters to the function. You then have code in the function that parses the object and assigns parameters and defaults as needed. The advantage of this technique is that you can then call the function with a dynamically creted object. So the order of the parameters does not matter. Also, if you add additional parameters to the function in the future, your existing calls to it do not need to change and if you do want to change them, it is easy to do so without messing up the existing parameters.
Instead, you set up the javascript function to accept a single object. And that object contains attributes which are the input parameters to the function. You then have code in the function that parses the object and assigns parameters and defaults as needed. The advantage of this technique is that you can then call the function with a dynamically creted object. So the order of the parameters does not matter. Also, if you add additional parameters to the function in the future, your existing calls to it do not need to change and if you do want to change them, it is easy to do so without messing up the existing parameters.
| Rating: | 100% positive, 1 Vote |
| Categories: | javascript programming web |
| Added: | on Jul 30, 2008 at 10:44 am |
| Added By: | an anonymous user |

