functions

Functions can be initialised is a couple of ways, we have the normal function declaration and also function expressions in which functions are declared as variables. Notice that the expression requires as semi colon where as the declaration does not.

function declaration and expression


function greet(name) {
  console.log(`hello ${name}`)
}

greet("Bob") // hello Bob

const greeting = function(name) {
  console.log(`hello ${name}`)
};

greeting("Jane") // hello Jane
			

Functions can have values set in their definition that provide default values, for the case in which values are not provided.


const speak = function(name = "Luigi", time = "night") {
  console.log(`good ${time} ${name}`
};

speak(); // good night Luigi
speak("day", "Jill"); // good day Jill
			

arrow functions

There is another way to express functions known as the arrow function. It is for the most part the same as function expressions, except for some slightly different behaviour concerning the "this" key word, "this" will be covered a little later on.


const area = (radius) => {
  return 3.14 * radius**2;
};
console.log(area(51) // 8167.14

const area2 = radius => {
  return 3.14 * radius**2; // 11304
};
console.log(area2(60); // 8167.14

const greeting = () => {
  console.log("hello");
}
greeting(); // hello

const square = x => x * x;
console.log(square(4)); // 16
			

callback functions

Functions can also be passed into a function as an argument, to be called by that function within its procedure or used in some other way by that function; These are known as callback functions.


const doThis = (callbackFunc) => {
  let value = 40;
  callbackFunc(value);
}

doThis(function(value){
  console.log(value);
});

doThis(value => {
  console.log(value);
});
			

forEach

forEach is an example of a method on a type that takes a callback function.


let people = ["bob", "jim", "jane", "sue", "willy"];

people.forEach(person => {
  console.log(person);
});

people.foreach((person, index) => {
  console.log(index, person);
});
			

defining html with a callback


const ul = document.querySelector(.people);
let people = ["bob", "jim", "jane", "sue", "willy"];
let html = ``

people.forEach(person => {
  html += `<li style="color: purple">${person}</li>`
});

ul.innerHTML = html;