JavaScript

Functions

Function Declaration

function foo() {}
  • Processed before the code in a JavaScript file is executed
    • Meaning you can use a statement that calls a function before it is defined
    • Known as function hoisting

Function Expression

let foo = function() {}
  • Not subject to hoisting,
    • Meaning that you can not call foo before its occurrence in the source

Examples

Battleship Game

// Return a random integer between min and max
// Both values inclusive
function getRandomIntInclusive(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function playGame() {
    const head = getRandomIntInclusive(0, 4);
    const shipLocations = new Set([head, head + 1, head + 2]);

    // Uncomment if you want to cheat!
    // shipLocations.forEach(value => {
    //     alert(value);
    // });

     while (shipLocations.size !== 0) {
        const shot = prompt('Shoot!');
        if (shipLocations.has(parseInt(shot))) {
            alert('Boom!');
            shipLocations.delete(parseInt(shot));
        } else {
            alert('No!');
        }
    }

    alert('You won!');
}

playGame();

Fetch API and Markdown to HTML Example

Fetch API Documentation

<!DOCTYPE html>
<html>
<head>
    <title>About Me Page</title>
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
</head>
<body>
<div id="content"></div>
<script>
    fetch('https://gitlab.com/api/v4/projects/6735489/repository/files/about.md/raw?ref=master')
    .then(response => {
        response.text().then(function (content) {
                document.getElementById("content").innerHTML = marked(content);
            }
        )
    });
</script>
</body>
</html>

References