JavaScript Primer: Defining and Using Functions

When the browser processes an HTML document, it looks at the elements one by one. When it encounters a script element, it immediately executes the JavaScript statements it contains in the sequence in which they are defined.

This is what happened in the previous example. The browser processed the HTML document, found the script element, and executed the two statements that it encountered, both of which wrote a message to the console. You can also package multiple statements into a function, which won’t be executed until the browser encounters a statement that invokes the function, as shown in Listing 5-4.

Listing 5-4. Defining a JavaScript Function in the jsdemo.html File

<!DOCTYPE HTML>

<html>

<head>

<title>Example</title>

<script src=”angular.js”></script>

<script type=”text/javascript”>

function myFunc() {

console.log(“This is a statement”);

};

myFunc();

</script>

</head>

<body>

This is a simple example

</body>

</html>

Defining a function is simple: Use the function keyword followed by the name you want to give the function, followed by parentheses (the ( and ) characters). The statements you want the function to contain are enclosed between braces (the { and } characters).

In the listing I used the name myFunc, and the function contains a single statement that writes a message to the JavaScript console. The statement in the function won’t be executed until the browser reaches another statement that calls the myFunc function, like this:

myFunc();

Executing the statement in the function produces the following output:

This is a statement

Other than demonstrating how functions are defined, this example isn’t especially useful because the function is invoked immediately after it has been defined. Functions are much more useful when they are invoked in response to some kind of change or event, such as user interaction.

1. Defining Functions with Parameters

JavaScript allows you to define parameters for functions, as shown in Listing 5-5.

Listing 5-5. Defining Functions with Parameters in the jsdemo.html File

<!DOCTYPE HTML>

<html>

<head>

<title>Example</title>

<script src=”angular.js”></script>

<script type=”text/javascript”>

function myFunc(name, weather) {

console.log(“Hello ” + name + “.”);

console.log(“It is ” + weather + ” today”);

};

myFunc(“Adam”, “sunny”);

</script>

</head>

<body>

This is a simple example

</body>

</html>

I added two parameters to the myFunc function, called name and weather. JavaScript is a dynamically typed language, which means you don’t have to declare the data type of the parameters when you define the function. I’ll come back to dynamic typing later in the chapter when I cover JavaScript variables. To invoke a function with parameters, you provide values as arguments when you invoke the function, like this:

myFunc(“Adam”, “sunny”);

The results from this listing are as follows:

Hello Adam.

It is sunny today

The number of arguments you provide when you invoke a function doesn’t need to match the number of parameters in the function. If you call the function with fewer arguments than it has parameters, then the value of any parameters you have not supplied values for is undefined, which is a special JavaScript value. If you call the function with more arguments than there are parameters, then the additional arguments are ignored.

The consequence of this is that you can’t create two functions with the same name and different parameters and expect JavaScript to differentiate between them based on the arguments you provide when invoking the function. This is called polymorphism, and although it is supported in languages such as Java and C#, it isn’t available in JavaScript. Instead, if you define two functions with the same name, then the second definition replaces the first.

Tip The closest you can come to polymorphism in JavaScript is to define a single function to act differently based on the number and the types of the arguments. Doing this requires careful testing, can result in an awkward API, and is generally best avoided.

2. Defining Functions That Return Results

You can return results from functions using the return keyword. Listing 5-6 shows a function that returns a result.

Listing 5-6. Returning a Result from a Function in the jsdemo.html File

<!DOCTYPE HTML>

<html>

<head>

<title>Example</title>

<script src=”angular.js”></script>

<script type=”text/javascript”>

function myFunc(name) {

return (“Hello ” + name + “.”);

};

console.log(myFunc(“Adam”));

</script>

</head>

<body>

This is a simple example

</body>

</html>

This function defines one parameter and uses it to produce a result. I invoke the function and pass the result as the argument to the console.log function, like this:

console.log(myFunc(”Adam”));

Notice that you don’t have to declare that the function will return a result or denote the data type of the result. The result from this listing is as follows:

Hello Adam.

3. Detecting Functions

Functions can be passed around as objects within JavaScript, and it can be useful to be able to tell whether an object is a function. AngularJS provides the angular.isFunction method for this purpose, as demonstrated in Listing 5-7.

Note All of the AngularJS utility methods are accessed via the global angular object, such as angular.isFunction, which is the subject of this example. The angular object is created automatically when you add angular.js to an HTML file using a script element.

Listing 5-7. Detecting Functions in the jsdemo.html File in the jsdemo.html File

<!DOCTYPE html>

<html>

<head>

<title>Example</title>

<script src=”angular.js”></script>

<script type=”text/javascript”>

function printMessage(unknownObject) {

if (angular.isFunction(unknownObject)) {

unknownObject();

} else {

console.log(unknownObject);

}

}

var variable1 = function sayHello() {

console.log(“Hello!”);

};

var variable2 = “Goodbye!”;

printMessage(variable1);

printMessage(variable2);

</script>

</head>

<body>

This is a simple example

</body>

</html>

This example is made more complex because it doesn’t have the context of a real project. I defined a function called printMessage that expects to receive different types of argument. I use the angular.isFunction method to check whether the object I am processing is a function and—if it is—then I invoke the function, like this:

unknownObject();

If the isFunction method takes an object as an argument and returns true if the argument is a function and false otherwise. For objects that are not functions, I pass the object to the console.log method.

I created two variables to demonstrate the printMessage function: variable1 is a function, and variable2 is a string. I pass both to the printMessage function; variable1 is identified as a function and invoked, and variable2 is written to the console. When variable! is invoked, it writes to the console anyway, producing the following results:

Hello!

Goodbye!

Source: Freeman Adam (2014), Pro AngularJS (Expert’s Voice in Web Development), Apress; 1st ed. edition.

Leave a Reply

Your email address will not be published. Required fields are marked *