3.1: Starting a JavaScript Program
- Page ID
- 27545
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)
( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\id}{\mathrm{id}}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\kernel}{\mathrm{null}\,}\)
\( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\)
\( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\)
\( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)
\( \newcommand{\vectorA}[1]{\vec{#1}} % arrow\)
\( \newcommand{\vectorAt}[1]{\vec{\text{#1}}} % arrow\)
\( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vectorC}[1]{\textbf{#1}} \)
\( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)
\( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)
\( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\(\newcommand{\avec}{\mathbf a}\) \(\newcommand{\bvec}{\mathbf b}\) \(\newcommand{\cvec}{\mathbf c}\) \(\newcommand{\dvec}{\mathbf d}\) \(\newcommand{\dtil}{\widetilde{\mathbf d}}\) \(\newcommand{\evec}{\mathbf e}\) \(\newcommand{\fvec}{\mathbf f}\) \(\newcommand{\nvec}{\mathbf n}\) \(\newcommand{\pvec}{\mathbf p}\) \(\newcommand{\qvec}{\mathbf q}\) \(\newcommand{\svec}{\mathbf s}\) \(\newcommand{\tvec}{\mathbf t}\) \(\newcommand{\uvec}{\mathbf u}\) \(\newcommand{\vvec}{\mathbf v}\) \(\newcommand{\wvec}{\mathbf w}\) \(\newcommand{\xvec}{\mathbf x}\) \(\newcommand{\yvec}{\mathbf y}\) \(\newcommand{\zvec}{\mathbf z}\) \(\newcommand{\rvec}{\mathbf r}\) \(\newcommand{\mvec}{\mathbf m}\) \(\newcommand{\zerovec}{\mathbf 0}\) \(\newcommand{\onevec}{\mathbf 1}\) \(\newcommand{\real}{\mathbb R}\) \(\newcommand{\twovec}[2]{\left[\begin{array}{r}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\ctwovec}[2]{\left[\begin{array}{c}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\threevec}[3]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\cthreevec}[3]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\fourvec}[4]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\cfourvec}[4]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\fivevec}[5]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\cfivevec}[5]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\mattwo}[4]{\left[\begin{array}{rr}#1 \amp #2 \\ #3 \amp #4 \\ \end{array}\right]}\) \(\newcommand{\laspan}[1]{\text{Span}\{#1\}}\) \(\newcommand{\bcal}{\cal B}\) \(\newcommand{\ccal}{\cal C}\) \(\newcommand{\scal}{\cal S}\) \(\newcommand{\wcal}{\cal W}\) \(\newcommand{\ecal}{\cal E}\) \(\newcommand{\coords}[2]{\left\{#1\right\}_{#2}}\) \(\newcommand{\gray}[1]{\color{gray}{#1}}\) \(\newcommand{\lgray}[1]{\color{lightgray}{#1}}\) \(\newcommand{\rank}{\operatorname{rank}}\) \(\newcommand{\row}{\text{Row}}\) \(\newcommand{\col}{\text{Col}}\) \(\renewcommand{\row}{\text{Row}}\) \(\newcommand{\nul}{\text{Nul}}\) \(\newcommand{\var}{\text{Var}}\) \(\newcommand{\corr}{\text{corr}}\) \(\newcommand{\len}[1]{\left|#1\right|}\) \(\newcommand{\bbar}{\overline{\bvec}}\) \(\newcommand{\bhat}{\widehat{\bvec}}\) \(\newcommand{\bperp}{\bvec^\perp}\) \(\newcommand{\xhat}{\widehat{\xvec}}\) \(\newcommand{\vhat}{\widehat{\vvec}}\) \(\newcommand{\uhat}{\widehat{\uvec}}\) \(\newcommand{\what}{\widehat{\wvec}}\) \(\newcommand{\Sighat}{\widehat{\Sigma}}\) \(\newcommand{\lt}{<}\) \(\newcommand{\gt}{>}\) \(\newcommand{\amp}{&}\) \(\definecolor{fillinmathshade}{gray}{0.9}\)The next 3 subsections 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, one example of all 3 sections will be given.
3.1.1 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>
tags10.
The following points should be remembered when implementing JavaScript:
- 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.
- 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 variablesName
andname
are different. Keywords are always lower case (for
,while
, etc), and using their uppercase equivalent will not work. - 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 11, as it is considered good practice.
3.1.2 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.
Program 16 – Line comment in JavaScript 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.
Program 17 - Block comment in JavaScript /* 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.
Program 18 - Block comment in a function 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:
Program 19 - Why you should not use block comments in a function 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.
3.1.3 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. Thedocument.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.Program 20 - 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. Thedocument.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. To write a page heading, the following string can be written to the document:Program 21 - Ouput to HTML DOM with HTML tags document.write(“<h1>First JavaScript Program</h1>”)
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.
- 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.Program 22 - Writing to the console log 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.
Program 23 - alert dialog box alert(“Something”);
3.1.4 First JavaScript program
The following JavaScript program shows how to combine all of the elements described in the last 3 sections.
Program 24 First JavaScript Program <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>
The result of running this html is the following web page.
3.1.5 Quick Check
- How is JavaScript code included in an HTML file?
- How many
<script></script>
tags can be present in an HTML file? - What are the different types of comments that can be used in HTML and JavaScript?
- What happens if you put an HTML comment in JavaScript? What happens if you put a JavaScript comment in HTML?
- Can you mix HTML and JavaScript code? What happens if you mix them?
- How can you use HTML tags in JavaScript code?
- What is a dialog?
- Give an example of when you would use
console.log
,document.write
, andalert
.
10 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.
11 When teaching introductory class in JavaScript for non-majors, I often drop semicolons as they are confusing to students with no programming background. For example, an if statement that uses a semicolon, such as “if (a == 1);”, is the source of much confusion to novice programmers, and it really does not serve a good purpose to go through the pain of explaining why the if has a null statement, and what that means.