O'Reilly logo

Eloquent JavaScript by Marijn Haverbeke

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

We have already used several functions in the previous chapter—things such as alert and print—to order the machine to perform a specific operation. In this chapter, we will start creating our own functions, making it possible to extend the vocabulary that we have available. In a way, this resembles defining our own words inside a story we are writing to increase our expressiveness. Although such a thing is considered rather bad style in prose, in programming it is indispensable.

The Anatomy of a Function Definition

In its most basic form, a function definition looks like this:

function square(x) {
  return x * x;
}

square(12);
→ 144

Here, square is the name of the function. x is the name of its (first and only) argument. return ...

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