• Home
  • »
  • Creating JavaScript functions

Creating JavaScript functions

If you have to write a large program, you may consider using functions. Functions allows you to easily reuse your code. A function is a series of commands that either calculates a value or performs an action. A function consists of function name, which identifies it, parameters, the values passed to the function, and the set of commands that run when the function is called. To use a function, you call the function. When you call the function, you pass (send) the values used by the function. Note that not all functions require you to pass values; thus parameters are optional. Functions can also return a value, the result of the calculation or the output of the function sent back from the function.

The general syntax of a JavaScript function is:

function functionName (parameters) {
JavaScript commands
functionName = name of the function
parameters = values sent to the functions
JavaScript commands = commands that run when the function is called or used

A function starts with the keyword function. All the commands that belong to a function must be placed inside the curly braces { }. The set of commands placed inside the curly braces is referred to as a commands block. The commands block combined with the function name is referred to as a function definition. In other words, a function definition tells you what the function is and what it does.

Before you start creating your own JavaScript functions, keep in mind that JavaScript function name must begin with a letter or underscore (_). The function name cannot contain any spaces. Also, like variables, function names are case-sensitive. Thus calculateSalary and CalculateSALARY are considered different function names. For the function parameters, there is no limit in the number of function parameters a function contains. The function parameters must be placed inside the parentheses, following the function name, and each parameter must be separated by a comma. Pay attentions to these rules in the JavaScript functions examples shown in these pages: