Chapter 7

Function Expressions


  • 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:

//works only in Firefox, Safari, Chrome, and Opera
alert(;    //"functionName"


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:

function sayHi(){


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.