O'Reilly logo

Learning JavaScript, 3rd Edition by Todd Brown

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

A function is a self-contained collection of statements that run as a single unit: essentially, you can think of it as a subprogram. Functions are central to JavaScript’s power and expressiveness, and this chapter introduces you to their basic usage and mechanics.

Every function has a body; this is the collection of statements that compose the function:

function sayHello() {
   // this is the body; it started with an opening curly brace...

   console.log("Hello world!");
   console.log("¡Hola mundo!");
   console.log("Hallo wereld!");
   console.log("Привет мир!");

   // ...and ends with a closing curly brace
}

This is an example of a function declaration: we’re declaring a function called sayHello. Simply declaring a function does not execute the body: if you try this example, you will not see our multilingual “Hello, World” messages printed to the console. To call a function (also called running, executing, invoking, or dispatching), you use the name of the function followed by parentheses:

sayHello();       // "Hello, World!" printed to the
                  // console in different languages
Note

The terms call, invoke, and execute (as well as run) are interchangeable, and I will use each in this book to get you comfortable with them all. In certain contexts and languages, there may be subtle differences between these terms, but in general use, they are equivalent.

Return Values

Calling a function is an expression, and as we know, expressions resolve to a value. So what value does a function ...

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