dominoGuru.com
Your Development & Design Resource
Relaying function-to-function arguments in JavaScript
05/24/2018 by Chris Toohey
Most Create and Update CRUD operations triggered from a data input User Interface run a validation prior to said Create or Update. To do this, you may have a function that handles your validation return a Boolean. If the validation Boolean is true, you proceed with the Create/Update. If the Boolean is validation Boolean is false, you return warnings to the User Interface based on the construction of your UI.
If you were to pseudocode some JavaScript for this process, it would look something like this:
Yeah, this is kinda ugly... but it gets something on the screen for us to improve on.
Let's say our application has several forms that each have unique validation and submission requirements. For code maintainability purposes, we don't want to write a validation and submission function for each form but rather create a metafunction that will handle all validation functions and submission functions. Since we're creating singular functions for validation and submission, we'll need to make those functions smart enough to know what to validate and what to submit.
Our updated pseudocode might look like this:
Let's talk about arguments. In JavaScript, arguments
is a reserved word object handle on the array of arguments for a function.
Let's try this interactive little demo:
Let's take a look at our argumentsAlert()
function, and how we're using the arguments
object handle:
Now that we know about arguments
, let's have another go at our pseudocode:
The change is subtle, so I removed the actual functions so we could focus on the HTML Button code. In there, you can see we're no longer duplicating our arguments from function to function, but rather using the arguments
supplied to the validateForm()
function for our submitForm()
function.
This results in cleaner, leaner, and more readable once you know what arguments
is and how it works.
In an upcoming article we'll be covering CRUD metafunctions which relies heavily on arguments
, so we needed to get this primer in before we're too far down a particular path.