Functions

Introduction

Function declaration

Variables created without a declaration keyword (var, let, or const) are always global, even if they are created inside a function.

function myFunction(a, b) {
  return a * b;
}
myFunction(10, 2);

Function scope

We might expect the following to fail, but it doesn’t.

function myFunction() {
    x = 5;
}
myFunction();
var y = x;

The following does fail, as x has not been declared.

"use strict";
function myFunction() {
    x = 5;
}
myFunction();
var y = x;

As does the following, because declaring the variable keeps it in the scope of the function.

"use strict";
function myFunction() {
    var x = 5;
}
myFunction();
var y = x;

Function expressions

The function here is an anonymous function. We just happen to be naming it.

const myFunction = function(a, b) {
    return a * b
};

Function expressions are not necessarily in the global score, and so can be preferred.

Arrow function expressions

Another way of writing function expressions.

const myFunction = (a, b) => a * b;

Again this is an anonymous function, that has happened to have been named. The function itself can be used as a parameter in eg a map.

Callbacks

pass function as argument

function myDisplayer(some) {
  document.getElementById("demo").innerHTML = some;
}
function myCalculator(num1, num2, myCallback) {
  let sum = num1 + num2;
  myCallback(sum);
}
myCalculator(5, 5, myDisplayer);

Sort

dynamically typed functions