JavaScript Functions
Async
Here’s a module example that exports a function with a promise.
./modules/stats.js
export function calcScoreAvg(scores) {
return new Promise(resolve => {
let sum = 0,
len = scores.length;
for(let i=0; i < len; i++) {
sum += Number(scores[i].strokesTotal);
}
resolve(sum / len);
});
}
example async function usage
import { calcScoreAvg } from './modules/stats';
const scores = [{
"strokesTotal": 80, "course": "Falls Road Golf Course", "tee": "Black"},{
"strokesTotal": 77, "course": "Twin Lakes Golf Course", "tee": "White"},{
"strokesTotal": 81, "course": "Stonewall Golf Club", "tee": "White"},{
"strokesTotal": 82, "course": "Laytonsville Golf Course", "tee": "Blue"},{
"strokesTotal": 79, "course": "Enterprise Golf Course", "tee": "White"
}]
const scoreAvg = async (scores) => {
const result = await calcScoreAvg(scores);
console.log(result);
}
Function Statement
The natural function declaration or statement is what new JavaSript developers are introduced to.
function helloWorld() {
console.log("Hello World");
}
helloWorld(); // logs "Hello World" to the console.
Function Expression
var message = "Hello World";
var helloWorld = function() {
console.log(message);
}
helloWorld(); // logs "Hello World" to the console.
Immediately Invoked Function Expression (IIFE)
Executes the function immediately upon it’s creation. The parentheses () for immediately invoking the function are contained in the outer parentheses. The outer parentheses make the function a function expression.
(function() {
var message = "Hello World";
console.log(message);
})();
The parentheses () for immediately invoking the function is contained in the outer parentheses. This behaves the same, it is just a styling preference.
(function() {
var message = "Hello World";
console.log(message);
}());
DOMContentLoaded Document Event Example
(function() {
var message = "Hello World";
function onDocumentReady() {
console.log(message);
}
if (document.readyState !== "loading") {
onDocumentReady();
} else {
document.addEventListener("DOMContentLoaded", onDocumentReady);
}
}());