034.1 Lesson 1
Certificate: |
Web Development Essentials |
---|---|
Version: |
1.0 |
Topic: |
034 JavaScript Programming |
Objective: |
034.1 JavaScript Execution and Syntax |
Lesson: |
1 of 1 |
Introduction
Web pages are developed using three standard technologies: HTML, CSS, and JavaScript. JavaScript is a programming language that lets the browser dynamically update website content. The JavaScript is usually executed by the same browser used to view a webpage. This means that, similar to CSS and HTML, the exact behavior of any code you write might differ between browsers. But most common browsers adhere to the ECMAScript specification. This is a standard that unifies JavaScript usage in the web, and will be the basis for the lesson, together with the HTML5 specification, which specifies how JavaScript needs to be put into a webpage for a browser to execute it.
Running JavaScript in the Browser
To execute JavaScript, the browser needs to obtain the code either directly, as part of the HTML that makes up the web page, or as a URL that indicates a location for a script to be executed.
The following example shows how to include code directly in the HTML file:
<html>
<head>
</head>
<body>
<h1>Website Headline</h1>
<p>Content</p>
<script>
console.log('test');
</script>
</body>
</html>
The code is wrapped between <script>
and </script>
tags. Everything included in these tags will be executed by the browser directly when loading the page.
The position of the <script>
element within the page dictates when it will be executed. An HTML document is parsed from top to bottom, with the browser deciding when to display elements on the screen. In the example just shown, the <h1>
and <p>
tags of the website are parsed, and likely displayed, before the script runs. If the JavaScript code within the <script>
tag would take very long to execute, the page would still display without any problem. If, however, the script had been placed above the other tags, the web page visitor would have to wait until the script finishes executing before seeing the page. For this reason, <script>
tags are usually placed in one of two places:
-
At the very end of the HTML body, so that the script is the last thing that gets executed. Do this when the code adds something to the page that would not be useful without the content. An example would be adding functionality to a button, as the button has to exist for the functionality to make sense.
-
Inside the
<head>
element of the HTML. This ensures that the script is executed before the HTML body is parsed. If you want to change the loading behavior of the page, or have something that needs to be executed while the page is still not fully loaded, you can put the script here. Also, if you have multiple scripts that depend on a particular script, you can put that shared script in the head to make sure it’s executed before other scripts.
For a variety of reasons, including manageability, it is useful to put your JavaScript code into separate files that exist outside of your HTML code. External JavaScript files are included using a <script>
tag with a src
attribute, as follows:
<html>
<head>
<script src="/button-interaction.js"></script>
</head>
<body>
</body>
</html>
The src
tag tells the browser the location of the source, meaning the file containing the JavaScript code. The location can be a file on the same server, as in the example above, or any web-accessible URL such as https://www.lpi.org/example.js
. The value of the src
attribute follows the same convention as the import of CSS or image files, in that it can be relative or absolute. Upon encountering a script tag with the src
attribute, the browser will then attempt to obtain the source file by using an HTTP GET
request, so external files need to be accessible.
When you use the src
attribute, any code or text that is placed between the <script>…</script>
tags is ignored, according to the HTML specification.
<html>
<head>
<script src="/button-interaction.js">
console.log("test"); // <-- This is ignored
</script>
</head>
<body>
</body>
</html>
There are other attributes you can add to the script
tag to further specify how the browser should get the files, and how it should handle them afterwards. The following list goes into detail about the more important attributes:
async
-
Can be used on
script
tags and instructs the browser to fetching the script in the background, so as not to block the page load process. The page load will still be interrupted while after the browser obtains the script, because the browser has to parse it, which is done immediately once the script has been fetched completely. This attribute is Boolean, so writing the tag like<script async src="/script.js"></script>
is sufficient and no value has to be provided. defer
-
Similar to
async
, this instructs the browser not to block the page load process while fetching the script. Rather than that, the browser will defer parsing the script. The browser will wait until the entire HTML document has been parsed and only then it will parse the script, before announcing that the document has been to be completely loaded. Likeasync
,defer
is a Boolean attribute and is used in the same way. Sincedefer
impliesasync
, it is not useful to specify both tags together.NoteWhen a page is completely parsed, the browser indicates that it is ready to display by triggering a
DOMContentLoaded
event, when the visitor will be able to see the document. Thus, the JavaScript included in a<head>
event always has a chance to act on the page before it is displayed, even if you include thedefer
attribute. type
-
Denotes what type of script the browser should expect within the tag. The default is JavaScript (
type="application/javascript"
), so this attribute isn’t necessary when including JavaScript code or pointing to a JavaScript resource with thesrc
tag. Generally, all MIME types can be specified, but only scripts that are denoted as JavaScript will be executed by the browser. There are two realistic use cases for this attribute: telling the browser not to execute the script by settingtype
to an arbitrary value liketemplate
orother
, or telling the browser that the script is an ES6 module. We don’t cover ES6 modules in this lesson.
Warning
|
When multiple scripts have the |
Browser Console
While usually executed as part of a website, there is another way of executing JavaScript: through the browser console. All modern desktop browsers provide a menu through which you can execute JavaScript code in the browser’s JavaScript engine. This is usually done for testing new code or to debug existing websites.
There are multiple ways to access the browser console, depending on the browser. The easiest way is through keyboard shortcuts. The following are the keyboard shorcuts for some of the browsers currently in use:
- Chrome
-
Ctrl+Shift+J (Cmd+Option+J on Mac)
- Firefox
-
Ctrl+Shift+K (Cmd+Option+K on Mac)
- Safari
-
Ctrl+Shift+? (Cmd+Option+? on Mac)
You can also right-click on a webpage and select the “Inspect” or “Inspect Element” option to open the inspector, which is another browser tool. When the inspector opens, a new panel will appear. In this panel, you can select the “Console” tab, which will bring up the browser console.
Once you pull up the console, you can execute JavaScript on the page by typing the JavaScript directly into the input field. The result of any executed code will be shown in a separate line.
JavaScript Statements
Now that we know how to start executing a script, we will cover the basics of how a script is actually executed. A JavaScript script is a collection of statements and blocks. An example statement is console.log('test')
. This instruction tells the browser to output the word test
to the browser console.
Every statement in JavaScript is terminated by a semicolon (;
). This tells the browser that the statement is done and a new one can be started. Consider the following script:
var message = "test"; console.log(message);
We have written two statements. Every statement is terminated either by a semicolon or by the end of the script. For readability purposes, we can put the statements on separate lines. This way, the script could also be written as:
var message = "test";
console.log(message);
This is possible because all whitespace between statements, such as a space, a newline, or a tab, is ignored. Whitespace can also often be put between individual keywords within statements, but this will be further explained in an upcoming lesson. Statements can also be empty, or comprised only of whitespace.
If a statement is invalid because it has not been terminated by a semicolon, ECMAScript makes an attempt to automatically insert the proper semicolons, based on a complex set of rules. The most important rule is: If an invalid statement is composed of two valid statements separated by a newline, insert a semicolon at the newline. For instance, the following code does not form a valid statement:
console.log("hello")
console.log("world")
But a modern browser will automatically execute it as if it were written with the proper semicolons:
console.log("hello");
console.log("world");
Thus, it is possible to omit semicolons in certain cases. However, as the rules for automatic semicolon insertion are complex, we advise you always to properly terminate your statements to avoid unwanted errors.
JavaScript Commenting
Big scripts can get quite complicated. You might want to comment on what you are writing, to make the script easier to read for other people, or for yourself in the future. Alternatively, you might want to include meta information in the script, such as copyright information, or information about when the script was written and why.
To make it possible to include such meta information, JavaScript supports comments. A developer can include special characters in a script that denote certain parts of it as a comment, which will be skipped on execution. The following is a heavily commented version of the script we saw earlier.
/*
This script was written by the author of this lesson in May, 2020.
It has exactly the same effect as the previous script, but includes comments.
*/
// First, we define a message.
var message = "test";
console.log(message); // Then, we output the message to the console.
Comments are not statements and do not need to be terminated by a semicolon. Instead, they follow their own rules for termination, depending on the way the comment is written. There are two ways to write comments in JavaScript:
- Multi-line comment
-
Use
/*
and*/
to signal the start and end of a multi-line comment. Everything after/*
, until the first occurrence of*/
is ignored. This kind of comment is generally used to span multiple lines, but it can also be used for single lines, or even within a line, like so:console.log(/* what we want to log: */ "hello world")
Because the goal of comments is generally to increase the readability of a script, you should avoid using this comment style within a line.
- Single-line comment
-
Use
//
(two forward slashes) to comment out a line. Everything after the double-slash on the same line is ignored. In the example shown earlier, this pattern is first used to comment an entire line. After theconsole.log(message);
statement, it is used to write a comment on the rest of the line.
In general, single-line comments should be used for single lines, and multi-line comments for multiple lines, even if it possible to use them in other ways. Comments within a statement should be avoided.
Comments can also be used to temporarily remove lines of actual code, as follows:
// We temporarily want to use a different message
// var message = "test";
var message = "something else";
Guided Exercises
-
Create a variable called
ColorName
and assign the valueRED
to it. -
Which of the following scripts are valid?
console.log("hello") console.log("world");
console.log("hello"); console.log("world");
// console.log("hello") console.log("world");
console.log("hello"); console.log("world") //;
console.log("hello"); /* console.log("world") */
Explorational Exercises
-
How many JavaScript statements can be written on a single line without using a semicolon?
-
Create two variables named
x
andy
, then print their sum to the console.
Summary
In this lesson we learned different ways of executing JavaScript, and how to modify the script loading behavior. We also learned the basic concepts of script composition and commenting, and have learned to use the console.log()
command.
HTML used in this lesson:
- <script>
-
The
script
tag can be used to include JavaScript directly or by specifying a file with thesrc
attribute. Modify how the script is loaded with theasync
anddefer
attributes.
JavaScript concepts introduced in this lesson:
;
-
A semicolon is used to separate statements. Semicolons can sometimes — but should not be — ommitted.
//
,/*…*/
-
Commenting can be used to add comments or meta information to a script file, or to prevent statements from being executed.
console.log("text")
-
The
console.log()
command can be used to output text to the browser console.
Answers to Guided Exercises
-
Create a variable called
ColorName
and assign the valueRED
to it.var ColorName = "RED";
-
Which of the following scripts are valid?
console.log("hello") console.log("world");
Invalid: The first
console.log()
command isn’t properly terminated, and the line as a whole doesn’t form a valid statement.console.log("hello"); console.log("world");
Valid: Each statement is properly terminated.
// console.log("hello") console.log("world");
Valid: The entire code is ignored because it is a comment.
console.log("hello"); console.log("world") //;
Invalid: The last statement is missing a semicolon. The semicolon at the very end is ignored because it is commented.
console.log("hello"); /* console.log("world") */
Valid: A valid statement is followed by commented code, which gets ignored.
Answers to Explorational Exercises
-
How many JavaScript statements can be written on a single line without using a semicolon?
If we are at the end of a script, we can write one statement and it will be terminated by the end of the file. Otherwise, you cannot write a statement without a semicolon with the syntax that you learned so far.
-
Create two variables named
x
andy
, then print their sum to the console.var x = 5; var y = 10; console.log(x+y);