Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
Functions are pieces of code within your program that perform a specific task. By using functions, you are able to write reusable code, not only within the context of the program you are writing, but also with other programs that you may write. In JavaScript, a function consists of the keyword function, followed by the name of the function, a list of arguments, and the JavaScript statements.
The contents of a function (the function body) include some coding logic, and even calls to other functions. This is a way in which you can share bits of code throughout your program. However, on its own, a function is never executed. It needs to be called in the execution of your code. This is done by calling the function by its name. Take the following example which defines a function sayWhat() to log the word “what” to the console. It is called by executing the function in the code.