12/14/2017 - 10:27 AM

JS Functions

In JavaScript, functions are often called first-class citizens, meaning they can be treated like other JS datatype such as a number, string, array....
E.g. you can pass a function into another function as an argument.

Named Functions
-invoked when called by name
-Named functions are useful if we need to call a function many times to pass different values to it or just need to run it several times and it's also useful when functions just get really big and just clutter up the overall flow of the script. In that case, we create functions and put them above the main script to be called when needed.

Anonymous Functions
-run once triggered by a specific event
-setting a variable = anon function you can hook up anonymous functions to events, and in that case, the function is what is returned, not the result of the function.
-but if the variable = the function itself and not the result of the function, how do you set a variable equal to the result of a function? You use an immediately invoked function expression

Immediately Invoked Functions
-run the moment the browser encounters them
-to create, just wrap an anon funct in parens and then add '()' at the end.
-since it runs immediately, variables you pass into the function need to be set BEFORE/ABOVE the function

// NAMED FUNCTIONS, called explicitly by name:
function multiply() {
    var result = 3 * 4;
    console.log("3 multiplied by 4 is ", result);

// ANONYMOUS FUNCTIONS stored in variable.
// Invoked by calling the variable as a function:
var divided = function() {
    var result = 3 / 4;
    console.log("3 divided by 4 is ", result);

// Runs as soon as the browser finds it:
(function() {
    var result = 12 / 0.75;
    console.log("12 divided by 0.75 is ", result);