SiteKickr Web Development

JavaScript – Passing a single parameter object

It's Saturday and I have things to do on the house, but I wanted to write a short post about function parameters before I put on my tool belt. It hit me yesterday afternoon while I was reviewing some of my old JavaScript code, that I really need to improve the way I pass parameters to my functions.

This is essentially what I was looking at:

scaleImage(this.image, 800, 600, true, false);

While this isn't the most extreme case of unreadable code, it still made my job of understanding what exactly was going on that much more difficult. I could make the following assumptions:

Okay, those assumptions could be made, but the following assumptions are equally believable:

Now, you're saying to yourself, "Why not just look at the function definition to see what those parameters mean?". I could, but do I really want to open another file, locate the function and determine the meaning of each parameter. This takes me away from the task at hand and adds another thing I need to store in my tiny brain.
 

Improves understanding of your code

Instead, I should have used a parameter object when I defined the function:

function scaleImage(options) { }

With only a single options parameter, I can now use more understandable code to call the function:

scaleImage( { imageUrl: this.image, imageWidth: 800, imageHeight: 600, keepRatio: true, returnImage: false });

Your code is more flexible

With the original method of passing multiple parameters, what happens when we want to add a parameter? Of course, we could just tack the parameter on to the end of the parameter list, and if the function is called without it, no harm done, it will simply equate to undefined. But what happens when we want to make that parameter required, we need to place it before the optional parameters. Then, we need to make sure all of the function calls are adjusted to meet this new parameter list requirement.

By using the single parameter object, you can easily add a new parameter, optional or required. You can validate for required parameters easily, and you don't need to break any of your existing code to do it.

scaleImage( { imageUrl: this.image, newRequiredParam: true, imageWidth: 800, imageHeight: 600, keepRatio: true, returnImage: false });