Chapter 7

Function Expressions

WHAT’S IN THIS CHAPTER?

  • Function expression characteristics
  • Recursion with functions
  • Private variables using closures

One of the more powerful, and often confusing, parts of JavaScript is function expressions. As mentioned in Chapter 5, there are two ways to define a function: by function declaration and by function expression. The first, function declaration, has the following form:

function functionName(arg0, arg1, arg2) {
    //function body
}

The name of the function follows the function keyword, and this is how the function’s name is assigned. Firefox, Safari, Chrome, and Opera all feature a nonstandard name property on functions exposing the assigned name. This value is always equivalent to the identifier that immediately follows the function keyword:

image
//works only in Firefox, Safari, Chrome, and Opera
alert(functionName.name);    //"functionName"

FunctionNameExample01.htm

One of the key characteristics of function declarations is function declaration hoisting, whereby function declarations are read before the code executes. That means a function declaration may appear after code that calls it and still work:

image
sayHi();
function sayHi(){
    alert("Hi!");
}

FunctionDeclarationHoisting01.htm

This example doesn’t throw an error because the function declaration ...

Get Professional: JavaScript® for Web Developers, Third Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.