Code is run from the first line in the file to the last line unless the computer runs across the (extremely frequent) structures that change the control flow, such as conditionals and loops. For example, imagine a script used to validate user data from a webpage form. The script submits validated data, but if the user leaves a required field empty, it prompts them to fill it in. To do this, the script uses a conditional structure or if...else, so that different code executes depending on whether the form is complete or not:
if (isEmpty(field)) { promoter(); } else { submitForm(); } Copy to Clipboard A typical script in JavaScript or PHP (and the like) includes many control structures, including conditionals, loops, and functions. Parts of a script may also be set to execute when events occur. For example, the above excerpt might be inside a function that runs when the user clicks the Submit button for the form. The function could also include a loop, which iterates through all of the fields in the form, checking each one in turn. Looking back at the code in the if and else sections, the lines promptUser and submitForm could also be calls to other functions in the script. As you can see, control structures can dictate complex processing flows even with only a few lines of code.
|