0% found this document useful (0 votes)
3 views

L1

JavaScript is a versatile scripting language used to create dynamic and interactive features on web pages, functioning alongside HTML and CSS. It allows developers to manipulate content, control multimedia, and utilize APIs for enhanced functionality. JavaScript can run on both client-side and server-side environments, with various methods for integration and execution within web pages.

Uploaded by

albsrawys686
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

L1

JavaScript is a versatile scripting language used to create dynamic and interactive features on web pages, functioning alongside HTML and CSS. It allows developers to manipulate content, control multimedia, and utilize APIs for enhanced functionality. JavaScript can run on both client-side and server-side environments, with various methods for integration and execution within web pages.

Uploaded by

albsrawys686
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

What is JavaScript?

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.

What is JavaScript doing on your page?


Here we'll actually start looking at some code, and while doing so, explore what actually happens
when you run some JavaScript in your page.
Let's briefly recap the story of what happens when you load a web page in a browser. When you load
a web page in your browser, you are running your code (the HTML, CSS, and JavaScript) inside an
execution environment (the browser tab). This is like a factory that takes in raw materials (the code)
and outputs a product (the web page).

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.

Interpreted versus compiled code


You might hear the terms interpreted and compiled in the context of programming. In interpreted
languages, the code is run from top to bottom and the result of running the code is immediately
returned. You don't have to transform the code into a different form before the browser runs it. The
code is received in its programmer friendly text form and processed directly from that.
Compiled languages on the other hand are transformed (compiled) into another form before they are
run by the computer. For example, C/C++ are compiled into machine code that is then run by the
computer. The program is executed from a binary format, which was generated from the original
program source code.
JavaScript is a lightweight interpreted programming language. The web browser receives the
JavaScript code in its original text form and runs the script from that. From a technical standpoint,
most modern JavaScript interpreters actually use a technique called just-in-time compiling to
improve performance; the JavaScript source code gets compiled into a faster, binary format while the
script is being used, so that it can be run as quickly as possible. However, JavaScript is still considered
an interpreted language, since the compilation is handled at run time, rather than ahead of time.
There are advantages to both types of language, but we won't discuss them right now.

Server-side versus client-side code


You might also hear the terms server-side and client-side code, especially in the context of web
development. Client-side code is code that is run on the user's computer — when a web page is
viewed, the page's client-side code is downloaded, then run and displayed by the browser. In this
module we are explicitly talking about client-side JavaScript.
Server-side code on the other hand is run on the server, then its results are downloaded and displayed
in the browser. Examples of popular server-side web languages include PHP, Python, Ruby, C#, and
even JavaScript! JavaScript can also be used as a server-side language, for example in the popular
Node.js environment.

Dynamic versus static code


The word dynamic is used to describe both client-side JavaScript, and server-side languages — it
refers to the ability to update the display of a web page/app to show different things in different
circumstances, generating new content as required. Server-side code dynamically generates new
content on the server, e.g. pulling data from a database, whereas client-side JavaScript dynamically
generates new content inside the browser on the client, e.g. creating a new HTML table, filling it with
data requested from the server, then displaying the table in a web page shown to the user. The meaning
is slightly different in the two contexts, but related, and both approaches (server-side and client-side)
usually work together.
A web page with no dynamically updating content is referred to as static — it just shows the same
content all the time.

How do you add JavaScript to your page?


JavaScript is applied to your HTML page in a similar manner to CSS. Whereas CSS uses <link>
elements to apply external stylesheets and <style> elements to apply internal stylesheets to HTML,
JavaScript only needs one friend in the world of HTML — the <script> element. Let's learn how this
works.

Script loading strategies


All the HTML on a page is loaded in the order in which it appears. If you are using JavaScript to
manipulate elements on the page (or more accurately, the Document Object Model), your code won't
work if the JavaScript is loaded and parsed before the HTML you are trying to do something to.
There are a few different strategies to make sure your JavaScript only runs after the HTML is parsed:
• In the internal JavaScript, the script element is placed at the bottom of the body of the document,
and therefore only run after the rest of the HTML body is parsed.
HTML

<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

<script type="module" src="script.js"></script>

• Inline JavaScript handlers


