You are on page 1of 109

div {

float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}

1.2.1 HTML is for structure


Skip to main content

The "Hyper Text" part: links!

A fundamental key to the World Wide Web is the concept of "hypertext".  Hypertext is built
on the idea of linking information together, not unlike using footnotes, but far easier and
more flexible. The idea is to "mark up" your document with links and define how to break it
down into different segments (chapters, sections, paragraphs, tables, figures, etc.)

That's why, in 1989, Tim Berners-Lee began to create a definition of HTML: Hypertext
Markup Language, to provide a simple, uniform way to incorporate hyperlinks into a text
document.

Welcome to the Course


Skip to main content

Welcome to the Introduction to User Experience!

From software to mobile applications and websites, UX projects can provide or


improve professional interfaces by offering quality experiences. This introductory
MOOC of 4 modules will guide you in learning about UX fundamentals and the
stakeholders involved. You will learn about the distinction between the user,
customer and citizen experience, as well as review arguments highlighting
UX profitability. You will finish this course by completing an introductory exercise,
taking you through all the phases of a UX design project.

This course is a double introduction, to UX and to our MicroMasters. It is the first in a


div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
series of seven MOOCs in UX Design and Evaluation. We hope that this introduction
will encourage you to continue the experience by registering for one or other courses
or by pursuing the MicroMasters.

Here is the sequence of the UX Design and Evaluation MOOCs in our program:

MOOC 1 is an introduction to UX, it will lay the groundwork.

MOOC 2 focuses on UX research, which coincides with the analysis phase of the
design cycle: where we analyze the context, see what users do, what they need,
how they live, etc. It is strongly recommended to do courses 1 and 2 first, the MOOC
on UX research being central to all the others; it is central because UX research is
how users are integrated into design and evaluation to make them UX practices (i.e.
user-centered).

MOOC 3 covers the UX design phase, which is the conceptual and strategic


creative phase.

MOOC 4 focuses on the prototyping phase; this is where we will talk, among other
things, about the user interface design and of the different kinds of prototypes.

MOOC 5 puts emphasis on the UX evaluation of digital interfaces, whether they are
already active or in the prototype stage.
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
MOOC 6 complements MOOC 5 by discussing tools and processes for analyzing
data collected during research and evaluation activities.

MOOC 7, the final course, focuses on the particulars of UX management.

The edX MicroMasters certification is conditional to completing and passing each of


the 7 MOOCs.  

HEC Montréal grants 9 credits towards its Master of Science (M.Sc.) in User

He envisioned a technology that would facilitate thoroughly interconnected documents. He


wanted authors to be able to connect an idea in one document to the source of the idea in
another, or connect a statement with the data that backs up that statement. Traditionally this
kind of thing was done with footnotes and bibliographies, which can be cumbersome. This
information should be easily transferable from one place to another, so that in reading one
document, it is easy to access everything related (linked) to it. Tim Berners-Lee imagined a
"Web" of interconnected documents.
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
He used the metaphor of a Web to emphasize the importance of connections between
documents. It was not just a long list of details, but rather a sea of information stretching out
in all directions. This sea of information was navigated by a new tool called a "browser".

The "Markup" part : elements, tags and attributes!

So the "M" in HTML stands for "Markup", but what does Markup really mean?  Essentially it
means to annotate a document with extra information: things like where different sections
and paragraphs begin and end, which part is the title, which things should be emphasized and
so on.

There are many ways to markup a document, but HTML borrows a technique from an
ancestor language, SGML (Standard Generalized Markup Language), which uses angle
brackets ("<" and ">") to separate the annotations from the regular text.  In HTML these
annotations are called "tags".

For example, consider the following chunk of HTML code (note: you can edit the source
code and see the resulting Web page updating in real time):

1.    <body>
2.       <h1>A Tale of Two Cities</h1>
3.       <p>
4.          It was the best of times, it was the worst of times, . . . .
5.       </p>
6.       . . .
7.       <p>
8.          . . . it is a far, far better rest
9.          that I go to than I have ever known.
10.       </p>
11.    </body>

If you eliminated everything in between the angle brackets from the text, for most purposes it
would still read the same:

A Tale of Two Cities


It was the best of times, it was the worst of times . . . .
. . .
. . . it is a far, far better rest
that I go to than I have ever known.

Once you know that everything in angle brackets is "meta-information", it gives you a lot of
flexibility. You can put a lot of different things in between those brackets without any of it
showing up (directly) in your finished document. And though you don't usually see directly
what's in those angle brackets, they can often have a big effect on how your Web page
looks, as well as how it responds and interacts with you.
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
Here is another, more generic example:

Notes:

o Remember that the first line of your HTML5 page should start by <!
DOCTYPE html>. CodePen does not force you to add a DOCTYPE on
CodePen, but be assured that you have to specify the DOCTYPE in all your
Web documents.
o You can modify the source code in CodePen, and see the results in real time.

1. <!DOCTYPE html>
2.  <html lang="en">
3.    <head>
4.      <title>Your first HTML page</title>
5.      <meta charset="utf-8"/>
6.    </head>
7.   <body>
8.   <h1>My home page</h1>
9.    <h2>Who am I?</h2>
10.     <p>Hi! Welcome to my Home Page! My name is Michel Buffa, I'm a professor at
the University of Nice, in France, and I'm also the author of two MOOCS about
HTML5 on W3Cx.</p>
11.     <p>I also play electric guitar and love coding WebAudio applications...</p>
12.     <img
src="https://pbs.twimg.com/profile_images/110455194/n666194627_2302_400x400.j
pg" width=200
13.      alt="Michel Buffa plays rock and roll">
14.    <h2>My Hobbies</h2>
15. Music, Movies, Video Games, Travelling, Family, etc.
16.    </body>
17.   </html>

Try it out!

It's time to write your first HTML code :-)

You can use a source code editor like Sublime Text, Atom, Brackets or any lightweight text
editor. You can also use more "professional" tools such as Visual Studio Code, NetBeans,
Eclipse, WebStorm, etc.

To try out the simple examples from this course, I'd suggest using an online IDE such as
JSBin, CodePen, Plunker, etc.
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
During the course, we will show you how to test out simple code snippets in online IDEs, but
we will also teach you how to organize your code with folders and files.

The next video shows how you can use JsBin, CodePen, and SublimeText in order to test the
HTML code provided earlier in this section.

Live coding video: using the course's tools (video downloaded)

HTML elements

If you are sitting at a coffee shop next to a table of Web developers, you will probably often
hear these three words: "Elements", "Tags" and "Attributes".

"Elements" are the pieces themselves, i.e. a paragraph is an element, a header is an element,
even the body is an element. Most elements can contain other elements, as the body element
would contain header elements, paragraph elements, in fact pretty much all of the visible
elements of the Document Object Model (that developers refer to as the "DOM").

As an example, let's look at a simplified version of the last HTML code we presented earlier:

1. <!DOCTYPE html>
2. <html lang="en">
3.   <head>
4.    <title>Your first HTML page</title>
5.    <meta charset="utf-8"/>
6.   </head>
7.   <body>
8.    <h1>My home page</h1>
9.    <p>Hi! Welcome to my Home Page! My name is Michel Buffa, I'm a professor at
the University of Côte d'Azur, in France, and I'm also the author of three W3Cx
MOOCS.</p>
10.    </body>
11. </html>

 HTML

<!DOCTYPE html>
<html lang="en">
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
<head>
<meta charset="utf-8">
<title>Tree Example</title>
<style>

.node {
cursor: pointer;
}

.node circle {
fill: #fff;
stroke: red;
stroke-width: 3px;
}

.node text {
font: 24px sans-serif; /* Font size */
}

.link {
fill: none;
stroke: #ccc;
stroke-width: 2px;
}

</style>

</head>

<body>

<!-- load the d3.js library -->


<script src="https://d3js.org/d3.v3.min.js"></script>

<script>

var treeData = [
{
"name": "html",
"parent": "null",
"_children": [
{
"name": "head",
"parent": "Top Level",
"_children": [
{
"name": "title",
"parent": "head",
"_children": [
]
},
{
"name": "meta",
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
"parent": "head",
"_children": [
]
}
]
},
{
"name": "body",
"parent": "Top Level",
"_children": [
{
"name": "h1",
"parent": "body",
"_children": [
]
},
{
"name": "p",
"parent": "body",
"_children": [
]
},
]
},
]
}
];

// ************** Generate the tree diagram *****************


var margin = {top: 20, right: 120, bottom: 20, left: 120},
width = 600 - margin.right - margin.left,
height = 300 - margin.top - margin.bottom;

var i = 0,
duration = 750,
root;

var tree = d3.layout.tree()


.size([height, width]);

var diagonal = d3.svg.diagonal()


.projection(function(d) { return [d.y, d.x]; });

var svg = d3.select("body").append("svg")


.attr("width", width + margin.right + margin.left)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top +
")");

root = treeData[0];
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
root.x0 = height / 2;
root.y0 = 0;

update(root);

d3.select(self.frameElement).style("height", "500px");

function update(source) {

// Compute the new tree layout.


var nodes = tree.nodes(root).reverse(),
links = tree.links(nodes);

// Normalize for fixed-depth.


nodes.forEach(function(d) { d.y = d.depth * 180; });

// Update the nodes…


var node = svg.selectAll("g.node")
.data(nodes, function(d) { return d.id || (d.id = ++i); });

// Enter any new nodes at the parent's previous position.


var nodeEnter = node.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + source.y0 +
"," + source.x0 + ")"; })
.on("click", click);

nodeEnter.append("circle")
.attr("r", 1e-6)
.style("fill", function(d) { return d._children ? "white" :
"lightgray"; });

nodeEnter.append("text") // adjust parameters on next couple lines


.attr("x", function(d) { return d.children || d._children ? -5 :
14; })
.attr("dy", "1.4em")
.attr("text-anchor", function(d) { return d.children || d._children ?
"end" : "start"; })
.text(function(d) { return d.name; })
.style("fill-opacity", 1e-6);

// Transition nodes to their new position.


var nodeUpdate = node.transition()
.duration(duration)
.attr("transform", function(d) { return "translate(" + d.y + "," +
d.x + ")"; });

nodeUpdate.select("circle")
.attr("r", 15)
.style("fill", function(d) { return d._children ? "white" :
"lightgray"; });

nodeUpdate.select("text")
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
.style("fill-opacity", 1);

// Transition exiting nodes to the parent's new position.


var nodeExit = node.exit().transition()
.duration(duration)
.attr("transform", function(d) { return "translate(" + source.y + ","
+ source.x + ")"; })
.remove();

nodeExit.select("circle")
.attr("r", 1e-6);

nodeExit.select("text")
.style("fill-opacity", 1e-6);

// Update the links…


var link = svg.selectAll("path.link")
.data(links, function(d) { return d.target.id; });

// Enter any new links at the parent's previous position.


link.enter().insert("path", "g")
.attr("class", "link")
.attr("d", function(d) {
var o = {x: source.x0, y: source.y0};
return diagonal({source: o, target: o});
});

// Transition links to their new position.


link.transition()
.duration(duration)
.attr("d", diagonal);

// Transition exiting nodes to the parent's new position.


link.exit().transition()
.duration(duration)
.attr("d", function(d) {
var o = {x: source.x, y: source.y};
return diagonal({source: o, target: o});
})
.remove();

// Stash the old positions for transition.


nodes.forEach(function(d) {
d.x0 = d.x;
d.y0 = d.y;
});
}

// Toggle children on click.


function click(d) {
if (d.children) {
d._children = d.children;
d.children = null;
} else {
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
d.children = d._children;
d._children = null;
}
update(d);
}

</script>

</body>
</html>

