# Functions Workshop
---
## Today
- Introduction
- Definitons
- Gotcha's
- Examples
---
## Introduction
----
### What is a function?
Some lines of code that do a predefined task. A function may take some input and return an output.
----
### Why do we use functions?
----
#### Define reusable code
Declare code which can be used in many places to do similar things with different inputs to give different outputs.
----
#### Modularise our code
Break our code up into sections.
----
#### Help us understand our code
- Having a well named function is easier to understand than a list of statements.
- A meaningful name makes it easier to understand what the function does. A function that adds two numbers can be "addTwoNumbers".
----
### Summary - Why?
- Define reusable code
- Modularise our code
- Help us to understand what each part of our code is doing
----
### How do we use functions?
----
#### Declare the function
----
``` javascript=
function myNamedFunction (...){
// Your logic here
}
```
----
``` javascript=
const myArrowFunction = (...) => {
// Your logic here
}
```
----
#### Call the function
----
```javascript=
myNamedFunction(...);
myArrowFunction(...);
```
----
### Summary - How?
- Declare your function
- Call your function
----
## Questions?
---
## Definitions
----
### Return Keyword
The `return` keyword ends function execution and gives back a value to the function caller.
----
```javascript=
function addTwoNumbers(num1,num2){
return num1+num2;
}
let total = addTwoNumbers(2,3)
// total is assigned the returned value
```
----
Any code after the return statement will never run
----
```javascript=
function addTwoNumbers(num1,num2)=>{
return num1+num2;
console.log("Hello world") // This line will not run
}
addTwoNumbers(2,3)
```
----
### Parameters vs Arguments
A Parameter is a variable defined in a function declaration.
An Argument is the actual value of this variable that get passed to the function.
These terms are often used interchangeably.
----
```javascript=
// num1 and num2 are parameters
function addTwoNumbers(num1,num2)=>{
return num1+num2;
}
// 2 and 3 are arguments
addTwoNumbers(2,3)
```
----
### Function body
The body of a function refers to the statements inside the function (usually within curly brackets).
----
An arrow function does not need curly brackets if there's only one expression inside it.
In this case, the `return` keyword is implied (automatic) and anything after the arrow `=>` will be returned from the function.
----
You can't put more than one expression in an arrow function unless you have curly brackets.
----
```javascript=
function addTwo (num1, num2){
// This is the function body
};
```
----
```javascript=
const addTwo=(num1,num2)=>num1+num2;
// is the same as
const addTwo=(num1,num2)=>{
return num2+num2;
};
```
----
```javascript=
// this is not valid
const addTwo=(num1,num2)=>console.log(num1);return num1+num2;
```
----
### Referencing a function
Referencing a function is when we use the name of a function but do not call it.
We're telling our code which function body to run, not returning the result of running the function.
----
```javascript=
const myElement = querySelector("#my-element");
const changeElementToBlue = (event) => {
event.target.style.backgroundColor = "blue";
}
myElement.addEventListener("click", changeElementToBlue);
```
----
Notice there are no brackets.
----
If we add brackets, the function will run when we add the event listener and not when the event happens.
----
### Methods
Methods are functions which are built in to JavaScript.
----
There are different methods for different datatypes like Arrays, Objects and Strings
Some examples are `map`, `reduce`, `substring` and `splice`.
----
### Higher Order functions
A higher order function takes another function as input, or returns a new function.
This is possible because functions can be passed around like strings, numbers, arrays or objects.
----
An example is javascript's map method, which is called on arrays. This takes a "callback" function as an argument, and calls this function for every element of the array
----
```javascript=
const multiplyBy2 = (element)=>element*2;
const arr = [1,2,3,4];
const doubledArr = arr.map(multiplyBy2);
```
Map calls multiplyBy2 for every element of the array.
The result of each call of the function is returned into a new array, doubledArr.
----
### Callbacks
Callbacks are functions that are passed into a higher order function, to be called **later**.
----
```javascript=
const multiplyBy2 = (number)=>number*2;
const arr = [1,2,3,4];
const doubledArr = arr.map(multiplyBy2);
// Notice here that we reference our function
// rather than calling it.
```
----
In this example, multiplyBy2 is a callback.
----
Here's an example of a higher order function that we've created:
```javascript=
const multiplyBy2 = (number)=>number*2;
const doSomething = (value, action)=> action(value);
const doubled = doSomething(2,multiplyBy2);
```
1. multiplyBy2 is called by doSomething
2. 2 is passed in as "number"
3. We get 4 as the return value.
----
### Scope
Scope is the context in which a variable can be accessed.
----
**Global variables** are defined outside any function blocks and can be accessed anywhere
----
**Local variables** are defined within a function block and can only be accessed within that function.
----
```javascript=
let myGlobalVariable = "Hello";
const stringMaker = (){
let myLocalVariable = "World";
return myGlobalVariable + " " + myLocalVariable
};
console.log(stringMaker()) // logs "Hello World"
consolg.log(myLocalVariable) // causes error
```
----
## Questions??
---
## Gotcha's
----
### Passing a global variable into a function means the function interprets it as a parameter, resetting the value.
----
```javascript=
let myString = "Hello World";
function logTheWords(myString){
console.log(myString);
};
logTheWords("Tortoise");
// logs "Tortoise" not "Hello World"
```
----
### Argument order matters, especially when using higher order functions like map/reduce etc.
----
```javascript=
let divideNumbers = (num1, num2) => num1/num2;
const firstResult = divideNumbers(1, 4);
const secondResult = divideNumbers(4, 1);
console.log(firstResult === secondResult)
// Logs false
```
----
## Questions??
---
## Examples
---
{"metaMigratedAt":"2023-06-15T16:56:26.717Z","metaMigratedFrom":"YAML","title":"Functions Workshop","breaks":true,"contributors":"[{\"id\":\"2967aacf-1990-431e-b963-91e79ce4a2bf\",\"add\":7486,\"del\":4810},{\"id\":\"fe34a90e-d4b7-4af4-aa2e-64bfeaf42064\",\"add\":4315,\"del\":512}]"}