Functions

Syntax

There are different ways to construct functions. Here are 3:

1. The basic old skool (ie. not ES6) way:

...the syntax is a bit like variable but:

  1. They start with function instead of let, const or var
  2. The name of the function is followed by parentheses: myFunction(). These may contain arguments inside.
  3. Following the bracket are curly braces which contain all the code for the function.
  4. Each statement inside the curly braces is separated by a semi-colon.

Example:

    function divide(x, y, z) {
            let answer = x / y / z;
            let txt = 'the answer is: ';
            return txt + answer;
    }
        

To run the above function just like a variable you omit the first word function and then put your numbers for x, y and z in the brackets separated by commas:

divide(5, 7, 181);

Which gives: "the answer is: 0.003946329913180742"

2. Anonymous Functions

Writing functions this way means they don’t have a name, hence anonymous.

document.querySelector('pre').onclick = function() {
                alert('fuck off you moron');
            }
        

The above code works on this page but only on the first <pre> element.

3. Arrow functions

These are a new way using => to represent a function.