Javascript anatomy

From wikinotes

Javascript is used in a variety of places.
Here are some common entrypoints, and some sample code to get a feel for it.

NodeJS CLI

${PROJECT}/main.mjs


#!/usr/bin/env node
import * as Process from 'node:process'
import * as Path from 'node:path'


const EXECUTABLE = Path.basename(Process.argv[1]);


class CliCommand {
  help = false;
  verbose = false;

  static fromArgs() {
    var cmd = new CliCommand();
    var argv = Process.argv.slice(2);
    while (argv.length) {
      var item = argv.shift();
      switch (item) {
        case "-h": case "--help":
          cmd.help = true;
          break;
        case "-v": case "--verbose":
          cmd.verbose = true;
          break;
        default:
          console.error(`Invalid Param: '${item}'. See --help`);
          Process.exit(1);
      }
    }

    return cmd;
  }

  exec() {
    if (this.help) {
      showHelp();
      Process.exit(0);
    }

    if (this.verbose) {
      console.debug("loggers set to stun");
    }

    console.log(".. your program starts here");
  }
}


function showHelp() {
  var msg = `${EXECUTABLE} [-h] [-v]

  ARGS:
    -h --help
      show this help message.

  EXAMPLE:
    ${EXECUTABLE} -h  # show help
  `.trim()
  console.log(msg);
}



function main() {
  var cmd = CliCommand.fromArgs();
  cmd.exec();
}


main();
./main.mjs -h  # run

Web Browser

Script Tags

One way that javascript can added to HTML within a <script> tag.
You can enter it directly, or set the src= parameter.
All HTML elements defined above the <script is accessible within it (and not items below).

<script>
  function myFunction() {
    document.getElementById("demo").innerHTML = "Paragraph changed.";
   }
</script>
<script src="myscript.js"></script>
<script src="https://foo.com/js/foo.js"></script>

You can use script tags anywhere, but this is discouraged in the Http content security policy.

<div>
  <script>
    document.getElementById("foo").innerHTMLL = "BAR";
  </script>
</div>

ES6 Modules

ES6 modules let you import your code from other files (ex import * as Math from './modules/math.js').

Note for testing: ES6 modules) do not work when loading webpages directly from the filesystem.
You can use a tiny toy web-server like python http or golang simple-go-web-server to load your javascript instead.

${PROJECT}/index.html

<!doctype html public "-//W3C//DTD HTML 4.01 Frameset//EN"
  "http://www.w3.org/TR/html4/frameset.dtd">
<html lang="en">
  <head>
    <title>My Website</title>
    <script type="module" src="main.js"></script>
  <!--   <link rel="stylesheet" href="stylesheet.css" /> -->
  </head>
  <body>
    <h1>My Title</h1>
    <p>Some paragraph</p>

    <div id="sum-div">
      <button id="sum-btn">Add</button>
      <input class="addend" type="text" placeholder="1">
      <input class="addend" type="text" placeholder="2">
      <span>=</span>
      <input class="result" type="text" readonly="1">
    </div>
  </body>
</html>

${PROJECT}/main.js


import * as Math from './modules/math.js'


function sumClicked() {
  var sum_btn = document.getElementById("sum-div");
  var addend_inputs = Array.from(sum_btn.querySelectorAll(".addend"));
  var addend_values = addend_inputs.map((input) => { return Number(input.value) });
  var sum = Math.sum(...addend_values);

  var result_input = sum_btn.querySelector(".result");
  result_input.setAttribute("value", String(sum));
}


document.getElementById("sum-btn").addEventListener("click", sumClicked);

${PROJECT}/modules/math.js


export function sum(a, b) {
  return a + b;
}

export function multiply(a, b) {
  return a * b;
}


open 'http://localhost:3000'
simple-go-web-server --hot
# reload to get changes

On Event Hooks

You can register callbacks to events on matching items.

document
  .getElementById('button')
  .addEventListener('click', () => { /* do something when clicked */ })

You also can trigger javascript from HTML DOM events, with the on${Event} syntax.
This is now discouraged for security reasons (See Http content security policy)

<button onClick="console.log('hello');">Log Hi</button>

Javascript Console

Most browsers have a javascript console where you can execute arbitrary javascript commands on a loaded webpage.
While you cannot evaluate files directly from your filesystem, but you can use a toy webserver like golang simple-go-web-server
to host your files, and then source them within the JS console.

// dir-with-js/foo.js

console.log("HI");
cd dir-with-js
open 'http://localhost:3000'
simple-go-web-server --hot
# reload to get changes
// javascript console
$.getScript("http://127.0.0.1:3000/foo.js")

Web Browser, Bundled javascript