Note that sometimes you'll come across bits of actual JavaScript code living inside HTML. It might
look something like this:
JS Play

function createParagraph() {
const para = document.createElement("p"); para.textContent =
"You clicked the button!"; document.body.appendChild(para);
}

HTML Play

<button onclick="createParagraph()">Click me!</button>


You can try this version of our demo below.
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

const buttons = document.querySelectorAll("button");

for (const button of buttons) {


button.addEventListener("click", createParagraph);
}

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

const myHeading = document.querySelector("h1");


myHeading.textContent = "Hello world!";

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

Primitive String 'Hello'

Number 5

Boolean true

Undefined undefined

Null null

Objects Array ['Saab', 'Volvo']

Object {type: 'Fiat', model: '500'}

Primitive data types


String
Strings are collections of text characters, inside single ( ' ) or double ( " ) quotes22. For example, the
following expressions define two variables that contain strings, s1 and s2 :
let s1 = 'Hello';
let s2 = 'World';
Strings can be concatenated using the + operator:
s1 + s2; // Returns 'HelloWorld'
s1 + ' ' + s2; // Returns 'Hello World'
The += operator works with strings too. It is useful to sequentially construct strings with HTML
code. For example, in the following code section we construct HTML code for a <ul> (unordered
list) element with two internal <li> elements (list items) using the += operator, assigned into a
string named list :
let list = ''; list +=
'<ul>'; list +=
'<li>Apples</li>'; list +=
'<li>Oranges</li>'; list +=
'</ul>';
We are going to revisit this technique later on, when constructing HTML code using loops
Number
Numbers can be integers or decimals. The usual arithmetic operators,
+ —Addition,
- —Subtraction,
* —Multiplication, and
/ —Division, can be used with numeric values. For example:
let x = 5, y = 6, z;
z = x + y; // Returns 11
In this example, we defined two variables x and y and assigned their values ( 5 and 6 ). We also
defined a third variable z without assigning a value. Note how we defined x , y , and z in the same
expression, separated by commas—this saves typing the let keyword three times. In the last
expression we calculated x+y and assigned the result of that calculation into z .
JavaScript also has increment ++ and decrement -- operators. The increment operator ++ adds
one to the current number. The decrement operator -- subtracts one from the current number. For
example:
let x = 5; x++; // Same as: x=x+1; the value of x
is now 6 x--; // Same as: x=x-1; the value of x
is now 5
When running the last two expressions, you will see 5 and 6 (not 6 and 5 ) printed in the console,
respectively. This is because the increment ++ and decrement -- expressions return the current
value, before modifying it.

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

=== Equal value and equal type

!= Not equal

!== Not equal value or not equal type

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to

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:

'5' == 5; // Returns true


'5' === 5; // Returns false
Since the conversion rules of the == and != operators are complicated and unmemorable, it is not
advised to use them. Instead, the === and !== operators, with their expected and strict behaviors,
are recommended (Crockford 2008).

Boolean values can be combined with logical operators:


&& —AND operator, true only if both values are true
|| —OR operator, true if at least one of the values is true 24
! —NOT operator, true if value is false
For example:
let x = 6; let y = 3; x < 10 && y > 1; // Returns true
x == 5 || y == 5; // Returns false
!(x == 5 || y == 5); // Returns true
Undefined
Undefined ( undefined ) means that a variable has been declared but has not been assigned with a
value yet. For example:
let x; x; // Returns undefined

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

let myVariable = "Bob";


You retrieve the value by calling the variable name:
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:

Variable Explanation Example

This is a sequence of text known as a string. To signify


let myVariable = 'Bob'; or let
String that the value is a string, enclose it in single or double
myVariable = "Bob";
quote marks.

This is a number. Numbers don't have quotes around


Number let myVariable = 10;
them.

This is a True/False value. The words true and false are


Boolean let myVariable = true;
special keywords that don't need quote marks.

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.

This can be anything. Everything in let myVariable =


Object JavaScript is an object and can be stored in a variable. document.querySelector('h1');
Keep this in mind as you learn. All of the above examples too.

So why do we need variables? Variables are necessary to do anything interesting in programming. If


values couldn't change, then you couldn't do anything dynamic, like personalize a greeting message
or change an image displayed in an image gallery.

You might also like