Consider the figure above. It contains a single html element. It turns out this includes within
it the entire content of your html file. If you click on the "html" red node, you'll find that it
contains two components, a head and a body. Clicking on each of those will reveal their
respective contents. This structure is what we computer scientists call a "tree". Any given
element (except for the outermost "html" element) is wholly contained inside another
element, referred to as the "parent" element. Not surprisingly, the elements contained within a
given element are its "child" elements. And, yes, children of a common parent are often
referred to as "siblings".

Thus in the example above, the top element is the html element, which contains just two
elements, the head and body.  The head element contains a title element and the
body contains an h1 element and a p element.  In a more typical example, the body would
contain many more children, but for our purpose this is enough. p is for "paragraph" (the text
between <p> and </p> will be separated by some space before the next element is displayed
in the final HTML page rendering), h1 means "heading level 1", and will be rendered by
default in bold with a bigger char size than any other text element, etc.

That may be a great picture, but how do we represent such a structure in a text file?  Well,
that's where "tags" come in.

HTML tags
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}

<html>
<BODY>

<p>

<em>

"Tags" are what we use to organize a text file (which is just a long string of characters) such
that it represents a tree of elements that make up the html document. Tags are not the
elements themselves, rather they're the bits of text you use to tell the computer where an
element begins and ends. When you "mark up" a document, you generally don't want those
extra notes that are not really part of the text to be presented to the reader.

HTML borrows a technique from another language, SGML, to provide an easy way for a
computer to determine which parts are "MarkUp" and which parts are the content. By using
"<" and ">" as a kind of parentheses, HTML can indicate the beginning and end of a tag, i.e.
the presence of "<" tells the browser "this next bit is markup, pay attention".

Whatever that tag (or "open tag") does, it applies to the content following the tag. Unless you
want that to be the entire rest of the document, you need to indicate when to stop using that
tag and do something else, so "<" and ">" are used again. Since elements are typically nested
within other elements, the browser needs to be able to distinguish between the end of the
current tag and the beginning of a new tag (representing a nested element). This is done by
adding a "/" right after the "<" to indicated that it's a "close tag". To indicate the beginning
and end of a paragraph (indicated by the single letter "p") you end up with something like
this:

1. <p>This is my first paragraph!</p>


div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
The browser sees the letters "<p>" and decides "A new paragraph is starting, I'd better start a
new line and maybe indent it". Then when it sees "</p>" it knows that the paragraph it was
working on is finished, so it should break the line there before going on to whatever is next.

For example, the "<em>" tag is used for element that needs Emphasis.  The  "<" and ">"
indicate that this is a tag, and the "little bits of text" in between tell us what kind of tag it is.
To completely describe the element, it needs an open and close tag, and everything in
between the tags is the contents of the element:

Most tags have open and close versions, but there are a few strange ones.  For more info, we
strongly recommend that you follow the W3Cx HTML5&CSS Fundamentals course, but we
generally refer to the strange ones as "self closing" tags.   Usually these tags represent an
element that is completely described by its attributes, and thus there is no need for other
content.  So if you see something like this:

1. <img src="https://goo.gl/pVxY0e" alt="Floating Flower"/>

... then you should know that the slash at the end of the open tag is sort of a shorthand for a
close tag, so you won't see any other indication that this element is now complete. There are
also a few tags that don't even use the "/" at the end, they just don't have any close tag at all.
This works because all of the information this tag needs is declared in an "attribute".
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
The <img> tag is one of them, the "/" at the end is optional and can be removed entirely, this
will still be valid HTML5.

1. <img src="https://goo.gl/pVxY0e" alt="Floating Flower">

These elements, without a "/" at the end, are called "void elements". They are : area,
base, br, col, embed, hr, img, input, link, menuitem, meta,
param, source, track, wbr.

HTML attributes

Most of what you can learn about HTML attributes is presented in the three W3Cx MOOCs
about HTML5 (fundamentals, coding essentials, and advanced techniques), but we
can introduce the idea briefly in this JavaScript course. Basically, a given element on your
Web page can be distinguished by any number of unique or common attributes. For example,
we've already seen how an image can be inserted in your Web page, and in that example we
used the width attribute of the <img> tag in order to constrain the width of the image:

1. <img
src="https://pbs.twimg.com/profile_images/110455194/n666194627_2302_400x400.j
pg"
2.      width=200 alt="Michel Buffa plays rock&roll">

As you might guess, the <img> tag also has a height attribute, as well as others. Different
HTML tags share some common attributes that we'll meet in the next section, which are
particularly useful when coupled with CSS (id and class) for applying graphic styles
(color, shadow, etc.), but  can also have specific attributes (for example: the src attribute can
be found in the <video>, <audio>, <img> tags but not on a <p> or on an <h1> tag!)

Try changing the value of the width attribute in the example below, or add a height attribute,
and see the result:

Live coding video: creating a simple Web page using common tags and
attributes

 (video downloaded)
Note : there is a small error in the live coding video.
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}

This shows a <h2> heading and <ol> nested in a <p> paragraph, I did not notice that while
shooting the video. The closing tag </p> should therefore be moved before <h2> starts, and
not be placed after <h2> and <ol> as demonstrated on the video. 

Michel Buffa

CSS is for style


Live coding video: using CSS to style HTML elements

Skip to main content

Live coding video: using CSS to style HTML elements

0:00 / 0:00

Press UP to enter the speed menu then use the UP and DOWN arrow keys to navigate the
different speeds, then press ENTER to change to the selected speed.

Click on this button to mute or unmute this video or press UP or DOWN buttons to increase
or decrease volume level.
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
Maximum Volume.

CSS, or Cascading Style Sheets, is a style sheet


language used to describe the way an HTML or XML document should look to a user. CSS is
where you specify the color, size, spacing, font and other visual aspects of the content that
you create in your markup language document.

Usually, you see CSS used alongside HTML to describe the way a Web page looks and feels.
You can have a Web page without CSS, but it would be very difficult to make it look the way
you want with just HTML. This is why almost every Web page is a combination of HTML
and CSS.

CSS • /si-ɛs-ɛs/ • noun 
Stands for "Cascading Style Sheets". A style sheet language for describing how to
display an HTML document.

Let's look at an example!

Let's take the (ridiculous) Michel Buffa home page again:

Notice the use of some HTML tags: h1, img, p, body etc.

Now, we can add some "CSS rules" to the HTML, and see that the appearance of the
resulting HTML page rendering is rather different (click on the HMTL/CSS buttons to see
alternatively the HTML or the CSS code, remember you can always make changes to the
code: change the color in the CSS part, etc.):

<!DOCTYPE html>

<html lang="en">

<head>

<title>Your first HTML page</title>


div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
<meta charset="utf-8"/>

</head>

<body>

<h1>My home page</h1>

<h2>Who am I?</h2>

<p>Hi! Welcome to my Home Page! My name is Michel Buffa, I'm a professor at the
University of Nice, in France, and I'm also the author of two MOOCS about HTML5 on
W3Cx.</p>

<p>I also play electric guitar and loves coding WebAudio applications...</p>

<img
src="https://pbs.twimg.com/profile_images/110455194/n666194627_2302_400x400.jpg"
alt="picture of Michel"

width=200>

<h2>My Hobbies</h2>

<p>Music, Movies, Video Games, Travelling, Family, etc.</p>

</body>

</html>

h1 {

color:red;

background-color:lightGreen;

border:12px solid violet;

padding: 5px;

border-radius: 15px;

text-align: center;
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
}

