# Chapter 5 Functions

Basic function

``````foo = function () {
print("hello world")
}
foo()``````
``#>  "hello world"``

Note: in the function, you need to use `print` to output

## 5.1 Parameters

Parameters and return values

``````addOne = function (x) {
return(x + 1)
}
``#>  6``

The syntax for return is like a function: `return(value)`

Parameter order can be arbitrary

``````add = function (x, y) {
return(x + (y*10))
}
``#>  102``
``add(y=10, x=2)``
``#>  102``

Functions are vectorized by default

``addOne(1:5)``
``#>  2 3 4 5 6``

All parameters are pass-by-value because functions are immutable.

``````a = 5
foo = function (a) {
a = 6
print(paste("Inside the function as a parameter: ", a))
}
print(paste("Before the function: ", a))
#>  "Before the function:  5"
foo(1)
#>  "Inside the function as a parameter:  6"
print(paste("After the function: ", a))
#>  "After the function:  5"``````

## 5.2 Scope

When you assign a value inside a function, it creates a local variable in the scope of the function. You can’t access the global variable inside the function. (OK, you can, but the syntax is so obnoxious that I pretend it doesn’t exist)

``````a = 5
foo = function () {
a = 6
b = 100
print(paste("Inside the function a =", a))
print(paste("Inside the function b =", b))
}
print(paste("Before the function a =", a))
#>  "Before the function a = 5"
foo()
#>  "Inside the function a = 6"
#>  "Inside the function b = 100"
print(paste("After the function a =", a))
#>  "After the function a = 5"
#trying to use `b` here will cause an error because it is out of scope``````

## 5.3 A function in a function

Might be useful for encapsulation

``````foo = function (a, b) {
square = function(x) {
return(x ^ x)
}
print(c(a, b))
print(c(square(a), square(b)))
}
foo(1, 10)``````
``````#>   1 10
#>  1e+00 1e+10``````

## 5.4 Dot dot dot

``````foo = function (a, b) {
return (a / b)
}
bar = function(a, ...) {
return(foo(a, ...))
}
bar(50, 10)``````
``#>  5``
``bar(b = 10, 50) # named parameter works too``
``#>  5``

## 5.5 Operators

Operators like `+` or `-` or even `[` are all functions. To use them like a function, surround them with `.

```+`(3, 4)``
``#>  7``
```*`(3, 4)``
``#>  12``
```[`(5:10, 2) # you don't need the close bracket ]``
``#>  6``