Writing Your First JavaScript Program

The next sections of this book will describe how to insert a JavaScript program into an HTML file, how to insert comments into JavaScript, and how to write output to the HTML page. At the end of this part, we’ll look at a complete example.

Inserting JavaScript into an HTML file

JavaScript is used to create interactivity in a HTML web page. JavaScript is not part of HTML but is a scripting language that is contained in an HTML document and is interpreted by a JavaScript engine in the browser. It is inserted into an HTML file by enclosing the JavaScript program between <script> and </script> tags.

Note: HTML was designed to handle scripting languages other than JavaScript. The <script> tag contains an attribute named language, and it is still possible to find HTML code that uses the <script language="javascript"> tag. However, no scripting language except JavaScript was ever seriously used in HTML. The <script> tag now does not need the language attribute, and it is seldom used unless some scripting language other than JavaScript is used.

The following points should be remembered when implementing JavaScript:

  1. JavaScript is not HTML. If you place JavaScript source in a non-scripting portion of an HTML web page, it will likely just print out on the page. If you place HTML source in a JavaScript portion of the page, the JavaScript program will likely fail with completely unpredictable consequences. Only use JavaScript programs inside of script tags.
  2. HTML is not case sensitive. The <i> and an <I> tag are interchangeable. For consistency and readability, one case should be selected and used, but there is no rule that says a body tag cannot be entered as <bODy>. However, JavaScript is case sensitive. The variables Name and name are different. Keywords are always lower case (for, while, etc), and using their uppercase equivalent will not work.
  3. JavaScript statements should end with a “;” (semicolon). However, in most cases the language does not care if you include this semicolon or not. This text will attempt to always use the semicolon to end all statements, as it is considered good practice.

JavaScript Comments

Comments in JavaScript are the same as comments in C derivative languages. There are two types of comments. The first type of comment is a line comment. A line comment is signified by a //, and all of the subsequent text on that line is a comment. An example of declaring a variable and commenting is illustrated on the following line.

let loopCount; // Counter for string processing loop

The second type of comment is a block comment. Block comments begin with a /* and continue until the program has a */. The following is a block comments.

/*
    This function calculates the velocity given the speed and time 
*/

Often novice and even intermediate level programmers will use these two types of comments interchangeably. This can lead to problems, particularly when commenting out lines of code while debugging. For example, consider the following code block where the comment for the variable is done using a block comment.

function f() {
    let loopCount; /* Counter for string processing loop */
}   

If something is wrong with the function, a common debugging tactic is to put a line of code in the program to show the program is entered, and then to comment out the rest of the program:

function f() {
    console.log("in function f");
    /*
    let loopCount; /* Counter for string processing loop */ 
    */
}

This comment will not work, as /* and */ tokens are not matched. The /* signals the start of the comment, and the comment ends when a */ is encountered. The highlighted /* and */ tokens are matched above. This leave the */ at the end of the function outside of a comment, and this will produce an error.

A good rule for using line and block comments is to use block comments for the documentation of a function that appears before the function. Comments that occur inside of the function should use line comments. This is the commenting strategy used in this book.

Output from a JavaScript program

JavaScript program output is normally written either to the web page that contains it, the console if it is information that is only of use to a programmer, or to a dialog box. These three options are explained below.

  • Output can be written it on the web page so that the user can see it. To write HTML code on the document, the document.write() function is used. The document.write() function can be used to write any HTML formatted string of information to the web page. For instance, to write the string “This is my first web page with JavaScript…” fromJavaScript, the following line of JavaScript can be added to the body of the web page.
// Output to HTML DOM from JavaScript
document.write("This is my first web page with JavaScript...");
  • The string passed to the document.write() function can be any HTML formatted string. The document.write() function does not simply output text on the page; document.write writes the text to the document, and the document will then correctly parse and render the output in the HTML string on the web page. Any valid html tag or statement can be written to a page, as the string which is written is effectively written to and interpreted as HTML by the browser processing the page. To write a page heading, the following string can be written to the document:
 // Ouput to HTML DOM with HTML tags
 document.write("<h1>First JavaScript Program</h1>")
  • The second way to produce output is used for debugging and involves printing information which is not intended to be seen by the normal user. This output is written to the web page console. The console is used to write output that is intended to be used by programmers and others who might be supporting this site. The web console can be accessed from all major browsers, but how to access it and even some constraints on how the information is displayed are different for every browser. For example, in Chrome the browser the ctrl-shift-i key will bring up the developer tools, and from there the console can be selected. You should search the internet on how to access the Web Console for your specific browser.

    The Web Console is an invaluable place to write debug output, and other information that a programmer might want the program to produce but not let the end users see. To write to the Web Console, pass a JavaScript element (string, object, etcetera) to the console.log() function, as in the following line of code.

console.log("The program is running")
  • The final way to output (and input) text from a program is to use a dialog box. Here only the output dialog box, created by using the alert function, is shown. Input will generally be handled in forms, so input dialogs, except for specialized dialogs such as file dialogs, are not that useful, and so are not covered. To create an output dialog box, run the alert function as follows.
alert("Something");

First JavaScript program

The following JavaScript program shows how to combine all of the elements described in the last 3 sections.

<html>
    <body>
        <script>
            /*
                This is an example of JavaScript
            */
            console.log("The program is running") // Write to the console
        
            document.write("<h1>First JavaScript Program</h1>") //Print head
            document.write("This is my first web page with JavaScript.");
            document.write("<br/>This is on a new line");
        
            alert("Here is an alert box");
        </script>
    </body>  
</html>  

First JavaScript Program

The result of running this html is the following web page.

Quick Check

  1. How is JavaScript code included in an HTML file?
  2. How many <script></script> tags can be present in an HTML file?
  3. What are the different types of comments that can be used in HTML and JavaScript?
  4. What happens if you put an HTML comment in JavaScript? What happens if you put a JavaScript comment in HTML?
  5. Can you mix HTML and JavaScript code? What happens if you mix them?
  6. How can you use HTML tags in JavaScript code?
  7. What is a dialog?
  8. Give an example of when you would use console.log, document.write, and alert.

Licenses and Attributions


Speak Your Mind

-->