O'Reilly logo

Professional: JavaScript® for Web Developers, Third Edition by Nicholas C. Zakas

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required