L1
L1
JavaScript is a scripting or programming language that allows you to implement complex features on
web pages — every time a web page does more than just sit there and display static information for
you to look at — displaying timely content updates, interactive maps, animated 2D/3D graphics,
scrolling video jukeboxes, etc. — you can bet that JavaScript is probably involved. It is the third layer
of the layer cake of standard web technologies, two of which (HTML and CSS).
HTML is the markup language that we use to structure and give meaning to our web content, for
example defining paragraphs, headings, and data tables, or embedding images and videos in the page.
CSS is a language of style rules that we use to apply styling to our HTML content, for example
setting background colors and fonts, and laying out our content in multiple columns.
JavaScript is a scripting language that enables you to create dynamically updating content, control
multimedia, animate images, and pretty much everything else. (Okay, not everything, but it is amazing
what you can achieve with a few lines of JavaScript code.)
What is even more exciting however is the functionality built on top of the client-side JavaScript
language. So-called Application Programming Interfaces (APIs) provide you with extra
superpowers to use in your JavaScript code.
APIs are ready-made sets of code building blocks that allow a developer to implement programs that
would otherwise be hard or impossible to implement. They do the same thing for programming that
ready-made furniture kits do for home building — it is much easier to take ready-cut panels and screw
them together to make a bookshelf than it is to work out the design yourself, go and find the correct
wood, cut all the panels to the right size and shape, find the correct-sized screws, and then put them
together to make a bookshelf. They generally fall into two categories.
Browser APIs are built into your web browser, and are able to expose data from the surrounding
computer environment, or do useful complex things. For example:
The DOM (Document Object Model) API allows you to manipulate HTML and CSS, creating,
removing and changing HTML, dynamically applying new styles to your page, etc. Every time you
see a popup window appear on a page, or some new content displayed (as we saw above in our simple
demo) for example, that's the DOM in action.
The Geolocation API retrieves geographical information. This is how Google Maps is able to find
your location and plot it on a map.
The Canvas and WebGL APIs allow you to create animated 2D and 3D graphics.
People are doing some amazing things using these web technologies
Audio and Video APIs like HTMLMediaElement and WebRTC allow you to do really interesting
things with multimedia, such as play audio and video right in a web page, or grab video from your
web camera and display it on someone else's computer.
Third party APIs are not built into the browser by default, and you generally have to grab their code
and information from somewhere on the Web. For example:
The Twitter API allows you to do things like displaying your latest tweets on your website.
The Google Maps API and OpenStreetMap API allows you to embed custom maps into your
website, and other such functionality.
A very common use of JavaScript is to dynamically modify HTML and CSS to update a user interface,
via the Document Object Model API (as mentioned above).
Browser security
Each browser tab has its own separate bucket for running code in (these buckets are called "execution
environments" in technical terms) — this means that in most cases the code in each tab is run
completely separately, and the code in one tab cannot directly affect the code in another tab — or on
another website. This is a good security measure — if this were not the case, then pirates could start
writing code to steal information from other websites, and other such bad things.
JavaScript running order
When the browser encounters a block of JavaScript, it generally runs it in order, from top to bottom.
This means that you need to be careful what order you put things in.
<script>
// JavaScript goes here
</script>
• In the external JavaScript, the script element is placed in the head of the document, before the
HTML body is parsed. But because we're using <script type="module"> , the code is treated as
a module and the browser waits for all HTML to be processed before executing JavaScript
modules. (You could also place external scripts at the bottom of the body. But if there is a lot of
HTML and the network is slow, it may take a lot of time before the browser can even start fetching
and loading the script, so placing external scripts in the head is usually better.)
HTML
function createParagraph() {
const para = document.createElement("p"); para.textContent =
"You clicked the button!"; document.body.appendChild(para);
}
HTML Play
Click me!
This demo has exactly the same functionality as in the previous two sections, except that the <button>
element includes an inline onclick handler to make the function run when the button is pressed, you'd
have to include the onclick="createParagraph()" attribute on every button you want the JavaScript to
Using addEventListener instead
Instead of including JavaScript in your HTML, use a pure JavaScript construct. The
querySelectorAll() function allows you to select all the buttons on a page. You can then loop through
the buttons, assigning a handler for each using addEventListener() . The code for this is shown below:
JS
This might be a bit longer than the onclick attribute, but it will work for all buttons — no matter how
many are on the page, nor how many are added or removed. The JavaScript does not need to be
changed.
Note: Try editing your version of apply-javascript.html and add a few more buttons into the file.
When you reload, you should find that all of the buttons when clicked will create a paragraph. Neat,
huh?
Comments
As with HTML and CSS, it is possible to write comments into your JavaScript code that will be
ignored by the browser, and exist to provide instructions to your fellow developers on how the code
works (and you, if you come back to your code after six months and can't remember what you did).
Comments are very useful, and you should use them often, particularly for larger applications. There
are two types:
//
JS
// I am a comment
/* */
JS
/* I am also a
comment */
A "Hello world!" example
JavaScript is one of the most popular modern web technologies! As your JavaScript skills grow, your
websites will enter a new dimension of power and creativity. However, getting comfortable with
JavaScript is more challenging than getting comfortable with HTML and CSS. You should start small,
and progress gradually. To begin, let's examine how to add JavaScript to your page for creating a
Hello world! example.
Inside your first-website folder, create a new folder named scripts.
Within the scripts folder, create a new text document called main.js , and save it.
Go to your index.html file and enter this code on a new line, just before the closing </body> tag:
HTML
<script src="scripts/main.js"></script>
This is doing the same job as the <link> element for CSS. It applies the JavaScript to the page, so it
can have an effect on the HTML (along with the CSS, and anything else on the page).
Add this code to your scripts/main.js file:
JS
Make sure the HTML and JavaScript files are saved, then load index.html in your browser. You
should see something like this:
What happened?
We have used JavaScript to change the heading text to Hello world!. We did this by using a function
called querySelector() to grab a reference to your heading, and then store it in a variable called
myHeading . This is similar to what we did using CSS selectors. When you want to do something to
an element, you need to select it first. Following that, the code set the value of the myHeading
variable's textContent property (which represents the content of the heading) to Hello world!.
Assignment
Assignment to variables is one of the most important concepts in programming, since it lets us keep
previously calculated results in memory for further processing.
Variables are containers that hold data values, simple or complex, that can be referred to later in your
code. There are several ways to define variables in JavaScript, using the following keywords:
• var
• let
• const
The traditional way has been using the keyword var. The newer method—using the keyword let —
is more similar to the “usual” behavior in other programming languages. For example, variables
defined with let have block-scope, are inaccessible before the declaration, and cannot be redefined.
For these reasons, in this book we are going to use let. You should be aware of var as well, because
it is still commonly used and you are going to see it often in other scripts, programming forums, etc.
The third keyword, const, is similar to let but used to define constant variables, which cannot be
modified later on in our code. We are going to use let throughout the book to keep things simple.
Keep in mind that using const, instead of let, is recommended for variables that are kept constant
throughout the program, to increase code clarity and minimize potential mistakes.
To define a variable, the let keyword is followed by the variable name. For example, the following
two expressions define the variables x and y:
let x;
let y;
Note that each JavaScript expression should end with ; . Ending statements with semicolon is not
strictly required, since statement ending can also be automatically determined by the browser, but it
is highly recommended to use ; in order to reduce ambiguity.
Values can be assigned to variables using the assignment operator = . Assignment can be made along
with variable definition:
let x = 5; let y = 6;
or later on, in separate expressions, after the variables have already been defined:
x = 5; y = 6;
Either way, we have now defined two variables x and y. The values contained in these two variables
are 5 and 6, respectively. In your JavaScript console, to see a current value of a variable, type its
name and hit Enter. The current value will be returned and printed:
x; // Returns 5
Note that you cannot re-define an existing variable defined with let , but you can assign a new value
into an existing variable. For example, the following pair of expressions raises an error:
let x = 5; let x = 6; // Uncaught SyntaxError: Identifier 'x' has already
been declared
while the following is perfectly fine:
let x = 5; x = 6;
At the time of writing, the console inside the developer tools in Chrome does allow redefining
variables defined with let , which makes code testing easier. Elsewhere—e.g., in scripts executed on
page load— variables defined with let cannot be redefined.
There are several short-hand assignment operators, in addition to the basic assignment operator = .
For example, another commonly used assignment operator is the addition assignment operator +=
, which adds a value to a variable. The following expression uses the addition assignment operator
+= :
x += 10;
This is basically a shortcut for the following assignment: x = x + 10;
Data types
In the examples above we defined variables holding numeric data, such as the numbers 5 and
6 . JavaScript variables can also hold other data types. JavaScript data types are divided into two
groups: primitive data types and objects.
Primitive data types include the following:
String—Text characters that are delimited by quotes, for example: "Hello" or 'Hello'
Number—Integer or floating-point value, for example: 5 and -10.2
Boolean—Logical values, true or false
Undefined—Specifies that a variable is declared but has no defined value, undefined
Null—Specifies an intentional absence of any object value, null
Objects are basically collections of the primitive data types and/or other objects:
• Array—Multiple variables in a single variable, for example: ['Saab', 'Volvo', 'BMW']
• Object—Collections of name:value pairs, for example: {type:'Fiat', model:'500',
color:'white'}
The data types in JavaScript are summarized in Table 1.1. we go over the data types in JavaScript
one by one.
TABLE1.1: JavaScript data types
Group Data type Example
Number 5
Boolean true
Undefined undefined
Null null
Boolean
Boolean (logical) values are either true or false . For example:
let found = true;
let lost = false;
In practice, boolean values are usually created as the result of comparison operators. For example:
9 >= 10; // Returns false
11 > 10; // Returns true
JavaScript comparison operators are summarized in Table 1.2.
TABLE 1.2: JavaScript comparison operators
Operator Meaning
== Equal to
!= Not equal
You may have noticed there are two versions of the equality ( == , === ) and inequality ( != , !== )
comparison operators (Table 3.2). The difference between them is that the former ones ( == , != )
consider just the value, while the latter ones ( === , !== ) consider both value and type. What do the
terms equal value and equal type mean? Consider the following example, where 5 and '5' have
equal value (5) but unequal type (number vs. string). Comparing these two values gives different
results when using the == and === operators. This is because == considers just the value, while
=== is more strict and considers both value and type:
Null
Null ( null ) is another special data type, representing lack of a value. For example:
let x = null;
Variables are containers that store values. You start by declaring a variable with the let keyword,
followed by the name you give to the variable:
JS
let myVariable;
You can name a variable nearly anything, but there are some restrictions. JavaScript is case sensitive.
This means myVariable is not the same as myvariable. If you have problems in your code, check the
case! After declaring a variable, you can give it a value:
JS
myVariable = "Bob";
Also, you can do both these operations on the same line:
JS
myVariable;
After assigning a value to a variable, you can change it later in the code:
JS
let myVariable = "Bob"; myVariable = "Steve";
Note that variables may hold values that have different data types:
let myVariable =
[1,'Bob','Steve',10];
This is a structure that allows you to store multiple
Array Refer to each member of the array like
values in a single reference.
this: myVariable[0] , myVariable[1] ,
etc.