JavaScript Code, Where Do We Put It?

JavaScript is a programming language originally conceived and implemented to reside in web pages in order to enhance their behaviour. Some mavens call JavaScript a scripting, rather than a programming language. The intended meaning is that scripting languages are less than compiled languages. Thism apart from being derogatory, is plainly wrong.

Scripting languages, thus JavaScript are interpreted languages. This means that their code is interpreted on on the fly, and executed according to it's content. A compiled language is compiled from code into another file format which in turn is being executed by a computer. In our context, we will look at JavaScript in relation to the interpreter built into today's modern browsers. To be quite precise, actually JavaScript is not really interpreted, but rather compiled on the fly, and the result of that compilation is what is executed. Because this compiled code is not saved as a file in it's compiled form, JavaScript is still classified as an interpreted language.

It should be indrectly clear that here we consider JavaScript in its browser, client, context. There is another, the server context. We will discuss that later when we deal with the backend.

JavaScript's Structural Place

Where From?

The JavaScript for a page is requested via the page. When the user clicks a link or fills in the url area in the browser, a page is requested. This creates subsidiary requests for whatever JavaScript is referred from that page.

What and Why?

In order to enrich the experience of reading web pages beyond reading "dumb," read static, content situated in HTML5 elements put there by a web designer, we need programming to activate some behaviour of the page. This programming is written in the JavaScript language as part of the web page. Let us first see how the JavaScript fits into the structure of the HTML5 document.

Generally speaking JavaScript code can occur anywhere in an HTML5 document as long as it is held in a script element.

If there's any remote chance that the JavaScript may be used elsewhere, or even for aesthetic reasons, not mixing JavaScript code with HTML5 we prefer to write the JavaScript code in a separate file, and then referring to that from the HTML5.

JavaScript after Body
Example 1.4. The JavaScript, hw00b.js
let targets = document.getElementsByClassName('title');
for(let i = 0; i < targets.length; ++i) {
    targets[i].innerHTML = 'Hello, World!';
}

Example 1.5. The HTML5 hw00b.html
<!doctype html>
<html>
    <head>
        <meta charset='utf-8'/>
        <meta name='viewport' content='width=device-width, initial-scale=1.0'/>
        <title class='title'></title>
        <link rel='icon' type='image/svg+xml' href='./favicon.svg'/>
    </head>
    <body>
        <h1 class='title'></h1>
        <script src='./js/hw00b.js'></script>
    </body>
</html>

View in browser.


JavaScript in the Head
Example 1.6. The JavaScript, hw00h.js
'use strict';

const go = function () {
    let targets = document.getElementsByClassName('title');
    for(let i = 0; i < targets.length; ++i) {
        targets[i].innerHTML = 'Hello, World!';
    }
}

window.addEventListener('load', go);

Example 1.7. The HTML5 hw00h.html
<!doctype html>
<html>
    <head>
        <meta charset='utf-8'/>
        <meta name='viewport' content='width=device-width, initial-scale=1.0'/>
        <title class='title'></title>
        <link rel='icon' type='image/svg+xml' href='./favicon.svg'/>
        <script src='./js/hw00h.js'></script>
    </head>
    <body>
        <h1 class='title'></h1>
    </body>
</html>

View in browser.


Where Needed, Another Structure
Example 1.8. Structural Example 0
<!doctype html>
<html>
    <head>
        <meta charset='utf-8'/>
        <meta name='viewport' content='width=device-width, initial-scale=1.0'/>
        <title>js demo</title>
        <link rel='icon' type='image/svg+xml' href='./favicon.svg'/>
        <link rel='stylesheet' href='./nml00.css'/>
        <script src='./nml00.js'></script>
    </head>
    <body>
        <header><h1>demo</h1></header>
        <main>
            <div>
                <script>document.write(f2c());</script>
            </div>
            <p>
                Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?
            </p>
        </main>
    </body>
</html>

View in browser.


Let us look at the JavaScript itself:

Example 1.9. Fahrenheit to Celsius, nml00.js
'use strict';
/* print conversion table
   fahrenheit to celsius */
const f2c = function () {
    let fahr;
    let celsius;

    let lower = 0;                       // define constants
    let upper = 300;
    let step = 20;

    let s = '<table>';
    s += '<tr><th>Fahrenheit</th><th>Celsius</th></tr>';
    fahr = lower;
    while (fahr <= upper) {
        celsius = 5 / 9 * (fahr - 32);   // the conversion formula
        s += `<tr><td>${fahr}</td><td>${celsius}</td></tr>`;
        fahr = fahr + step;
    }
    s += '</table>';
    return s;
}

