Defining Functions
A function is a named block of code that we can run again whenever we need it. Functions are one of the main pieces we build JavaScript programs out of.
Basic Function Structure
Here is a simple function in JavaScript that adds two numbers:
function total(x, y) {
return x + y;
}
JavaScript functions work much like functions in other programming languages:
- They can accept zero or more named parameters.
- They group a set of statements together. That group is called the function body, and it does the work of the function.
- They create a local scope: variables declared within a function are accessible only within that function.
- They may return a value using the
returnstatement, which also stops the function right away.
Differences from Other Languages
JavaScript functions differ from Java or C++ functions in two ways:
- They do not require type declarations for parameters or return values.
- If no value is explicitly returned, JavaScript functions return
undefined.
JavaScript functions are also first-class values, which means a function is a value like any other. We can assign a function to a variable, pass it as an argument to another function, or return it from a function.
const sum = total;
console.log(sum(2, 1)); // 3
Invoking Functions
To run a function, write its name followed by parentheses. Any arguments go inside the parentheses:
const result = total(2, 1);
If we want to refer to a function without calling it, we write the name and leave the parentheses off. We do that when we want to pass the function as a value or assign it to another variable:
const sum = total;
const result = sum(2, 1);
console.log(result); // 3