JavaScript Functions

But First …


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

Note that = does not mean “equals”.

Try your equation again.

Now change x to something and try your equation.

x = 200
2 * x

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.



Create some functions on your own like the following:

Hint: the square root of x is the same as x to the 1/2 power.