Lines delimited by /* and */, lines 2-3, are comments, which in this case explains briefly what the program does. Comments are ignored by the interpreter; they may be used freely to make a program easier to understand. Comments may appear anywhere a blank or tab or newline can. These comments are called C-comments because they are from that language.

Further down the code, in line 7, we see the text // define constants from column 40. Text starting with double slashes are called C++ comments, and they too, are ignored by the interpreter.

Please notice how the JavaScript code in the separate JavaScript file(s) does not have script tags. The script tags are supplied in the HTML5 document when you reference the JavaScript file.

In JavaScript when using "use strict";, all variables must be declared before they are used, often at the beginning of your code before any executable statements. A declaration consists of an appropriate keyword name and one, or a list of variables, such as

let fahr;
let celsius;

let lower = 0;
let upper = 300;
let step = 20;

The keyword used for declaring variables in this case is let. Please notice that you may declare variables without assigning values to them, or you may assign initial values to them while declaring them.

It is a common misunderstanding that in JavaScript variables are untyped. In JavaScript variables are dynamically typed assuming the type of whatever value assigned to them. JavaScript has only one numeric type number. It corresponds to the double type of other languages, a floating point number with a fractional part. The number type is a 64-bit quantity with 53 significant bits and an 11 bit exponent including a sign bit. This results in a magnitude generally between about 1.8 x 10308 and 1.8 x 10308. Integer precision is guaranteed for numbers between -(253 - 1) and 253 - 1.

Each line of the table is computed the same way, so we use a loop that repeats once per output line; this is the purpose of the while loop

while (fahr <= upper) {
            ...
}

The while loop operates as follows: The condition in parentheses is tested. If it is true (fahr is less than or equal to upper), the body of the loop (the three statements enclosed in braces) is executed. Then the condition is re-tested, and if true, the body is executed again. When the test becomes false (fahr exceeds upper) the loop ends, and execution continues at the statement that follows the loop. There are no further statements in this program, so it terminates.

The body of a while can be one or more statements enclosed in braces, as in the temperature converter, or a single statement without braces, as in

while (i < j)
    i = 2 * i;

In either case, we will always indent the statements controlled by the while by one tab stop {which we have shown as four spaces} so you can see at a glance which statements are inside the loop. The indentation emphasizes the logical structure of the program. Although JavaScript interpreters do not care about how a program looks, proper indentation and spacing are critical in making programs easy for people to read. We recommend writing only one statement per line, and using blanks around operators to clarify grouping. The position of braces is less important, although people hold passionate beliefs. We have chosen one of several popular styles. Choose a style that suits you, then use it consistently[4].

Most of the work gets done in the body of the loop. The Celsius temperature is computed and assigned to the variable celsius by the statement

celsius = 5 / 9 * (fahr-32);

This example also shows a bit more of how to build strings from string constants and variables. One way to do that is by delimiting the string with backtics, and then designate the variables in the string with ${...} so the statement

document.write(`<tr><td>${fahr}</td><td>${celsius}</td></tr>`);

causes the values of the two numbers fahr and celsius to be printed nicely wrapped in HTML5 markup.

Readability may be improved by pushing a new line into the code after calculating celsius and before printing it.

    celsius = celsius.toFixed(2);

The toFixed function for numbers, rounds the number to the given number of decimal places. Later we shall improve readability by dropping document.write for using the DOM directly.

Code Validation, Linting[5]

Program code in script elements must of course do what you intend it to do. No validator in the world would be able to look inside your mind, then into the code, then decide whether what was in the code reflect your mind so that the code must then be correct, valid. Validation in this sense, logically, is not possible.

We are, however, able to have our JavaScript code checked from a syntactic, grammatical point of view. There are services out there that will help you do that. There is a condition. The general rules of grammar in JavaScript are liberal, very liberal. The condition for the enormous help of a validator, is that you forsake some liberties, and instead submit yourself, and your JavaScript code to some stricter rules. In return you get, as I stated, the help of the validator. You get the benefit of easy to read JavaScript, properly indented, etc. This is a contribution to much easier maintainability.

Douglas Crockford, [Cro08] invented jsLint, a static code analyzer many years ago, re http://www.jslint.com/. The more modern successor is http://www.jshint.com.

These services issue warnings rather than actual errors. Some of the warnings are errors and must be corrected, others are petty warnings and may be ignored. Personally I choose to accept some warnings that are a reflection of my personal coding style.



[4] The style used in these materials is K&R variant Java, please refer to [WPIS].

[5] For reading about the origin of linting please refer to lint (software)