# JavaScript Functions

## But First …

## Basic

Write some simple related math equations:

```
2 * 2
2 * 4
2 * 20
```

Which of the numbers changing? (`variable`

)

Replace the `variable`

with a letter.

```
2 * x
Uncaught ReferenceError: x is not defined
at <anonymous>:1:1
```

Notice it fails because there is no `x`

.

Declare `x`

to exist.

`let x`

Assign `x`

a number.

```
x = 20
2 * x
40
```

Note that `=`

does not mean “equals”.

Try your equation again.

Now change `x`

to something and try your equation.

```
x = 200
2 * x
400
```

All this changing of `x`

is getting pretty tiresome. You know what they say, the best programmers are *lazy* programmers.

Let’s put our equation `2 * x`

into a *function*. A function is like a machine you can put stuff in, `x`

in this case.

Put an `x`

and a *fat arrow* in front of your equation.

```
x => 2 * x
ƒ
```

Notice the `ƒ`

which means it’s a *function*.

Also notice it does not do anything.

Let’s give our function a name how about `double`

.

`let double = x => 2 * x`

Notice that `double`

is just like any other *variable*. A first class function is just another data type in JavaScript. Can you name some the other data types?

Here’s a reminder:

```
let name = 'Mr. Rob' // string
let count = 1 // number (integer)
let percent = 0.85 // number (float)
let likesCode = true // boolean (true/false)
let double = x => x * 2 // first-class function
```

Now let’s try out our `double(x)`

function.

```
double(20)
40
double(4234)
8468
```

### Challenges

Create some functions on your own like the following:

`decr(x)`

that returns`x`

with 1 subtracted.`incr(x)`

that returns`x`

with 1 added.`triple(x)`

that returns three times the value`x`

.`square(x)`

that returns`x`

to the power of 2.`sqroot(x)`

that returns the square root of`x`

Hint: the square root of `x`

is the same as `x`

to the `1/2`

power.