h2 {

color:brown;

p, h1, h2 {

font-family: cursive

img {

box-shadow: 10px 10px 15px grey;

p, img {

margin-left:50px;

If you click on the CSS button on the top left of the previous codepen example, you see the
CSS rules that have been applied to the HTML document. Let's look at the first one:

1. h1 {
2.     color:red;
3.     background-color:lightGreen;
4.     border:12px solid violet;
5.     padding: 5px;   
6.     border-radius: 15px;
7.     text-align: center;
8. }
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
This rule turns all the h1s in the document into red text, centered horizontally, on a light
green background, with a violet border of 12 pixels (a solid border, not a dashed one), and
this border has rounded corners made of arcs of a circle whose radius is 15 pixels.

The part before the opening brace (line 1) is the "CSS selector", it indicates the elements that
have their properties changed according to what is inside the braces.

The part inside the braces is a set of properties and values that are useful for setting the look
and feel of the selected elements.

Line 2 for example, says that all h1s is colored in red.

CSS rules are applied in sequence

After the previous rule is applied, then the second rule is taken into account, then the next,
etc. In this way, you can see that all h2s is in brown (second rule).

The third rule uses what is called "a multiple selector":

1. p, h1, h2 {
2.    font-family: cursive
3. }

This one says that all p, h1 and h2 uses a cursive font character. The "," means "and also".

This is also how we indicate in the last rule that images and paragraphs should be moved to
the right 50 pixels (property margin-left: 50px).

The id and class attributes

Basically, any given element on your Web page can be identified uniquely with an 'id'
attribute, or grouped with a class of other elements by setting the 'class' attribute.

1. <p id="paragraph-1" class="regular-paragraphs">


2.     Call me Ishmael . . .
3. </p>

The paragraph above has a unique identifier: the id attribute whose value is "paragraph-1"
and is part of a class of "regular-paragraphs". The letters inside the quotes have no meaning
to the computer, they just need to be consistent. They are actually strings. 

Again, the fact that the computer does not care what we put in those strings (except for some
restrictions) means we can use them to convey meaning to a human developer. I could just as
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
easily have said id='x' and class='y', but anyone looking at that would have no hint
what the significance of x and y are. Best practice is to name these things to increase clarity,
consistency and brevity.

Let's look at a modified version of Michel Buffa's home page example:

The last two rules first target the element whose id is 'hobbyTitle', in our case it's the second
h2 element:

<!DOCTYPE html>

<html lang="en">

<head>

<title>Your first HTML page</title>

<meta charset="utf-8"/>

<link href="https://fonts.googleapis.com/css?family=Caveat" rel="stylesheet">

</head>

<body>

<h1>My home page</h1>

<h2>Who am I?</h2>

<p>Hi! Welcome to my Home Page! My name is Michel Buffa, I'm a professor at the
University of Nice, in France, and I'm also the author of two MOOCS about HTML5 on
W3Cx.</p>

<p class="funny">I also play electric guitar and loves coding WebAudio
applications...</p>

<img
src="https://pbs.twimg.com/profile_images/110455194/n666194627_2302_400x400.jpg"

width=200>

<h2 id="hobbyTitle">My Hobbies</h2>

<p class="funny">Music, Movies, Video Games, Travelling, Family, etc.</p>


div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
</body>

</html>h1 {

color:red;

background-color:lightGreen;

border:12px solid violet;

padding: 5px;

border-radius: 15px;

text-align: center;

h2 {

color:brown;

p, h1, h2 {

font-family: cursive

img {

box-shadow: 10px 10px 15px grey;

p, img {
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
margin-left:50px;

#hobbyTitle {

font-family: 'caveat';

font-size:40px;

text-shadow: 4px 4px 2px rgba(150, 150, 150, 1);

.funny {

color:purple;

font-family: 'caveat';

font-size:40px;

1. <h2 id="hobbyTitle">My Hobbies</h2>

And here is the CSS rule:

1. #hobbyTitle {
2.   font-family: 'caveat';
3.   font-size:40px;
4.   text-shadow: 4px 4px 2px rgba(150, 150, 150, 1);
5. }
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
Line 1 uses the "#" character in the selector, meaning that we're going to select an element by
its id attribute. In this case, the selector equal to #hobbyTitle, selects the element that
has an attribute id="hobbyTitle".

In that case, we use a funny char font called 'caveat' we took from the
Google font service (see fonts.google.com), and in order to be able to use
it in a font-family CSS property, we included its definition using a <link>
tag in the HTML part of the document:

1. <head>
2.   <title>Your first HTML page</title>
3.   <meta charset="utf-8"/>
4.   <link href="https://fonts.googleapis.com/css?family=Caveat"
5.         rel="stylesheet">
6. </head>

The last rule targets all elements that have an attribute class="funny". Notice they can
be different elements, we can have a p and an h3 element that have the class="funny"
attribute:

1. .funny {
2.   color:purple;
3.   font-family: 'caveat';
4. font-size:40px;
5. }

This rule changes the color, font family and size of two out of three paragraphs in the HTML
element:

1. ...
2. <p class="funny">I also play electric guitar and love coding WebAudio
applications...</p>
3. ...
4. <p class="funny">Music, Movies, Video Games, Traveling, Family, etc.</p>

There are many, many, many different CSS properties in existence, and many different ways
to select elements. We recommend that you follow the W3Cx CSS Basics and HTML5&CSS
Fundamentals courses to learn more about CSS and about HTML5 basics.

Where can we put the CSS rules: in the HTML file? in another file? 

You can do both! 


div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
You can embed the CSS rules between a <style>...</style> tag, located inside the
<head>...</head> of the HTML documents, like in this example:

<!DOCTYPE html>

<html lang="en">

<head>

<title>Your first HTML page</title>

<meta charset="utf-8">

<style>

h1 {

color:red;

background-color:lightGreen;

border:12px solid violet;

padding: 5px;

border-radius: 15px;

text-align: center;

</style>

</head>

<body>

<h1>My home page</h1>

...

</body>

</html>
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
This is OK if you do not have too many CSS rules. In general it's better to put the CSS rules
in one or more separate .css files, like this (open this example in Plunker)

Note that when you use an online IDE, you usually type/paste the CSS rules in a "CSS tab" in
the online editor, and it hides all the "plumbing" for you (except the more complete ones such
as Plunker or AWS Cloud9 that enable you to manage files in the cloud).

Live coding video: mixing HTML and CSS

0:00 / 0:00

Press UP to enter the speed menu then use the UP and DOWN arrow keys to navigate the
different speeds, then press ENTER to change to the selected speed.

Click on this button to mute or unmute this video or press UP or DOWN buttons to increase
or decrease volume level.

Maximum Volume.

Video transcript

1. Start of transcript. Skip to the end.


2. In this video, I will show you how you can include CSS in your HTML file, because
we used
3. online tools that hide, in a way, the location of the different languages.
4. So, if you take this example we described in the previous video,
5. and if I export it using CodePen…
6. and if I look at the zip file that has been dowloaded,
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
7. you can see CSS file are located in the subdirectory and in a .css file.
8. This is a common way for organizing source code when you make a project with
HTML and CSS.
9. And if we open the "index.html" file, you can see that, what is really going on if we
look at the source code.
10. Actually, in order to include CSS file in an HTML file, we use the "link" tag with the
attribute
11. "rel = "stylesheet" and "href" = the name of the file.
12. So here, it means the "style.css" file located in the "css" subdirectory.
13. So if I open this project with Sublime Text …
14. I go to the directory I've just downloaded, and if I open the directory, I can see my
hierarchy, here.
15. The "index.html" file that includes the .css file.
16. And if I open the "style.css".
17. I can see the CSS content here. And it's interesting to use a real source code editor
because you've
18. got auto-completion on the name of the properties: « background-color".
19. You can use also some wizard for indicating or choosing the colors.
20. So if I take this color, it will give me directly the value and so on.
21. So you can edit your CSS, edit your HTML and when you save the result, you can
open directly
22. in your browser the file and see the result.
23. Here, I change the background-color of the heading 1.
24. You can also used directly in your HTML, the CSS rules.
25. In that case, instead of using the "link" element, you use the "style" element.
26. <style>, </style>, and like that you can directly include, in the HTML file, the style.
27. So I've got "h1" CSS rule, that will indicate how the "h1" will be rendered and I'm no
more including an external file.
28. If I save this and "Open in the Browser", I've go the same result here for the "h1".
29. And if I look at the source code, I will see directly in the HTML, the CSS rule.
30. So, to sum up, you can have your CSS in external file or inside the HTML file using
the "style" element.
31. End of transcript. Skip to the start.

Downloads and transcripts

Video downloaded

JavaScript is the "interactive glue"

Skip to main content


div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
Live coding video: JavaScript is the interactive glue between HTML and CSs

Video downloaded

JavaScript is the third of the "magic trio": HTML5/CSS/JavaScript. It is the only


programming language a browser can run (without installing any plugins or extensions), and
it's a real standard of the Web (even if not standardized by the W3C).

Why do we call it "the interactive glue between HTML and CSS"? 

Actually, this description does not do justice to JavaScript, which can do far more than just
act as glue. JavaScript can be run outside of the browser (on a nodeJS interpreter on a remote
server, or in scripts run by the operating system), but for this intro course, we focus on
"JavaScript" in the browser.

So, in the browser, JavaScript lies between HTML and CSS and will be used together with
these two languages. Let's take a look at two small examples:

Examp<!DOCTYPE html>

<html lang="en">

<head>

<title>JavaScript and HTML</title>

<meta charset="utf-8"/>

<script>

function changeTitle() {
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
var title = document.querySelector("#mainTitle");

title.innerHTML += "<br>This new <u>title</u> has been changed from


JavaScript!";

</script>

</head>

<body>

<h1 id="mainTitle">My home page</h1>

<p>This is an example of interactivity between JavaScript and the HTML content of


a document.</p>

<button onclick="changeTitle();">Click me to change the title of the page</button>

</body>

</html>

h1 {

color:red;

background-color:lightGreen;

border:12px solid violet;

padding: 5px;

border-radius: 15px;

text-align: center;

}
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
p, h1 {

font-family: cursive

p, img, button {

margin-left:50px;

Example #2: push another button to modify the CSS style (color, background-color,
border) of a paragraph in the page.

<!DOCTYPE html>

<html lang="en">

<head>

<title>JavaScript and HTML</title>

<meta charset="utf-8"/>

<script>

function changeTitleCSSStyle() {

var title = document.querySelector("#mainTitle");

title.style.color = 'black';

title.style.backgroundColor = "yellow";

title.style.border = "5px dashed red";

</script>
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
</head>

<body>

<h1 id="mainTitle">My home page</h1>

<p>This is an example of interactivity between JavaScript and the HTML content of


a document.</p>

<button onclick="changeTitleCSSStyle();">Click me to change the CSS colors of the


title of the page</button>

</body>

</html>

h1 {

color:red;

background-color:lightGreen;

border:12px solid violet;

padding: 5px;

border-radius: 15px;

text-align: center;

p, h1 {

font-family: cursive

}
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
p, img, button {

margin-left:50px;

We have a closer look at how these examples work in the subsequent parts of the course.
These examples are just here to show you how JavaScript can interact with the HTML
content and the CSS styles of a Web document.

Finally, note that, in these examples, the JavaScript code is located in the HTML of the
document.

JavaScript history
Skip to main content

JavaScript remains the most commonly used programming language with 67.7% of
developers employing it in 2020 (see this survey's results).

How and why JS was created?

Created out of necessity, it is used to build 97.4% of websites, including some of the world’s
largest, like Facebook and YouTube. Without it, we would not have popular and useful web
apps such as Google Maps and eBay.
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}

JavaScript was born in 1995 as part of the work of Brendan Eich's team at Netscape (the
ancestor of Mozilla). At that time, Netscape, in association with Sun MicroSystems, provided
popular server and client-oriented solutions (Netscape Navigator, ancestor of Firefox) which
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
depended on Java. (Sun Microsystems,  the company that created the Java programming
language, no longer exists, having been bought by Oracle Corporation in 2009.)

But Netscape realized that Java wasn't a suitable language for in-browser use. Netscape
thought of JavaScript at the beginning, as a lightweight Java.

JavaScript was initially inspired by Java, but in fact only some naming conventions remained
the same. We highly recommend not even trying to look for similarities - this is actually a
bad way to start learning JavaScript! We'd rather just say that the only real commonality
between these two languages is their names. If you are coming to this course from Java, leave
the Java thinking behind!

JavaScript quickly became a success following its first appearance in Netscape Navigator 2 in


March 1996, and it was quickly integrated into other popular browsers. Microsoft also
created its own version named JScript (and shipped it with Internet Explorer 3 in 1996).
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}

Netscap
e Navigator 2 in 1996, with big buttons and plain HTML pages (CSS did not exist at that
time)
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}

Inter
net Explorer 3 in 1996 - look at the official Yahoo page :-) CSS did not exist at this time!

Towards the end of 1996, JavaScript was standardized by ECMA as


the EcmaScript standard. So no matter whether you see it called JavaScript or
EcmaScript, don't worry, it's the same thing. EcmaScript has continued to be released
right up to the present day.
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}

The present: what is the current version?

What about ES6/ES2015/ES2016/ES2017/ES2018/ES2019/ES2020/ES2021?


Are these the new names of JavaScript?
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
Since 1996, multiple versions of JavaScript have appeared. For a long time, the stable version
supported by all major browsers deployed on computers and smartphones was EcmaScript
version 5 from 2010, but in 2015, a new version known first as EcmaScript 6 or ES 2015
came out with lots of new features (classes, etc.). Since then, every year a new version is
published, with some adjustments/novelties.  The latest official version is ES2021. 

Back in 2015, ES2015 was a pseudonym for the 6th version of the JavaScript


programming language to be approved by ECMA International, the standards group
responsible for vetting and approving different versions of the language. In June 2015,
ECMA International approved the 6th edition of the language. The name, ES2015, was used
because the latest version of JavaScript is identified as the 2015 version of ECMAScript (the
alternative name for JavaScript). Read this blog post about all these naming incongruities!

At the beginning, ES2015 was referred to as ES6 and before that, Harmony. Moving forward,
ES suffixed with the year of the latest approved standard is the naming convention. The next
version was called... ES2016, etc.!
Browser vendors do not wait that ECMA standardizes a version as they start implementing it
during the standardization process, which can take months or years (they also contribute to
the standardization process all along its life cycle).

The new open development process adopted by the ECMA TC39 committee decided that
every year, a new version will occur. This annual publication rate has been effective since
2015.

The current edition of the ECMA-262 standard is the 12th edition, published in June 2021
and is known as ES2021.

Beware: even on recent Web browsers the whole supported feature sets of the latest versions
are generally not completely implemented, as it takes time for browser vendors to follow the
standards!

Current support for ES2020/ 11th version (June 2020):

There is no easy-to-read table of current browser global support, but caniuse.com can be used
to check feature by feature which browsers support them. For example, this link shows the
support for the new "javascript private class fields" feature.

Up to date browsers usually support more than 90% of the features from the version
corresponding to the previous year. For example, in 2020, there is an good support for
ES2019, while certain features from ES2020 won't be implemented before some months.

Which version will we learn?


div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
First of all, this is an intro course! Not all features of JavaScript need to be covered, in
particular the ones that you cannot run in your browser without using advanced tools (there
are tools, such as Babel,  that can turn ESxxxx source code into ES5 code that can be run in
nearly any browser, but they are tricky to use and not for beginners).

We will cover all the important features of the last version that are relevant for an intro
course. 

Is JavaScript an important language to learn? What about Java, PHP, C#,


Python, Ruby and all the others?

JavaScript is the only programming language you can run in your browser. Without
JavaScript there would be no games, no fancy dynamic HTML forms, no interactive maps, no
Gmail, no YouTube, no Twitch TV, no Netflix....

JavaScript is integrated into nearly every popular Web browser and is probably the most
frequently used language in the world. More than 90% of Web documents now use
JavaScript too.

Every computer, smartphone, and tablet uses JavaScript many times a day within the browser
and even as native code! Indeed, some applications are compiled from their
JavaScript/HTML/CSS version into "classic" applications that can be run without a browser.
This compilation step can give an extra performance boost, the NetFlix application, or Office
365 are such applications.

In the beginning, JavaScript was invented to work not only on the client side (in Web
browsers) but also on the server side (on the Netscape HTTP Web server back in 1995).

In recent years this trend has returned, thanks to the appearance of the Node.js
server/JavaScript interpreter. It's common to see JavaScript applications running on a remote
Web server. Mastering JavaScript basics is highly recommended before trying to learn
JavaScript server side programming.

JavaScript is an interpreted language

JavaScript is an interpreted (or just-in-time compiled) language, which means that the code is
converted into a machine language at, or just before, runtime. The most popular JavaScript
engines are:

o SpiderMonkey (included in Mozilla Firefox)


o JavaScriptCore (included in Apple Safari)
o Chrome V8 (included in Google Chrome, in the Node.js server)
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
o Chakra (included in Microsoft Internet Explorer and now in the Microsoft
Edge browser)

Skip to main content.

W3Cx JS.0xJavaScript Introduction


Help
CourseProgressDatesDiscussion

1.

1. Course
2. /
3. Module 1: Introduction to JavaScript
4. /
5. 1.3 JavaScript overview

1.3.1 The best way to learn JavaScript


Live coding video: learn by the examples

(video downloaded)

What is the best method to learn JavaScript?

FIRST: learn by looking at and tweaking the code in the examples

Well, there is no definitive answer to this question, but I'd recommend firstly looking at small
examples, tweaking them and trying to guess what they do. You will rapidly discover that
you can learn a lot just by modifying a few lines of JavaScript code, even if you do not
understand the whole thing. 

During module 1, we give you some basics:

o How to write a simple HTML/CSS/JS page,


o Suggest some regular source code editors to use,
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
o How to use online environments that run in the browser, and offer an "instant
preview" of your creations. These tools are generally not suited for full scale
projects, but are really valuable for testing and learning.
o We present many examples (some short and some bigger ones) that will show
what can be done with JavaScript. We strongly encourage you to tweak them,
look at the code, download them on your hard disk, etc. Even if you do not
understand everything, have a go at modifying them; further down this page
we outline such an exercise.
o In further modules, we will be revisiting the examples, and discussing them in
greater detail and with fuller explanations.

SECOND: take some time to carefully read the sections titled "What you've
learnt / let's detail ...."

During the course, we provide extra "reference pages" that detail some important parts of the
language. For example, in a later section, we explain the concepts of "variables", "values",
"operators", "output", etc.

Here is an example - we provide some clues, but it's your job to tweak it!

Here is an example that uses an external JavaScript library useful for plotting math functions.
Look at the JavaScript code (click on the JS button) and try to guess where the function is
specified, where the range for the x and y values is set, etc. Notice that you can use your
mouse wheel to zoom in/out the function plot.

Html:

<!DOCTYPE html>

<html lang="en">

<head>

<title>Plotting functions in JavaScript using the

function plot library</title>

<meta charset="utf-8"/>

<script src="https://d3js.org/d3.v3.min.js"></script>

<script src="https://mauriciopoppe.github.io/function-plot/js/function-plot.js"></script>
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
</head>

<body>

<div id="myFunction"></div>

</body>

</html>

Css: div {

float: left;

#myFunction {

padding: 25px;

width: 250px;

height: 250px;

Js: var parameters = {

target: '#myFunction',

data: [{

fn: 'sin(x)',

color: 'red'

],

grid: true,
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
yAxis: {domain: [-1, 1]},

xAxis: {domain: [0, 2*Math.PI]}

};

functionPlot(parameters);

By looking at this example (HTML and JS code), you note a few things:

Two lines in the HTML code that correspond to the inclusion in the document of some
external JavaScript code:

1. <script src="https://d3js.org/d3.v3.min.js"></script>
2. <script src="https://mauriciopoppe.github.io/function-plot/js/function-plot.js"></
script>

We will examine this soon in a later section of the course, but, in brief, it means that we will
use the d3js plotting library, and another from github (a famous repository for open source
contributions), and located in the github account of a person named "mauriciopoppe", the
repository is named "function plot" ("function plot JavaScript library").

Then, looking at the JavaScript code of the example (click the JS button on the CodePen
example), we see:

1. functionPlot({
2.        target: '#myFunction',
3.        data: [{
4.        fn: 'sin(x)',
5.        color: 'red'
6.     }],
7.     grid: true,
8.     yAxis: {domain: [-1, 1]},
9.     xAxis: {domain: [0, 2*Math.PI]}
10. });
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
Ok, the syntax looks strange if you are not used to JavaScript, but I bet that you guessed that
the function plotted is "sin(x)", that the color of the curve is "red", that the range of the x
values is [0, 2*PI], and the range of the y values is [-1, 1].

Your job:

1. try to plot sin(x^2),


2. try to change the domain for the x and y values,
3.  try to change the color of the curve, etc.

To do this:

o Edit directly the JS code in the embedded example, after a few seconds, you
should see the updated result in the "Results" tab,
o ...or just click on the "Edit on CodePen" title on the top right of the embedded
example, then change  the code. Normally you should see the results of your
modifications as soon as you stop typing (we call this "live coding"). (Here is
an example of what you can obtain as a result).

What can you guess from this example?

A function call

You can think of this code in this way:

1. functionPlot(...);

Where the "..." corresponds to some sort of parameter. When you see a name followed by two
parentheses (maybe with something in between) followed by a ";", this is "a function call". 

A function is a piece of code defined somewhere else, that can accept parameters (the "thing"
between the parentheses), and that will do something. In our case the function's name
is "functionPlot" and we can assume (or we read the documentation of the library) that
the goal of this function is to plot a mathematical function, as its name tells us.

Function parameters

The "thing" between parentheses is what we call "the parameters of the function": the data we
pass to the function so that it can plot different math functions, with different colors, with
different ranges for the x and y values, with or without a grid, etc.

Let's have a look at the parameters we used in our example (the ones you tweaked). They are
in bold in the source code we saw earlier:
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
1. {
2.     target: '#myFunction',
3.     data: [{
4.              fn: 'sin(x)',
5.              color: 'red'
6.           }],
7.     grid: true,
8.     yAxis: {
9.          domain: [-1, 1]
10.     },
11.     xAxis: {
12.          domain: [0, 2*Math.PI]
13.     }
14. }

JavaScript object

In JavaScript you can have simple values like: 2, 5, "hello", "3.14", and you may also
encounter more "structured" values that we call "objects". In Module 3 we will address
JavaScript objects, but for the moment we will just present them through examples, without
too much detail.

A JavaScript object can be defined by two braces with a set of properties/values inside,


separated by a comma. Here is a simple object:

1. {
2.    givenName: "Michel",
3.    familyName: "Buffa"
4. }

We use the ":" separator between the property name and its value. We use a comma between
two properties, and we omit the comma after the last property (or before the ending brace).

In our examples, the properties of the object that is passed as a parameter to the
functionPlot(...) call are in bold.

They are respectively:

o target: the CSS selector that corresponds to the HTML element that will
contain the plot. Look at the HTML code (<div
id="myFunction"></div>), the id value corresponds to target:
"#myFunction" in the object.
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
o data: this is where we indicate the value of the function(s) to be plotted. We
talk about this in greater detail below.

o grid: this can be true or false (we call these "boolean values") and
indicates whether or not we want a grid to be drawn in the background.
o xAxis: the value specifies the domain (range) for the x values...
o yAxis: the value specifies the domain (range) for the y values...

Notice that after each property (color, grid, etc.) there is a ",". Notice that between the
name of the properties and the value there is a ":", etc...

Embedded objects

If we look at the values of the xAxis and yAxis properties, they are also objects.

1. xAxis: {
2.     domain: [0, 2*Math.PI]
3. }

The data object is even more complicated:

1. data: [{
2.    fn: 'sin(x)',
3.    color: 'red'
4. }],

Instead of containing another object like xAxis or yAxis, it contains another sort of object,
but inside brackets! In JavaScript, brackets are used to create arrays of "things" (multiple,
enumerable things). In this example, the array contains one single object that has two
properties:

o fn: the value of the function to be plotted, in this case sin(x),


o color: the color of the curve
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
In arrays, the different elements are separated by commas. Let's try to plot an additional
function in our example. We will add f(x) = cos(x) to our example, with a different color:

1. data: [

1.   {
2.        fn: 'sin(x)',  // First function
3.        color: 'red'
4.     },
5.   {
6.        fn: 'cos(x)',  // second function
7.        color: 'blue'
8.   }
9. ]

Html:

<!DOCTYPE html>

<html lang="en">

<head>

<title>Plotting functions in JavaScript using the

function plot library</title>

<meta charset="utf-8"/>

<script src="https://d3js.org/d3.v3.min.js"></script>

<script src="https://mauriciopoppe.github.io/function-plot/js/function-plot.js"></script>

</head>

<body>

<div id="myFunction"></div>

</body>

</html>
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
Css:

div {

float: left;

#myFunction {

padding: 25px;

width: 250px;

height: 250px;

Js:

functionPlot({

target: '#myFunction',

data: [{

fn: 'sin(x)',

color: 'red'

},

fn: 'cos(x)',

color: 'blue'

}],

grid: true,
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
yAxis: {domain: [-1, 1]},

xAxis: {domain: [0, 2*Math.PI]}

});

Conclusion

Just by looking at one example, and without going into the boring details, you saw:

o How to plot a function using a third party library and how to include it in your
code,
o How to change some parameters without knowing JavaScript in depth,
o You had a first encounter with concepts such as: "a function call", "function
parameters", simple objects, embedded objects and arrays (we will discuss
them as we move through the course).

Not bad ;-)

Live coding video: what can be done with JavaScript

(video downloaded)

What can be done with JavaScript:

1) interact with the HTML and CSS content of a document, respond to events

We have already seen three examples in previous parts of this week's course material.

Html:

<!DOCTYPE html>

<html lang="en">

<head>

<title>JavaScript and HTML</title>


div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
<meta charset="utf-8"/>

<script>

function changeTitle() {

var title = document.querySelector("#mainTitle");

title.innerHTML += "<br>This new <u>title</u> has been changed from JavaScript!";

</script>

</head>

<body>

<h1 id="mainTitle">My home page</h1>

<p>This is an example of interactivity between JavaScript and the HTML content of a


document.</p>

<button onclick="changeTitle();">Click me to change the title of the page</button>

</body>

</html>

Css:

h1 {

color:red;

background-color:lightGreen;

border:12px solid violet;

padding: 5px;

border-radius: 15px;
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
text-align: center;

p, h1 {

font-family: cursive

p, img, button {

margin-left:50px;

This first example used the selector API for selecting a particular element in the document
(the main title) and the DOM API for modifying its content.

o An API is an application programming interface. In the case of JavaScript,


the DOM API is implemented natively by the browser, and you can call
several functions/methods or access properties of the DOM:  an object that
represents the document (the Web page). 

It uses the selector API to target a particular part of the DOM (in our case, the main title of
the page), the HTML element with an id attribute equal to "mainTitle". The selector API
uses the same syntax as CSS to select elements in the document. In our case,
"#mainTitle" is a selector value that means "the element whose id is equal to
mainTitle".

1. var title = document.querySelector("#mainTitle");

It uses the DOM API to change the HTML content of the selected element:

1. title.innerHTML = "This new title has been changed from JavaScript!";

It listens to click events in order to call the changeTitle() function when we click on
the button:
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
1. <button onclick="changeTitle();">Click me to change the title of the page</button>

And it executes the whole action (changing the title text) in a function (a block of code that is
executed only when we call it by adding a parenthesis after its name, followed by a semi
colon):

1. function changeTitle() {
2.     var title = document.querySelector("#mainTitle");
3.     title.innerHTML = "This new title has been changed from JavaScript!";
4. }

Html:

<!DOCTYPE html>

<html lang="en">

<head>

<title>JavaScript and HTML</title>

<meta charset="utf-8"/>

<script>

function changeTitleCSSStyle() {

var title = document.querySelector("#mainTitle");

title.style.color = 'black';

title.style.backgroundColor = "yellow";

title.style.border = "5px dashed red";

</script>

</head>

<body>

<h1 id="mainTitle">My home page</h1>


div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}

<p>This is an example of interactivity between JavaScript and the HTML content of a


document.</p>

<button onclick="changeTitleCSSStyle();">Click me to change the CSS colors of the title


of the page</button>

</body>

</html>

Css:

h1 {

color:red;

background-color:lightGreen;

border:12px solid violet;

padding: 5px;

border-radius: 15px;

text-align: center;

p, h1 {

font-family: cursive

p, img, button {

margin-left:50px;
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
}

The second example is nearly the same except that we changed the name of the function, and
instead of using the DOM API to update the text content of the main title, we use its style
property to change its look and feel. Using the style property is a way of altering the
CSS property values of this HTML element.

1. function changeTitleCSSStyle() {
2.     var title = document.querySelector("#mainTitle");
3.     title.style.color = 'black';
4.     title.style.backgroundColor = "yellow";
5.     title.style.border = "5px dashed red";
6. }

title is in reality what we call "an object" and style is a property of the title object. The
style is an object as well and has attributes that correspond to the different CSS properties
we set. For example, style.color returns the color that element has set on it. By calling
title.style.color = "yellow"; you can apply the style change dynamically.

Some of you may be wondering what happens when the CSS property being set has a
hyphen. The syntax has to be different here, because, for example, if you write
title.style.background-color, JavaScript will try to subtract color from the
title.style.background notation, which is not what you want to happen. To stop
this problem from occurring, all the CSS properties are written out in CamelCase: the CSS
name background-color becomes backgroundColor, text-size becomes
textSize, border-color becomes borderColor etc.

Don't worry, we will return to this later in this course, these first examples are just here as an
introduction.

The third example (outlined in the previous section), which showed how to plot math
functions, illustrated that with a few lines of code you can reuse code from others (a third
party JavaScript library).

2) use numerous APIs in addition to the DOM and selector APIs: multimedia,
drawing, animating, geolocation, webcam, etc.

Your browser comes with a lot of different "libraries" that are called "standards APIs" for
"application programming interfaces". Such APIs are "W3C standards" and are present in all
Web browsers that follow the Web Standards. You will have APIs for manipulating
multimedia (audio and video), geolocation (getting the longitude and latitude), orientation (on
mobile devices), accessing the webcam or the microphone, etc. In a later section we will
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
provide a set of examples that use some of the most useful APIs provided by your Web
browser.

Example of an HTML page that embeds an interactive OpenStreet Map (you need to click
the CodePen logo on top right to run this example. For security reasons it cannot be run
inside this course page).

Html:

<html>
<head>
<meta charset="utf-8">
<title>OpenStreetMap Example</title>
<link rel="stylesheet"
href="https://unpkg.com/leaflet@1.0.3/dist/leaflet.css">
<script src="https://unpkg.com/leaflet@1.0.3/dist/leaflet.js"></script>
</head>
<body>
<button class="btn" onclick="getLocation(event)">Click to show your
location with OpenStreetMap</button>
<div id="map" class="map"></div>
</body>
</html>

Css:

html, body {
height: 100%
}

.map {
height: 300px;
}

.btn {
background-color: rgba(10, 10, 230, .5);
border: 0;
color: #fff;
padding: 10px;
text-shadow: 0 0 1px rgba(0, 0, 0, .3);
text-decoration: none;
margin: 0.5rem 0 1rem;
display: inline-block;
}
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}

Js:

function getLocation(e) {
e.preventDefault();
if (!navigator.geolocation) {
alert("Browser doesn't support geolocation");
} else {
navigator.geolocation.getCurrentPosition(success, error);
}
}

// Get current position successfully


function success(position) {
var map, marker,
latitude = position.coords.latitude,
longitude = position.coords.longitude;

// Instance map using leaflet


map = L.map('map').setView([latitude, longitude], 13);

// Tile layer using key api at cloudmade.com


L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
key: '760506895e284217a7442ce2efe97797',
styleId: 103288,
maxZoom: 16
}).addTo(map);

// Marker using leaflet


marker = L.marker([latitude, longitude]).addTo(map);

// Popup in leaflet
marker.bindPopup('<p>Your location</p>').openPopup();
}

// Get current position fail


function error() {
alert('Get current position fail. Please access codepen to get
geolocation.');
}
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}

3) work with remote data / speak with a remote HTTP Web server

You can also download or upload data from your browser to a remote Web server. When this
is done from JavaScript the popular term to describe such operations is "AjaX"
(Asynchronous JAvascript and Xml), even though XML is not used in any examples you'll
see in this course (XML is a language for describing structured data that was very popular a
few years ago).

Here is an example that will display the current and past members of famous rock bands:

Html:

<!DOCTYPE html>

<html lang="en">

<head>

<title>Working with remote data</title>

<meta charset="utf-8"/>

<!-- Polyfill in case your browser does not support the fetch API -->

<script src="https://cdnjs.cloudflare.com/ajax/libs/fetch/0.10.1/fetch.js"></script>

</head>

<body>

<p>

Type in the name of a Rock Band (ex: "The Rolling Stones", "Metallica", "The Who", "The Beatles",
"Led Zeppelin", "Van Halen", "Grateful Dead").</p>

<label for="bandName">Band Name: </label>

<input type="text" id="bandName" value="Metallica">

<button onclick="search();">Look for members</button>

<div id="members"></div>

</body>
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
</html>

Css:

table {

margin-top: 20px;

table, tr, td {

border: 1px solid;

td {

padding:10px;

Js:

var membersDiv = document.querySelector("#members");

function init() {

console.log("page loaded");

function search() {

var bandName = document.querySelector("#bandName").value;

console.log(bandName);

// API for getting info about an artist/band by name

var url = encodeURI("https://wasabi.i3s.unice.fr/api/v1/artist/name/" + bandName);


div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
console.log(url);

membersDiv.innerHTML = "";

fetch(url)

.then(function(response) {

// response is a json string,

// convert it to a pure JavaScript object

return response.json();

})

.then(function(band) {

membersDiv.innerHTML += "<h2>Current and old members of " +band.name + "</h2>"

displayMembers(band.members);

})

.catch(function(error) {

console.log('Error during fetch: ' + error.message);

membersDiv.innerHTML += "<h2>No Results</h2>"

});

function displayMembers(listOfMembers) {

// users is a JavaScript object

var table = document.createElement("table");

listOfMembers.forEach(function(member) {

// iterate on the array of members

var row = table.insertRow();

var memberNameCell = row.insertCell();

memberNameCell.innerHTML = member.name;
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}

// Show instruments played by this member

var instrumentCell = row.insertCell();

member.instruments.forEach(function(inst, index) {

instrumentCell.innerHTML += inst;

if(index !== member.instruments.length-1) {

instrumentCell.innerHTML += ",";

});

var activeYearsCell = row.insertCell();

activeYearsCell.innerHTML += member.begin;

if(member.end !== "") {

activeYearsCell.innerHTML += " - " + member.end;

} else {

activeYearsCell.innerHTML += " - still active in band";

});

membersDiv.appendChild(table);

var membersDiv = document.querySelector("#members");

function init() {

console.log("page loaded");

function search() {
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
var bandName = document.querySelector("#bandName").value;

console.log(bandName);

// API for getting info about an artist/band by name

var url = encodeURI("https://wasabi.i3s.unice.fr/api/v1/artist/name/" + bandName);

console.log(url);

membersDiv.innerHTML = "";

fetch(url)

.then(function(response) {

// response is a json string,

// convert it to a pure JavaScript object

return response.json();

})

.then(function(band) {

membersDiv.innerHTML += "<h2>Current and old members of " +band.name + "</h2>"

displayMembers(band.members);

})

.catch(function(error) {

console.log('Error during fetch: ' + error.message);

membersDiv.innerHTML += "<h2>No Results</h2>"

});

function displayMembers(listOfMembers) {

// users is a JavaScript object


div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
var table = document.createElement("table");

listOfMembers.forEach(function(member) {

// iterate on the array of members

var row = table.insertRow();

var memberNameCell = row.insertCell();

memberNameCell.innerHTML = member.name;

// Show instruments played by this member

var instrumentCell = row.insertCell();

member.instruments.forEach(function(inst, index) {

instrumentCell.innerHTML += inst;

if(index !== member.instruments.length-1) {

instrumentCell.innerHTML += ",";

});

var activeYearsCell = row.insertCell();

activeYearsCell.innerHTML += member.begin;

if(member.end !== "") {

activeYearsCell.innerHTML += " - " + member.end;

} else {

activeYearsCell.innerHTML += " - still active in band";

});

membersDiv.appendChild(table);

}
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}

Where to put JavaScript code


Live coding video: where to put JavaScript code?

(downloaded)

JavaScript code can be located in different places

1. In your HTML code between <script> and </script> tag


2. In local files, usually ending with the .js suffix (i.e: in a script.js file),
and included using, for example, a syntax such as: <script
src="style.js"></script> tag
3. In external files located on the Web, using their URLs, also using the
<script
src="https://www.aserver.com/..../js/script.js"></sc
ript> tag

Here are some examples:

Example #1:  the JavaScript code is included in an HTML file using the
<script>...</script> tag

First variant: in the <body>..</body> of the HTML document

Typically:

1. <body>

1. ...

1.  <script>
2.    var x = 2;
3.    // show a message in the body of the html document
4.    document.body.innerHTML += "<b>JavaScript code executed. The value of the
variable x is: " + x + "</b>";
5.    // also print a message in the devtool console
6.    console.log("JavaScript code executed");
7.  </script>
8. ...
9. </body>

Here is this first example on CodePen:


div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Example 1</title>

</head>

<body>

<h1>Example 1: js in the .html file</h1>

<p>Open the dev console (F12 or ctrl-shift-i or cmd-alt-i), and see that the

JavaScript code has been executed.</p>

<script>

var x = 2;

// show a message in the body of the html document

document.body.innerHTML += "<b>JavaScript code executed. The value of the variable x


is: " + x + "</b>";

// also print a message in the devtool console

console.log("JavaScript code executed");

</script>

</body>

</html>
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
Old JavaScript examples may use a type attribute:
<script type="text/javascript">.
The type attribute is now obsolete and should be ignored.

Second variant: in the <head>...</head> of the document

In this example, the <script>...</script> element is placed in the


<head>..</head> section of an HTML page.

This time, we placed a JavaScript function that is invoked (called) when a button is clicked:

1. <head>
2.   <script>
3.      function addSomeText() {
4.         // append a message in the body of the html document
5.         document.body.innerHTML += "<br>Function executed!";
6.      }
7.   </script>
8. </head>
9. <body>
10. <button onclick="addSomeText();">Click me to call a JavaScript function that will
add
11.    some content to this document
12. </button>
13. </body>

Here is this second example on CodePen:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Example 2</title>

<script>

function addSomeText() {

// append a message in the body of the html document


div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
document.body.innerHTML += "<br>Function executed!";

</script>

</head>

<body>

<h1>Example 2: js in the .html file, but this time in the &lt;head&gt;...&lt;/head&gt; of the
document</h1>

<button onclick="addSomeText();">Click me to call a JavaScript function that will add


some content to this document</button>

</body>

</html>

Example #2: put the JavaScript code in local .js files

Putting JavaScript code in external scripts files is easy, and offers many advantages:

1. It separates HTML and code (and also CSS code, if you use external CSS
files)
2. It makes HTML and JavaScript easier to read and maintain
3. JavaScript files can be reused more easily in other projects
4. Cached JavaScript files can speed up page loads

A typical example:

1. <head>
2.    ...
3.    <link rel="stylesheet" href="css/style.css">
4.    <script src="js/script.js"></script>
5. </head>

To use an external JavaScript file:

1. In the HTML, put the name of the script file in the src (source) attribute of a
<script> tag, like in the typical example above,
2. JavaScript files must end with the .js extension,
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
3. Do no use any <script>...</script> tag in a .js file!
4. Using an external JavaScript file with <script src="..."></script>
is 100% equivalent to using <script>...</script> with the file
content between the opening and closing tags. 
5. It's possible to use more than one JavaScript file, just use multiple <script
src="..."></script>

Example that uses more than one JavaScript file:

1. <head>
2.    ...
3.    <link rel="stylesheet" href="css/style.css">
4.    <script src="js/script1.js"></script>
5.    <script src="js/script2.js"></script>
6.    <script src="js/anotherOne.js"></script>
7.    ...
8. </head>

A typical HTML/CSS/JS project folder structure, when working with external local files

It is good practice to locate CSS files in a css subfolder, and JavaScript files in


a js subfolder.

In this example, we have just one CSS file and one JavaScript file:
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}

Content of the index.html file:

1. ...
2. <head>
3.    ...
4.    <link rel="stylesheet" href="css/style.css">
5.    <script src="js/script.js"></script>
6. </head>
7. <body>
8. <h1>Example 3: JavaScript and CSS in local files!</h1>
9. <button onclick="addSomeText();">Click me to call a JavaScript function that will
add some content to this document</button>
10. </body>
11. </html>

Content of the js/script.js file (JavaScript file):

1. function addSomeText() {
2.    document.body.innerHTML += "<p>Function executed!</p>";
3. }

Content of the style.css file:

1. p {
2.    color:green;
3. }

How to run this example:

1. Download the zip file of this project: Example_3.zip


2. Unzip/unarchive it somewhere
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
3. Double click the index.html file, this will open your Web browser and load the
index.html file.
4. Click on the button in the page

Example #3: use external references to JavaScript files/libraries located on the


Web

External JavaScript libraries (they are just big JS files) can be also referenced with a full
URL, like in this example:

1. <script src="https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.22/paper.js"></script>

Here, we just included in our HTML document the excellent paperJS library that can be used
to make fancy animations in the HTML canvas element - we will use it later in the course. 

Once the library is included, the JavaScript code you will write can call functions located in
this library. This "reuse existing" work made by others is really common when working on
JavaScript projects.

Here is a running example that uses the paperJS library, included using an external URL:

<!DOCTYPE html>

<html>

<head>

<title>Example 4: use an external JS file</title>

<meta charset="utf-8"/>

<script src="https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.22/paper.js"></script>

</head>

<body>

<canvas id="canvas" resize></canvas></body>

</html>

body {

bleh:adf;

meh:d;
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
}

html {

paperScript = function() {

var mousePoint = view.center;

var amount = 25;

var colors = ['red', 'white', 'blue', 'white'];

for (var i = 0; i < amount; i++) {

var rect = new Rectangle([0, 0], [25, 25]);

rect.center = mousePoint;

var path = new Path.Rectangle(rect, 6);

path.fillColor = colors[i % 4];

var scale = (1 - i / amount) * 20;

path.scale(scale);

function onMouseMove(event) {

mousePoint = event.point;

var children = project.activeLayer.children;

function onFrame(event) {

for (var i = 0, l = children.length; i < l; i++) {

var item = children[i];


div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
var delta = (mousePoint - item.position) / (i + 5);

item.rotate(Math.sin((event.count + i) / 10) * 7);

if (delta.length > 0.1)

item.position += delta;

var a = document.createElement('script')

a.setAttribute('type', 'text/paperscript');

a.setAttribute('canvas', 'canvas');

var src = paperScript.toString();

a.appendChild(document.createTextNode(src.substring(src.indexOf('\n') + 1, src.lastIndexOf('\n'))));

document.body.appendChild(a);

How to debug JavaScript


Live coding video: how to open the browser devtool console

(downloaded)

Let's introduce what is debugging.

You will make errors!

When you are developing a Web Application that contains JavaScript code, you will make
errors. 

Repeat after me: "I WILL MAKE ERRORS!" ; "I WILL MAKE ERRORS!"

So there will be error messages, and you will need to print messages for debugging your
code. We will see more advanced debugging techniques at different points in this course, but
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
for the moment, let's see the basics of JavaScript debugging: seeing error messages in the
devtool console, or in the "console tab" of your source code editor.

We will not look at the JavaScript syntax here, but more at "JavaScript in the browser", how
it works, how to start writing code, etc.

First of all, you need to find a way to debug your code and see errors. If your work does not
produce any results, you need to know why!

Your Swiss army knife: your browser devtools, especially the devtool console!

For this you will use the dev. tools of your browser. Press F12 (or ctrl-shift-i) in Windows


or cmd-option-i in MacOS to open the dev. tools, then go to the console tab: this is where
errors will be displayed, or messages of your own (use
the console.log(string) JavaScript function in the JavaScript code embedded in your
html page). In the console, you will be able to type any JavaScript command.

Let's look at this example below (or online as a JS Bin):

1. <!DOCTYPE html>
2. <html lang="en>
3. <head>
4. <meta charset=utf-8 />
5. <title>Web Audio API</title>
6. <script>
7. console.log("Some JavaScript code has been executed");
8. </script>
9. </head>
10. <body>
11. <h1>JavaScript debugging using the dev tool console</h1>
12. </body>
13. </html>

The simplest way to add JavaScript code in an HTML page is to use
the <script>...</script> element.

The code in this example is executed sequentially when the page is loaded: the JavaScript
code is executed before the browser could see the rest of the page (as
the <script></script> is located before the <body>).

The H1 element, for example, does not exist in the Document Object Model, and has not yet
been displayed when the JavaScript code is executed. If we move
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
the <script></script> at the end of the document, then the H1 would have been built
before the JavaScript code is executed.

The only line of code we have is console.log("Some JavaScript code has


been executed");

This means "display in the JavaScript console the message...". If we open the console tab
provided by jsbin.com in a dedicated tab (that redirects all console.log() messages),
and re-execute the page (just type a space at the end of a line to re-render the page and
display the message in the console), we see the message in the console tab, as well as in the
dev. tools console. This is illustrated by the image below (or online):

It is also possible to use the "real dev. tool console", and for this, I recommend running the
application in a single window, not in the Js Bin editor. Press the black arrow on the top right
of the output window - this will render the page as a standalone Web page, then press F12.
You should see:
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}

Ok, now, let's make an error: change console.log() into consollle.log(). Let's


see what happens:
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}

And if we run it standalone and use the dev. tool console:


div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}

And if we click on the line number to the right, the dev. tool shows the source code centered
on the line that caused the error:
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}

Without such tools, debugging JavaScript code is impossible. So you need to look at some
basic tutorials on how to use the dev. tools of your browsers, since they differ from one
another in the way they work - although the principles remain the same.

4.1 Creating an HTML/CSS/JS project


Skip to main content

Let's create a small HTML/CSS/JS project together.

It's time for you (and me) to create a small HTML/CSS/JS project, step by step, following
some best practices. We will do this using different tools: source code editors + files but also
two online IDEs (JsBin.com and CodePen.io). We will see how to write/debug the code and
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
also how to migrate a project prototyped with online tools to a project you can run and edit on
your hard drive using regular source code editors.

Many things we use in this example may be new to you. Don't worry. We will cover them
either later on this week or over the following weeks. It's time to throw you in the deep end
of the JavaScript world, getting you to write code, and look at examples etc. And from time
to time, we will take a break and have a "real", "academic", look at the concepts of the
language you have been using. We think this is the best way for you to learn!

Topic

We will write a small, interactive HTML page that will use some HTML input fields for
indicating the name of a math function we'd like to plot, the ranges for the x and y values, the
color of the curve etc.

We will first write this application online, using the JsBin.com editor, then we will do the
same thing using the CodePen online editor, then, using a regular source code editor
and .html, .css and .js files.

Here is what the resulting Web page will look like:

 HTML

<!DOCTYPE html>
<html lang="en">
<head>
<title>Plotting functions in JavaScript using the
function plot library</title>
<meta charset="utf-8"/>
<script src="https://d3js.org/d3.v3.min.js"></script>
<script src="https://mauriciopoppe.github.io/function-plot/js/function-
plot.js"></script>
</head>
<body onload="plot();">
<h2>Interactive function plotter</h2>
<section id="plotSettings">
<label for="xMin">xMin: </label>
value: <input type=number id="xMin" value=0 step=0.5
oninput="plot();">
<p></p>
<label for="xMax">xMax: </label>
value: <input type=number id="xMax" value=6.28 step=0.5
oninput="plot();">

<p></p>
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
<label for="yMin">yMin: </label>
value: <input type=number id="yMin" value=-1 step=0.5
oninput="plot();">
<p></p>
<label for="yMax">yMax: </label>
value: <input type=number id="yMax" value=1 step=0.5
oninput="plot();">
<p></p>
<label for="color">Color: </label>
value: <input type=color id="color"
onchange="plot();">
<p></p>
<label for="function">Function to plot: </label>
<input id="function" type="text"
value="sin(x)"
onchange="plot();">
<p></p>
<button onclick="plot();">Plot it!</button>

</section>

<section id="plot">
<div id="myFunction"></div>
</section>

</body>
</html>

 CSS

section {
border:4px solid grey;
border-radius:15px;
box-shadow: 5px 5px 5px grey;
float:left;
height:360px;
padding: 20px;
margin:10px;
}

#plotSettings {
width:140px;
}
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}

#plot {
width:550px;
}

 JS

var parameters = {
target: '#myFunction',
data: [{
fn: 'sin(x)',
color: 'red'
}],
grid: true,
yAxis: {domain: [-1, 1]},
xAxis: {domain: [0, 2*Math.PI]}
};

function plot() {
var f = document.querySelector("#function").value;
var xMin = document.querySelector("#xMin").value;
var xMax = document.querySelector("#xMax").value;
var yMin = document.querySelector("#yMin").value;
var yMax = document.querySelector("#yMax").value;
var color = document.querySelector("#color").value;

parameters.data[0].fn = f;
parameters.xAxis.domain = [xMin, xMax];
parameters.yAxis.domain = [yMin, yMax];
parameters.data[0].color = color;

functionPlot(parameters);
}

Live coding video: using CodePen

In the video, at 3:19, there are some mistakes in the HTML code:
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
1. This line uses a wrong value for the for attribute (it should be the same value as the
id attribute of the input field): <label for="yMax">Color: </label>
value: ... should be: <label for="color">Color value:
</label> ...
2. Improvement in the code could be to replace all empty paragraphs <p></p> by line
breaks <br> or by a single <p>.

CodePen example with the starting code used in the video

If you want to code while watching the video, please open this CodePen. It contains the
source code of the example we started coding from. 

And here is the same version with the polyfill for the <input type="color"> input
field, not yet supported by Safari.

In case you have a hard time to follow the video, here is the full example (this link points to
the example from the previous course page).

Live coding video: using SublimeText

(downloaded)

.1 JS variables and values


Live coding video: JavaScript variables

(downloaded)

In most of the examples seen earlier, we've used the concept of "variable", and we have used
them to "store values". It's time to take a break and talk about them :-)

Variables

In order to remember a value, programming languages share the concept of "variables".


When you write programs, you will need to store values in the computer's memory. By
saving these values in "variables", by giving them a "name" (we call it an identifier), you can
reuse them later for display, for computations, etc.

Create (declaring) a variable

With JavaScript versions < 5 (prior to 2015), there was a single way to create (we say
"declare") a variable: using the var keyword. But with the subsequent versions (called
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
ES2015/ES2016 or JavaScript 6/7), we can also use the keyword let (this has some subtle
differences, which we'll explain later in the course when we will talk about "functions").

JavaScript is weakly typed. Each variable is declared with the keyword var or let. So
you are not required to specify the type of variable you are creating. After the keyword
"var" and a space, just give the name of the variable.

Example:

1. var myVar;
2. let x;

The first letter of a variable can only be "$", "_", "a" to "z", or "A" to "Z". The other
characters in a name must be any of these, or numeric digits. The name is case sensitive. So
variables "myVar" and "MyVar" are different variables.

There are some reserved names that you can't use as a variable name: boolean, if,
delete, var, function, etc. as they are reserved words of the JavaScript language.

Give a value to a variable (assign a value to a variable)

A value can be assigned to a declared variable, or even directly in the variable declaration.
For this, we use the equal character, also called "the assignment operator". 

Example:

(notice at line 4 one way to introduce comments in your code: start a line with "//"!)

1. var myValue;
2. myValue = 78;
3.  
4. // With the ES2015 syntax. BTW, lines staring with // are comments!
5. let myNumber = 1.34;

At line 2, we are not saying that "myValue" and "78" are the same, we're saying "hey, I want
to store the value 78, and I'm putting it in a variable whose name is "myValue". It's like
giving an id to a location somewhere in the memory of the computer.

Using the id "myValue", we store 78 into a memory location identified by the name
"myValue": a variable, or if you prefer, a value that can vary over time if we assign a new
value to the variable "myValue" (for example by executing myValue = 5;).
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
You can also declare many variables at once by separating them with a comma. Always
end each instruction line with a semi colon.

Example:

1. var myNumber1, myNumber2 = 34, myNumber3;


2.  
3. // Or with the ES2015 syntax, you can also use "let"
4. let x = 1, y = 3, z = 12;

Try the devtool console - you can type code in there too!

Reminder: you can always open the devtool console using F12 on windows, or ctrl-shift i, or
cmd-alt-i on other computers.

If we copy and paste the variable declarations from the previous example, and type
myNumber2 in the devtool console, it will display 34 (while myNumber1 will have an
undefined value):

1. > var myNumber1, myNumber2 = 34, myNumber3;


2. undefined
3.  
4. > // Or with the ES6 syntax you can also use "let"
5. undefined
6.  
7. > let x=1, y=3, z=12;
8. undefined
9.  
10. > x;
11. 1
12.  
13. > z;
14. 12
15. > myNumber2;
16. 34
17.  
18. > myNumber1;
19. undefined

Below is an image that explains how you can try JavaScript code in the devtools console:
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}

If you try to use a variable that has never been declared, you get an error message:

Name conventions for variables

The JavaScript community has some conventions about naming variables:

 The camelCase notation is preferred: mySpaceShip,


sumOfAllGrades, etc.
 For a variable, the first letter is lowercase and each first letter of
each word is capitalized. Example: var myVariableName

Example:

1. var myModel;
2. // ES2015 syntax
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
3. let michelBuffaAge = 51;

Most JavaScript examples you will find are written in the camelCase format. For harmony in
the code source, it is a good idea to keep this convention. Sometimes, you will see the
snake_case naming convention, which separates each word of a variable with an underscore.

Here's an interesting article: CamelCase vs underscores: Scientific showdown 

Constants

Constants are variables that cannot be modified after a value has been set.

The naming convention is to use uppercase letters with underscores. 

Example: var TIME_LIMIT = 50;

With JavaScript 5, constants were declared as normal variables, using the var keyword, and
there were no verifications by the JavaScript interpreter forbidding you to modify them after
you assigned a value to them.

With ES2015/2016 it is recommended that you use the keyword const instead of var to
declare them. This means that an error will be raised if you try to change their value in the
future.

Example:

1. var TIME_LIMIT;
2.  
3. // ES2015 Syntax
4. const MAX_GRADE = 20;
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}

Summary

Here are a set of examples (using the let keyword, but they would also work with var):

1. let a;
2. let thisIsAVariable;
3. let and_this_too; // but does not respect the usual naming convention
4. let mix12three;
5. // invalid!
6. let 2three4five; // can't start with a digit!
7.  
8. let a = 1
9. let v1, v2, v3 = 'hello', v4 = 4, v5;
10.  
11. // Beware with lowercase / uppercase
12. let case_matters = 'lower';
13. let CASE_MATTERS = 'upper';

Knowledge check 1.5.1 (not graded)

0 points possible (ungraded)


What is valid JavaScript below? (four correct answers!)

var !x = 3;
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
var x, y=2, z=3;

let myCar = "Ferrari";

let _12 = 4;

var michel123Buffa = "Your JavaScript teacher";


unanswered
Some problems have options such as save, reset, hints, or show answer. These options follow
the Submit button.

5.2 Scope of JS variables


Live coding video: scope of JavaScript variables

(downloaded)

Skip to main content

Live coding video: scope of JavaScript variables

0:00 / 0:00

Press UP to enter the speed menu then use the UP and DOWN arrow keys to navigate the
different speeds, then press ENTER to change to the selected speed.

Click on this button to mute or unmute this video or press UP or DOWN buttons to increase
or decrease volume level.

Maximum Volume.

Video transcript

1. Start of transcript. Skip to the end.


2. Hi!
3. Let’s talk about "variable scopes".
4. The scope of a variable corresponds to the locations in your code
5. where you can use this variable.
6. When you define... when you declare a variable outside of any functions,
7. it’s usable anywhere in your code.
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
8. It’s considered as a "global variable": it belongs to the "global scope".
9. So, the x variable here, can be used inside a function.
10. The console.log inside f1… if I execute f1… will display the value “1” because
11. the variable here is "global".
12. If I’ve got another function… f2, that declares another variable y,
13. and if I try to display this value from outside of the function, then it does not work…
14. I’ve got an error: y is not defined.
15. So, you’ve got "local variables", and "global variables".
16. In the case of local variables, when a variable has the same name as a global variable,
17. then the most local one wins.
18. If I try to display inside F2 the value of x, it will be the closest variable
19. -the local one- that will be displayed.
20. If I execute f2, then it will display "x = 2", it’s the value of the local one that is
21. taken into account, not the value of the global one.
22. We call this "masking".
23. The same... if I pass a parameter to a function, and if this parameter has the same
name as
24. a global variable, then it acts as a local variable, and it’s the value of the local
25. parameter that is taken into account.
26. This x here, is not the global one: it’s the one I passed as a parameter
27. that has the value 10.
28. Ok. So now, there are some little variations when I use "let" instead of "var".
29. Ok, let’s see some examples.
30. So, with JavaScript 6, I can use "let" instead of "var".
31. The global scope does not change.
32. If I declare a global variable, it can be used anywhere.
33. But, if I declare a local variable, it’s no more local to the whole function in which
34. it is defined, but it’s local to the block of instructions that is defined by
35. an opening brace and a closing brace.
36. So, if I try to use this variable here, that is defined in the block, outside of the block
37. but inside of the function, the “a”…, the value of the variable “a” here,
38. will not be the value of the local variable here, because this one does not exist,
39. it’s not usable here. It will be the global variable "a" that will be used.
40. So this is why the printed value here, when I execute “f“ is "1" and not "4".
41. If the variable was named “b” and if I tried to display it, then…
42. I’ve got an error: "b is not defined".
43. Remember that if I used "var" in that case it works, because "var" will define a
variable
44. local to the whole function, not just to the block of instructions.
45. End of transcript. Skip to the start.

Downloads and transcripts

Video
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
Download video file

Transcripts

 Download SubRip (.srt) file


 Download Text (.txt) file

Scope of JavaScript variables

1)  JavaScript 5 / ES5 scopes, with the var keyword

JavaScript 5 / ES5 has the var keyword for declaring variables.

JavaScript 5 / ES5 has two scopes: 1) a global scope for declaring global variables, and 2)
a function scope for declaring variables that are local to a function.

Furthermore, like in most programming languages, inside a function, a local variable masks
a global variable that has the same name.

See examples below.

1.1) Global scope / global variable

Global variables are variables declared outside of functions. They can be used anywhere in
the code.

Here is an example:

var x = 1;

// global scope

function f1() {

console.log(x); // displays '1' in devtool console

f1();
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
1.2) Local scope / local variable (also called function scope)

Variables declared with the keyword var in a function, are said to be "local to the function".
They "mask" any global variable that may have the same name.

When a variable is declared in a function, we also call it simply "a local variable", as
opposed to "a global variable". In JavaScript 5 (and this is not common in programming
languages), local variables are local to the function. They can be used anywhere inside the
function.

Most programming languages have local variables that are limited to the block of instructions
between '{' and '}' that contains the variable declaration. We call these variables "block
variables". This is the case with variables declared with the let keyword  introduced by
JavaScript 6 / ES6. See examples at the end of this section.

Example of a local variable declared in a function, that is NOT local to the block, but to the
whole function:

JS:

var a = 1; // global variable

function f() {

if (true) {

// this is a block, defined by "{" and "}"

var a = 4; // this "a" is NOT local to the block

alert(a); // alerts '4', not the global value of '1'

// a variable declared with "var" in a

// function is local to the function!

// and can be used anywhere in the function


div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
// so here, the local a masks the global a!

Here is another example that shows the differences between global and local variables, and
highlights the "masking" of global variables by local variables when they share the same
name.

 JS

var x = 1; // global variable, could be "masked" by local variables

function f2(x) {
console.log(x); // displays the given argument
// not the global value of x (value = 1)
// the x parameter acts as a variable
// local to the function, that "masks"
// the global variable x
}

f2(3); // will display 3

// local scope again


function f3() {
var x = 4; // local variable, scope = the function
console.log(x); // displays '4'. The local variable x
// "masks" the global variable x
}

f3(); // will display '4'

1.3) Never declare a variable without the keyword var!

JavaScript is sometimes an overly permissive language. We can make stupid errors that turn
out to be very hard to detect. One such error occurs when we forgot to use the var keyword
while declaring a local variable.

In JavaScript 5 / ES5, a variable declared in a function without the var keyword, makes it a


global variable.
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}

BEST PRACTICE: in JavaScript 5 / ES5, always use the keyword var when
declaring a global or a local variable.

Better: use the keyword let if you target browsers that support JavaScript 6 or
above.

Here is an example that shows what happens when you forget to use var or let while
declaring a local variable:

 JS

// local scope again, but mistake! We forgot var


// when declaring the local variable x
// -> same as declaring a global function var x = 3;
function f3() {
x = 3; // mistake, we forgot "var"
// x is no more a local variable,
// x is now global!
var y = 5; // real local variable
console.log(x); // displays '3'.
}

function f4() {
console.log(x); // will display 3 even if there is no
// global declaration var x outside of
// functions. The error in the declaration of x
// in f3 has made x global
}

function f5() {
console.log(y); // error, no global variable y
}

f3(); // displays 3
f4(); // displays 3, x declared without var in f3
// is considered global, and usable in f4

f5(); // error, y is a variable local to the f3 function


div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}

2) Since 2015 and ES2015, there are new scopes, with the let keyword

Modern JavaScript has the let keyword for declaring variables, and the const


keyword for declaring constants.

Modern JavaScript has two scopes: 1) a global scope for declaring global variables, and 2)
a block scope for declaring variables between { and }. This is similar to what we find in
many other programming languages such as Java, C# etc.

Furthermore, like in most programming languages, inside a block, a local variable


masks other variables located in higher scopes (global or in another block that contains
the current block).

Example of a local variable declared with the let keyword. Its scope is the block:

var a = 1; // global variable

function f() {

if (true) {

// this is a block, defined by { and }

let a = 4; // this "a" IS LOCAL TO THE BLOCK

alert(a); // alerts '1', a is the global variable


div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
// a variable declared with "let" in a

// block is local to the block!

// and is not defined anywhere else

// The a defined in the if block is not

// visible here, so the a we have here

// is the "global" a!

3) Recommended way to declare variables: var or let?

Well, all modern browsers support the let and const keywords, however, you might find
lots of examples that still use the var keyword...

Anyway, we highly recommend to use let and const instead of var, for declaring
variables and constants!

Live coding video: JavaScript data types

(downloaded)

What kind of values can we assign to a variable?

Well, there are multiple possibilities:

1. What we call "primitive data types": for example a number, a string, etc. ex:

var x = 3; var name = "Buffa";


2. Objects (everything that is not a  "primitive data type" is an object):
var michel = {firstName:'Michel', lastName:'Buffa'};
 There is a set of "predefined objects" in JavaScript (arrays, functions,
etc). We will come back on these later in the course.
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
JavaScript has a small set of primitive data types

o number: 1,2,105,3.14 ...


o string: 'a', "one", 'two' , 'World Wide Web' ...
o boolean: true / false
o undefined: absent or unknown value
o null: special keyword, meaning no value or empty. The difference from
undefined is that when a variable is null, it is still defined.

These are the simplest forms of data we can use in programming.

Anything that is not listed above is an object (JavaScript objects are covered later in Module
3). 

You said JavaScript does not have types for variables?

No! I said that JavaScript is weakly typed; you do not declare the type of variable. In some
other languages (Java language syntax, for instance) instead of var x=2; or let
name="Buffa"; you would write int x=2; or String name = "Buffa";, with
the datatype explicit in the variable declaration.

Knowing the type of a JavaScript variable: the typeof operator

The next section of the course talks about "operators" but there is one that is better introduced
in this section: the typeof operator, that is useful for knowing the type of a variable
depending in its value (possible values: number, string, boolean, undefined,
object, or function)

We will use it in lots of examples in the next three sections.


div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}

This operator is not often use in JavaScript programs, but it's useful for us, for explaining the
data types.

Numbers
Skip to main content

Number values can be:

o Integer: 1, 4, 274929
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
Type 343 in the devtool console, and after you press the Enter key,  the  corresponding value
(343) will be displayed.

o Signed integer: -17
o Decimal: 3.46, -466.8770

Examples of integer and decimals:

1. > var n=1;


2. undefined
3.  
4. > typeof n;
5. "number"
6.  
7. > n=1234;
8. 1234
9.  
10. > typeof n;
11. "number"
12.  
13. > n=1.23;
14. 1.23
15.  
16. > typeof n;
17. "number"
18.  
19. > typeof 123;
20. "number"

o Scientific notation: 3.46e4, 5.3e+6, 5344000e-5

3.46e4 equals 3.46 x 10^4 equals 34600

Examples:

1. > 1e1;
2. 10
3.  
4. > 1e+1;
5. 10
6.  
7. > 2e+3;
8. 2000
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
9.  
10. > typeof 2e+3;
11. "number"
12.  
13. > 2e-3;
14. 0.002
15.  
16. > 123.456E-3;
17. 0.123456
18.  
19. > typeof 2e-3;
20. "number"

o Octal: 010

Be careful with this, don't start an integer with 0 (zero), JavaScript will understand it as
an octal value.

010 equals 8 which means 1 * 8^1 + 0 * 8^0

The number 0456 means 4 * 8^2 + 5 * 8^1 + 6 * 8^0

Question 1: What's the result, as an integer, of the operation: 24 - 024?

Explanation 1: 24 is an integer which equals 24 but 024 is an octal value which equals 20.

Question 2: Which value will be displayed in the devtool console if you type 098 followed
by the Enter key?

Explanation 2: 9 and 8 don't exist in base 8 (only 0 to 7), so the typed number will


be considered as an integer.

o Hexadecimal: 0xF3

0xFF equals 255, 0xF3 means 15 * 16^1 + 3 * 16^0 and the resulting value is 243

Examples of octal and hexadecimal data types:

1. > var n3 = 0377;


2. undefined
3.  
4. > typeof n3;
5. "number"
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
6.  
7. > n3;
8. 255
9.  
10. > var n4 = 0x00;
11. undefined
12.  
13. > typeof n4;
14. "number"
15.  
16. > n4;
17. 0
18.  
19. > var n5 = 0xFF;
20. undefined
21.  
22. > typeof n5;
23. "number"
24.  
25. > n5;
26. 255

o Special values:
 +Infinity
 -Infinity
 NaN (Not a Number)

The value Infinity (or +Infinity) represents all number values greater


than 1.79769313486231570e+308 and -Infinity represents values smaller than -
1.79769313486231570e+308.

Finally, Nan represents not-a-number values, for example if you try to divide 0 by 0 (type


0/0 in the devtool console).

1. > 0 / 0;
2. NaN
3.  
4. > 3 / 0;
5. Infinity

Examples:

Any operation with Infinity gives Infinity as a result:


div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
1. > Infinity;
2. Infinity
3.  
4. > typeof Infinity;
5. "number"
6.  
7. > 1e309;
8. Infinity
9.  
10. > 1e308;
11. 1e+308
12.  
13. > var a = 6 / 0;
14. undefined
15.  
16. > a;
17. Infinity
18.  
19. > var i = -Infinity;
20. undefined
21.  
22. > i;
23. -Infinity
24.  
25. > typeof i;
26. "number"

1. > Infinity - Infinity;


2. NaN
3.  
4. > -Infinity + Infinity;
5. NaN

1. > Infinity - 20;


2. Infinity
3.  
4. > -Infinity * 3;
5. -Infinity
6.  
7. > Infinity / 2;
8. Infinity
9.  
10. > Infinity - 9999999999999;
11. Infinity
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
Examples with NaN:

NaN is a special value and its type is "Number"!

1. > typeof NaN;


2. "number"
3.  
4. > var a = NaN;
5. undefined
6.  
7. > a;
8. NaN

1. > var a = 10 * "f";


2. undefined
3.  
4. > a;
5. NaN
6.  
7. > 1 + 2 + a;
8. NaN

[ADVANCED] Optional explanations about numbers

In JavaScript, numbers are represented with a double-precision 64-bit format (IEEE 754).
These 64 bits are used with this table:

Total bits Sign Exponent Significant

64 1 11 52

What does it mean?

First, each number is represented as a float. For example, 1 equals 1.0. But there are
approximation errors that are well-known in float calculations. One common example of
errors due to the approximation of floating point numbers is that 0.1 + 0.2 does not
equal 0.3. 

1. > 0.1 + 0.2;


2. 0.30000000000000004
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}

Second, an integer has 2^52 relevant bits, so the biggest integer is 2^53. There is one bit
that determines the sign of the number, so the smallest signed integer is -2^53.

Note: Some arithmetic functions use only numbers with a 32-bit format. Larger numbers will
be converted...

For more information about floating point numbers, follow this link at Wikipedia.

Knowledge check 1.5.4 (not graded)

0 points possible (ungraded)


What is the value of a after the execution of var a = 18 / 0;?

Infinity

undefined

NaN
unanswered
Some problems have options such as save, reset, hints, or show answer. These options follow
the Submit button.

Knowledge check 1.5.5 (not graded)

0 points possible (ungraded)


What is the value of a after the execution of var a = 0 / 0;?

undefined

NaN
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}

JS operators and expressions


Skip to main content

An expression is a small piece of code used to produce a value.

For example, the expression 3 + 5 produces the value 8, and the value 11 alone is also an
expression. Within an expression, we can find values, variables, operators, and expressions.
The first two have been already described above, so all that's left are operators.

In JavaScript, an operator can be unary or binary (plus one ternary operator). A unary


operator is applied to one expression. It can be prefixed or suffixed.

Unary operator example: 

1. typeof 'world';
A binary operator is applied to two different expressions, and is both prefixed and
suffixed.
Binary operator example:

1. var x = 45 / 32;
The division operator is binary.

Within an expression, we can also use parentheses to force the execution of the expression
inside. Parentheses can be used to indicate precedence.   

For example, this is an expression: (3 + 2). And the expression (3 + 2) * 4, which

equals 20, depends on the expression within the parentheses.

In JavaScript, expressions can evaluate to four types, which are: numbers, strings,
booleans, and objects. For example, an expression with the operator - will evaluate to
a number. But an expression with the operator + can evaluate to a number or a string
(for addition or concatenation).

1.5.6 Number operators


div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
Live coding video: number operators

(downloaded)

The following arithmetic operators are binary:

+, - , /, *, % (modulo)
Example: 7 % 5 equals 2, which is the remainder of the integer division of 7 by 5

Note: (7 / 5 = 5 * 1 + 2 ).

And there are also unary operators:


++, --, - (the opposite of a number)
++ and -- operators increment or decrement the value of a variable. They can be
both prefixed or suffixed, which have different effects:

 Suffixed ++ adds one to the value of the variable, then returns the old value.
 Prefixed ++ also adds one to the value, but returns the new value. Both of these
must be used with variables.

Examples typed in the devtool console of a browser

Example #1: simple operator use

1. > 1 + 2;
2. 3
3.  
4. > var a = 1;
5. undefined
6.  
7. > var b = 2;
8. undefined
9.  
10. > a + 1;
11. 2
12.  
13. > b + 2;
14. 4
15.  
16. > a + b;
17. 3
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
18.  
19. > var c = a + b;
20. undefined
21.  
22. > c;
23. 3

Example #2: more operators

1. > 1 + 2;
2. 3
3.  
4. > 99.99 - 11;
5. 88.99
6.  
7. > 2 * 3;
8. 6
9.  
10. > 6 / 4;
11. 1.5

Example #3: pre and post increments

1. > var m = 0;
2. undefined
3.  
4. > m;
5. 0
6.  
7. > // regular use of the + operator
8. m = m + 1;
9. 1
10.  
11. > m;
12. 1
13.  
14. > m = m + 1;
15. 2
16.  
17. > m;
18. 2
19.  
20. > // post increment
21. m++;
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
22. 2
23.  
24. > m;
25. 3
26. > console.log(m++); // will display 3 but after that m is incremented
27. 3
28.  
29. > m;
30. 4

Below is snapshot with explanations:

Strings (part 1)
Skip to main content

To declare or manipulate strings you must write them with single quotes ' or double quotes
" around them. Single quotes or double quotes are both accepted, and there is no difference
between them in JavaScript. However, the community prefers to use single quote for string -
this is not a convention, but a recommendation.

And finally, you cannot start a string with a single and end with a double quotes, or the
opposite.

1. > "Hello World";


2. "Hello World"
3.  
4. > "JavaScript Course";
5. "JavaScript Course"
6.  
7. > 'With simple quotes';
8. "With simple quotes"
9.  
10. > "Do not mix double and simple quotes'; // here we opened the string with double
and closed with simple quotes
11. VM24763:1 Uncaught SyntaxError: Invalid or unexpected token

Image from the devtool console, from the above example:


div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}

There are many reasons to use simple quotes when possible:

1. Double quotes are used in HTML


2. You must hold the Shift key to type "
3. Single quotes are easier to read and to type
4. To output HTML in JavaScript, single quotes are more useful
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}

Example #4: other versions of post and pre increments


div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
1. > var a = 123; var b = a++;
2. undefined
3.  
4. > b;
5. 123
6.  
7. > a;
8. 124
9.  
10. > var a = 123; var b = ++a;
11. undefined
12.  
13. > b;
14. 124
15.  
16. > a;
17. 124
18.  
19. > var a = 123; var b = a--;
20. undefined
21.  
22. > b;
23. 123
24.  
25. > a;
26. 122

Example #5: short variant that mixes assignment and execution of an operator

Binary operators can be used with a shorter syntax when we want to assign the resulting
value to a variable at the same time.

Code below (try it in the devtool console of your browser):

1. > var a = 10;
2. > a *= 5; // equivalent to a = a * 5;
3. > console.log(a);
4. > 50

Example #6: more with pre operators +=, -=, *=, /= 

There are good chances you will encounter such code:

1. > var a = 5;
div {
float: left;
}

#myFunction {
padding: 25px;
width: 250px;
height: 250px;
}
2. undefined
3.  
4. > a += 3 // equivalent to a = a + 3;
5. 8
6.  
7. > a -= 2; // equivalent to a = a - 2;
8. 6
9.  
10. > a *= 10; // equivalent to a = a * 10;
11. 60
12.  
13. > a /= 5; // equivalent to a = a / 5;
14. 12
15.  
16. > a %= 2; // equivalent to a = a % 2;
17. 0
18.  
19. > // this is normal, as a is even

You might also like