Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

Lesson 1: Introducing JavaScript CHAPTER 3 75


Using function expressions
A function expression produces a value of type function. You can assign function expressions
to variables or execute them directly. Here is an example of a function expression being cre-
ated and assigned to a variable:
var addFunction = function(x, y){
return x + y;
};

var c = addFunction(5, 10);

First, notice that addFunction is called after the function expression is assigned to the
addFunction variable. If you tried to call addFunction before the assignment of the function
expression to the addFunction variable, an exception would be thrown.
The addFunction variable is of type function, in which the function expression is created by
using the function keyword to create a function with no name (also known as an anonymous
function), and then the function expression is assigned to the variable. An anonymous func-
tion has no name or identifier. Although function expressions can be named or anonymous,
it’s considered better to leave the function anonymous to minimize confusion.
Function expressions can be beneficial when you want to determine the code conditionally
to be executed at runtime. Here is an example of when you might add two values or subtract
one value from the other:
var myFunction = function(x, y){
return x + y;
};
//lots of code
var c = myFunction(10, 5);
//lots of code
myFunction = function(x, y){
return x - y;
};
//lots of code;
var d = myFunction(10,5);

In this example, variable c will be assigned a value of 15 because myFunction was declared
and assigned code that adds x and y. Variable d is assigned the value of 5 because myFunction
was assigned new code that subtracts y from x.

Deciding which arguments
JavaScript is very loose when passing arguments to functions. If you have too many argu-
ments, JavaScript just discards the extras. If you don’t have enough arguments, the parameter
values for missing arguments will be undefined.
The biggest benefit of this loose behavior is that you can add parameters to a method that
has already been created and is already being called. The added parameters might provide
extra functionality that can be accessed, but existing callers continue to work.
Free download pdf