We have already discussed using loops, arrays, Booleans, and other operators in JavaScript. Here I have provided an introduction to using functions in JavaScript. Functions are inevitable in JavaScript, especially for advanced Web Developers. Make sure that you are using Chrome, IE9+, or Firefox 5 for best performance.
A function is a bit of code that doesn’t run until it is referenced or called. alert() is a function built into our browser. It’s a block of code that runs only when we explicitly tell it to. In a way, we can think of a function as a variable that contains logic, in that referencing that variable will run all the code stored inside it.
All functions share a common pattern. The function name is always immediately followed by a set of parentheses (no space), then a pair of curly braces that contain their associated code. The parentheses sometimes contain additional information used by the function called arguments.
Arguments are data that can influence how the function behaves. For example, the alert function we know so well accepts a string of text as an argument, and uses that information to populate the resulting dialog.
There are two types of functions: those that come “out-of-the-box” (native JavaScript functions) and those that you make up yourself (custom functions). Let’s look at each.
Native functions
There are hundreds of predefined functions built into JavaScript, including:
alert(), confirm(), and prompt()
These functions trigger browser-level dialog boxes.
Date()
Returns the current date and time.
parseInt(“123″)
This function will, among other things, take a string data type containing numbers and turn it into a number data type. The string is passed to the function as an argument.
setTimeout(functionName, 5000)
Will execute a function after a delay. The function is specified in the first argument, and the delay is specified in milliseconds in the second (in the example, 5000 milliseconds equals 5 seconds).
There are scores more beyond this, as well.
Custom functions
To create a custom function, we type the function keyword followed by a name for the function, followed by opening and closing parentheses, followed by opening and closing curly brackets.
function name() { // Our function code goes here. }
Just as with variables and arrays, the function’s name can be anything you want, but all the same naming syntax rules apply.
If we were to create a function that just alerts some text (which is a little redundant, I know), it would look like this:
function foo() { alert("Our function just ran!"); // This code won't run until we call the function 'foo()' }
We can then call that function and execute the code inside it anywhere in our script by writing the following:
foo(); // Alerts "Our function just ran!"
We can call this function any number of times throughout our code. It saves a lot of time and redundant coding.
No comments yet (leave a comment)