A Brief Overview of Functions
Tags: webdev, beginners, javascript, tutorial
Published: 2023-01-31 17:58:55

If you’ve spent any time at all with Javascript, you’ll probably know that functions are a very important part of the language. Functions use code statements, like instructions in a recipe, to do work, or to calculate a value. One function can do the same work for multiple sources of data, removing the need to repeat our code over and over again. Doesn’t that sound great? The following is a brief overview of the parts of a function, how to use functions, and how to choose the most appropriate type of function for your code.

#Parts of a Function

Take a look at this example function declaration.
``` javascript
function add(a, b) {
    return a + b
}
```

###Function Keyword
This function declaration starts with the function keyword.

###Function Name
Some functions have names, which allows us to “call” those functions into action. In the example above, the function name is "add". Functions without names are known as “anonymous functions”. We’ll cover those later.

###Parameters
In the example above, the parameters are "a" and "b". Functions may or may not expect parameters, or rather named variables or data to be provided to them. If parameters are included, the function will expect them to appear somewhere within the function body at least once. Parameters are essentially placeholders for arguments when calling the function.

###Function Body
The function body follows the parameters, and is home to the statements. In most cases, it is represented by curly braces.

###Statements
Statements are the lines within the function body which detail specific tasks for the function to perform. A function body can contain many statements. In the example above, the sole statement is ``` javascript
return a + b
```

###Return value
Functions may or may not have a return value. After completing the work outlined by the statements, a function may “return” a value based on that work. Another way to frame this, is the function resolves to a specific value like a variable does. That value could be any data type, like a string, number, array, object, or even another function!

###Arguments
Arguments are used when calling a function. The arguments passed to a function take the place of the parameters, and act as inputs for the function so it can do something with them.

#How to Use a Function




###Invoking a Function
This involves typing out the function or variable name, followed by ( ), with any arguments passed inside the parentheses. 

``` javascript
add(2, 5)
```

#Types of Functions




###Function Declaration
Perhaps the most common way to create a function is with a function declaration. Our add function from above is an example of a function declaration. Function declarations are **hoisted**, which means they can be invoked before they are defined. This is especially helpful, so function declarations are a great way to go when deciding which type of function to create. Function expressions on the other hand, are not hoisted.

###Function Expression
``` javascript
const subtract = function (a, b) {
   return a - b
}
```
* A function expression differs from a function declaration in that the function is assigned to a variable.
* A traditional function expression starts with either the const or let keyword, followed by the variable name. It is then set equal to the “function” keyword, followed by parentheses for the parameters and curly braces for the function body.
* Immediately Invoked Function Expressions can be either named or anonymous, and invoked immediately by adding an extra set of parentheses to the end of the function. 
* This avoids needing to call the function elsewhere in the code.
``` javascript
const subtract = function (a, b) {
   return a - b
}()
```


###Callback Functions
Callback functions are functions passed as arguments to other functions.
``` javascript
function cb(num) {
   return num * 2
}

function add(a, cb) {
   return a + cb
}

add(3, cb(2))
//=>returns 7
```
In this example, cb is our callback function, and it takes a number as it's argument. When add is called, it returns 3 + ((2 * 2)) which equals 7.

###Arrow functions
Arrow functions are a special type of function expression. Their syntax can be simplified and comes with some added benefits. Arrow functions take parameters in the usual way, but the parameters are followed by => before the curly braces of the function body.
``` javascript
const multiply = (a, b) => {a + b}
```

###Special Cases for Arrow Functions
* If the arrow function has only one parameter, the parameter does not need to be surrounded by parentheses.
* If the arrow function has only one statement, it doesn’t need the curly braces for the function body. The function body can instead be written as one line of code after the arrow.
``` javascript
const log = a => console.log(a)
```
* Arrow functions allow us to keep simple functions short, tidy and easy to interpret.
* Arrow functions with a single statement (known as a “concise body”), have an “implicit return value”, which means they return a value without requiring the “return” keyword. Arrow functions with more than one statement (known as a “block body”), will require the “return” keyword if they should return a value.
* Arrow functions don’t create their own context, so when using the “this” keyword, and nesting functions, arrow functions allow us to avoid using .bind or similar methods to set our context. This can be extremely helpful, as keeping track of a nested function's context can be challenging.

###Anonymous functions
``` javascript
setTimeout(() => console.log('Wait 1 second'), 1000);
```
Anonymous functions are function expressions, typically passed as callback functions. Only function expressions can be anonymous. Arrow functions can be anonymous functions. In our example above, our anonymous arrow function is
``` javascript
() => console.log('Wait 1 second')
```

###Asynchronous functions
Async functions allow our functions to do work without holding up the rest of our code. They do work outside the normal execution context. This helps web pages load quickly while information is gathered and processed behind the scenes. Our setTimeout function is an example of an async function. It accepts, as arguments, a callback function (in this case an anonymous arrow function), and a number of milliseconds to wait before executing the callback function.
``` javascript
setTimeout(() => console.log('Wait 1 second'), 1000);
```

###Recursive functions
Recursive functions are functions which call themselves until they meet a condition which tells them to stop. 

As you can see, there are a whole bunch of different functions, all with their distinct perks and limitations. Many of these function types perform similarly, but you’ll find specific situations for each in your work. Choosing the right type for a given scenario can pay dividends, making your code more succinct, effective, and communicative.