Functions

We start with functions as that is the primary script code that JavaScript developers write. C# developers will notice that functions are not bound by namespaces or classes. Instead, they are just defined as script. You can then call these functions inside your page as a response to a user action or similar.

A JavaScript declarative function is code you write to execute an action and possibly return a value(s). Again, this should be familiar to server-side developers. Functions can be declared anywhere in your script, including as a method of a JavaScript object (more on this in a moment). You declare a function with the keyword function. You then name it, set any parameters inside parentheses, and use the return keyword to return a value from the function.

As an example, the following JavaScript function calculates the average speed (as miles/hour). Notice that it takes two parameters and uses the return keyword to provide the results.

//Calculate average speed using named function.
function averageSpeed(distanceMiles, timeMinutes) {
  return distanceMiles / (timeMinutes / 60)
}

You can call this function (inside the same script file or web page) by name. The following shows an example. Of course, in most cases a call to this function happens as the result of user action (clicked a button, navigated away from a field, etc.). And, the values you pass into the function would likely come from user input. We will see that shortly.

var speed = averageSpeed(22, 90);

Note that functions can return more than one value. You can do so using an array as the return type. However, if you need to return more than one value, it is often cleaner to return an object with multiple properties (see the “Objects” section later in this chapter).

The averageSpeed function is known as a named function. It has a name; can exist anywhere in your script; and can be called from anywhere in your script or on the web page. JavaScript interpreters look for named functions before executing any code. The interpreter finds these functions and loads then. It then looks for any script that is meant to be executed immediately (including those that call a named function) and then begins executing your code line by line as we will see next. Some functions are only called based on user action (click a button, select a value, etc.). The browser works with the JavaScript interpreter to execute those functions too.

Anonymous Functions

You will often write functions without names; a function without a name is known as an anonymous function. You write anonymous functions when you need the power of a function but do not intend to reuse that function throughout your code. These functions can also help prevent name conflict between multiple scripts used in the same page (as there is less likely a conflict if the function is unnamed).

For example, assigning a function to a variable uses an anonymous function. However, this creates a function expression. A function expression is when a function is used where the interpreter might normally expect to see an expression. The interpreter does not find these in advance of running your script. Instead, the interpreter encounters them as it executes your code, line by line. Therefore, you must declare your function expression (using an anonymous function) first, before calling it. The following shows the prior example now written (and executed) using a function expression.

//Calculate average speed with function expression.
var speed = function(distanceMiles, timeMinutes) {
  return distanceMiles / (timeMinutes / 60)
}
var mySpeed = speed(22, 90);

Immediately Invoked Function Expressions (IIFE)

There are also times when you will need the power of an anonymous function directly inside a line of executing code. These type of functions are known as immediately invoked function expressions, or IIFE (pronounced “iffy”). You write an IIFE by enclosing the function in parentheses, as in (myFunction(){});. You call the function directly using parentheses after the declaration, as in (myFunction(){}());.

The following shows the average speed calculation as an IIFE. In this case, the function is immediately executed by the interpreter when it encounters the line of code. It returns the value to the variable bikeSpeed. This value is then used in the alert message. (The function is not and cannot be called a second time.)

var bikeSpeed = (function (distanceMiles, timeMinutes) {
  return distanceMiles / (timeMinutes / 60)
}(22, 90));

alert(bikeSpeed);

Functions are everywhere in JavaScript. It is important that you understand these few key differences to work with them effectively. Functions can also be assigned to an object. In doing so, the function becomes a method of that object. Let’s look at that next.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset