You are on page 1of 110

Indice

0. Welcome To The Course!...................................................................................................8


Where Do We Begin? ........................................................................................................8
Language environments.................................................................................................8
Course Overview:........................................................................................................10
1. The Language Itself..........................................................................................................11
1.1 Getting Started............................................................................................................ 11
1.2 Functions....................................................................................................................15
1.3 Objects.......................................................................................................................20
Properties ....................................................................................................................21
Methods....................................................................................................................... 22
Another quick note about the curly brackets............................................................23
Nesting objects........................................................................................................23
Practical part of this lesson..........................................................................................24
1.4 Arrays......................................................................................................................... 25
Adding a new item to our arrays..................................................................................27
Removing an item from an array..................................................................................28
How to access the value of a particular item in an array..............................................29
Why arrays are so important........................................................................................29
1.5 Making Decisions.......................................................................................................30
If.................................................................................................................................. 30
Operators.....................................................................................................................32
Without a comparison operator ..................................................................................32
While...........................................................................................................................32
What's going on? How is this working? .................................................................34
1.6 Higher-Order Functions..............................................................................................35
Lesson overview..........................................................................................................35
1. A function that accepts another function as an argument.........................................35
2. A function that returns a function as a result............................................................36
3. Useful higher-order functions, that are part of the language itself...........................38
1.7 Returning vs Mutating................................................................................................40
array.map()................................................................................................................... 42
array.filter().................................................................................................................. 44
1.8 Scope & Context........................................................................................................47
Scope...........................................................................................................................48
Example...................................................................................................................49
Var and let................................................................................................................52
Context......................................................................................................................... 53
Why we would use the “this” keyword...................................................................56
1.9 Miscellaneous Info ....................................................................................................58
Anonymous functions..................................................................................................58
Arrow functions...........................................................................................................59
function hoisting..........................................................................................................61

1
template literals............................................................................................................61
semicolons................................................................................................................... 62
1.10 Building To-Do App.................................................................................................63
2. Server Basics.................................................................................................................... 68
2.1 Why Do We Need a Server?.......................................................................................69
11:23................................................................................................................................ 69
2.2 Node.js Intro...............................................................................................................72
10:21................................................................................................................................ 72
2.3 Text Editor Software..................................................................................................74
10:48................................................................................................................................ 74
2.4 Our First Basic Server................................................................................................76
19:53................................................................................................................................ 76
2.5 Express Intro (Part 1).................................................................................................80
10:13................................................................................................................................ 80
2.6 Express Intro (Part 2).................................................................................................82
19:48................................................................................................................................ 82
2.7 What's Next? (Big Picture).........................................................................................86
14:03................................................................................................................................ 86
3. Database Basics................................................................................................................ 90

03:34:24................................................................................................................................ 90
First Taste of a Database...................................................................................................90
10:57................................................................................................................................ 90
Note for Advanced Students.............................................................................................90
00:51................................................................................................................................ 90
CRUD: Actually Working With A Database.....................................................................90
14:04................................................................................................................................ 90
Initial Setup for App #1....................................................................................................90
18:02................................................................................................................................ 90
Save Time: Automatic Node App Restarts.......................................................................90
09:12................................................................................................................................ 90
Quick Note About MongoDB Warning in Command-Line..............................................90
00:30................................................................................................................................ 90
Connecting Node App to Database...................................................................................90
19:58................................................................................................................................ 90
Installing NPM Packages Without Stopping Server/App.................................................90
00:27................................................................................................................................ 90
Reading Data from a Database.........................................................................................90
17:24................................................................................................................................ 90
Updating a Database Item (Part 1)...................................................................................91
19:58................................................................................................................................ 91
Updating a Database Item (Part 2)...................................................................................91
19:55................................................................................................................................ 91
Deleting a Database Item.................................................................................................91
12:55................................................................................................................................ 92

2
Create New Item Without Page Reload............................................................................92
19:57................................................................................................................................ 92
Client-Side Rendering......................................................................................................92
10:17................................................................................................................................ 92
What About Security?......................................................................................................92
19:54................................................................................................................................ 92
Quick Note For Mac Users...............................................................................................92
00:27................................................................................................................................ 92
Pushing Our App Onto The Internet.................................................................................92
19:19................................................................................................................................ 92
Pushing Future Changes To Your Heroku App.................................................................92
00:17................................................................................................................................ 92
–....................................................................................................................................... 92
4. Starting Our Complex App (App #2)................................................................................92

05:16:19................................................................................................................................ 93
What's Next?.................................................................................................................... 93
08:03................................................................................................................................ 93
Let's Begin App #2...........................................................................................................93
18:39................................................................................................................................ 93
Important Note About Package Versions To Save You Frustration...................................93
01:32................................................................................................................................ 93
What Is A Router?............................................................................................................93
14:11................................................................................................................................ 93
What Is A Controller?.......................................................................................................93
17:52................................................................................................................................ 93
Security Note.................................................................................................................... 93
00:24................................................................................................................................ 93
What Is A Model?............................................................................................................. 93
19:58................................................................................................................................ 93
Adding Validation To Our Model.....................................................................................93
19:58................................................................................................................................ 93
Quick Misc. Clean Up......................................................................................................93
08:01................................................................................................................................ 93
Quick Note About Connecting to Database......................................................................93
00:25................................................................................................................................ 94
Connecting To Database In a Reusable Fashion...............................................................94
17:12................................................................................................................................ 94
Best Practice Time Out: Environment Variables..............................................................94
10:10................................................................................................................................ 94
Quick Note.......................................................................................................................94
00:09................................................................................................................................ 94
Letting Users Log In........................................................................................................94
18:37................................................................................................................................ 94
What is a Promise? (Part 1)..............................................................................................94

3
19:32................................................................................................................................ 94
What is a Promise? (Part 2)..............................................................................................94
14:24................................................................................................................................ 94
Running Multiple Promises Efficiently When Order Doesn't Matter...............................94
00:30................................................................................................................................ 94
Hashing User Passwords..................................................................................................94
13:53................................................................................................................................ 94
How Can We "Identify" or "Trust" a Request?.................................................................94
19:17................................................................................................................................ 94
For Those Who Are In a Hurry (Security Note)...............................................................94
00:42................................................................................................................................ 95
Understanding Sessions....................................................................................................95
19:07................................................................................................................................ 95
Letting Users Logout........................................................................................................95
11:57................................................................................................................................ 95
Adding Flash Messages....................................................................................................95
16:28................................................................................................................................ 95
User Registration Improvements (Part 1).........................................................................95
17:41................................................................................................................................ 95
User Registration Improvements (Part 2).........................................................................95
12:01................................................................................................................................ 95
Adding User Profile Photos..............................................................................................95
15:36................................................................................................................................ 95
–....................................................................................................................................... 95
5. User Created Posts............................................................................................................ 95

04:03:44................................................................................................................................ 95
Letting Users Create Posts (Part 1)...................................................................................95
17:31................................................................................................................................ 95
Letting Users Create Posts (Part 2)...................................................................................95
12:17................................................................................................................................ 95
Post Model (Part 1)..........................................................................................................96
19:59................................................................................................................................ 96
Post Model (Part 2)..........................................................................................................96
07:16................................................................................................................................ 96
Viewing a Post (Part 1).....................................................................................................96
07:45................................................................................................................................ 96
Viewing a Post (Part 2).....................................................................................................96
19:10................................................................................................................................ 96
Performing a Lookup in MongoDB (Part 1).....................................................................96
16:50................................................................................................................................ 96
Performing a Lookup in MongoDB (Part 2).....................................................................96
08:14................................................................................................................................ 96
User Profile Screen..........................................................................................................96
18:10................................................................................................................................ 96

4
View Posts by Author.......................................................................................................96
19:47................................................................................................................................ 96
Is the Current Visitor the Owner of the Post?...................................................................96
12:53................................................................................................................................ 96
The "Edit" Screen for a Post.............................................................................................96
08:50................................................................................................................................ 96
Updating Posts in Database (Part 1).................................................................................97
10:51................................................................................................................................ 97
Updating Posts in Database (Part 2).................................................................................97
18:57................................................................................................................................ 97
Miscellaneous Improvements...........................................................................................97
14:55................................................................................................................................ 97
Markdown: Safe User Generated HTML.........................................................................97
15:44................................................................................................................................ 97
Make This Quick Edit To Your Code...............................................................................97
00:37................................................................................................................................ 97
Let Users Delete a Post....................................................................................................97
13:58................................................................................................................................ 97
–....................................................................................................................................... 97
5. Live Search Feature..........................................................................................................97

01:41:08................................................................................................................................ 97
Staying Organized: Front-End JavaScript........................................................................97
19:57................................................................................................................................ 97
Showing and Hiding Search Overlay...............................................................................97
16:54................................................................................................................................ 97
Responding to Key Press Events......................................................................................97
19:12................................................................................................................................ 98
Back-End Aspect of Search..............................................................................................98
15:40................................................................................................................................ 98
Generating HTML for Search Results (Part 1).................................................................98
10:05................................................................................................................................ 98
Generating HTML for Search Results (Part 2).................................................................98
10:47................................................................................................................................ 98
Fixing The Month for Post Dates in Search Results.........................................................98
00:21................................................................................................................................ 98
Sanitizing User Generated HTML on the Front-End........................................................98
08:12................................................................................................................................ 98
–....................................................................................................................................... 98
6. Letting Users Follow Each Other.....................................................................................98

02:08:16................................................................................................................................ 98
Letting Users Follow Each Other.....................................................................................98
12:25................................................................................................................................ 98
Saving a "Follow" Action Into Our Database...................................................................98

5
12:25................................................................................................................................ 98
Stop Following a User (Part 1).........................................................................................98
13:48................................................................................................................................ 98
Stop Following a User (Part 2).........................................................................................99
13:16................................................................................................................................ 99
Profile Followers Screen (Part 1).....................................................................................99
10:26................................................................................................................................ 99
Profile Followers Screen (Part 2).....................................................................................99
15:25................................................................................................................................ 99
Following Screen (Part 1).................................................................................................99
13:29................................................................................................................................ 99
Following Screen (Part 2).................................................................................................99
17:30................................................................................................................................ 99
Homepage Feed (Posts From Those You Follow)............................................................99
19:32................................................................................................................................ 99
–....................................................................................................................................... 99
7. Live Chat (Socket.IO).......................................................................................................99

01:23:18................................................................................................................................ 99
Beginning Chat Feature....................................................................................................99
19:37................................................................................................................................ 99
Socket.IO (Part 1)............................................................................................................. 99
10:43................................................................................................................................ 99
Socket.IO (Part 2)............................................................................................................. 99
11:42............................................................................................................................... 100
Finishing Chat (Part 1)...................................................................................................100
13:39.............................................................................................................................. 100
Finishing Chat (Part 2)...................................................................................................100
19:56.............................................................................................................................. 100
Quick Misc. Feature: Dynamic Title Tag........................................................................100
07:41.............................................................................................................................. 100
–..................................................................................................................................... 100
8. Live Validation for Registration Form............................................................................100

01:16:09.............................................................................................................................. 100
Live Form Validation (Part 1).........................................................................................100
18:41.............................................................................................................................. 100
Live Form Validation (Part 2).........................................................................................100
18:22.............................................................................................................................. 100
Live Form Validation (Part 3).........................................................................................100
19:58.............................................................................................................................. 100
Live Form Validation (Part 4).........................................................................................100
19:08.............................................................................................................................. 100
9. What is CSRF? (Security)...............................................................................................101

6
33:02................................................................................................................................... 101
Preventing Cross-Site Request Forgery (CSRF).............................................................101
19:58.............................................................................................................................. 101
Adjusting Our App To Use CSRF Token........................................................................101
13:04.............................................................................................................................. 101
–.......................................................................................................................................... 101

10. Let's Create an API.......................................................................................................101

01:04:15.............................................................................................................................. 101
Setting Up The Skeleton for an API...............................................................................101
19:41.............................................................................................................................. 101
JSON Web Tokens (Part 1).............................................................................................101
11:37............................................................................................................................... 101
JSON Web Tokens (Part 2).............................................................................................101
13:47.............................................................................................................................. 101
Finishing API and Understanding CORS.......................................................................101
19:10.............................................................................................................................. 101
–..................................................................................................................................... 101
11. Deploying Complex App to Heroku.............................................................................102

29:40................................................................................................................................... 102
Pushing Our Complex App Up Onto The Web...............................................................102
14:15.............................................................................................................................. 102
Sending Email From Our App........................................................................................102
15:25.............................................................................................................................. 102
–..................................................................................................................................... 102
12. Where Do We Go From Here?......................................................................................102

19:53................................................................................................................................... 102
Next Steps & Career Advice..........................................................................................102
19:53.............................................................................................................................. 102

7
0. Welcome To The Course!
Where Do We Begin?
hello everyone and welcome to the ten days of JavaScript team here we are in day number
zero and the question is where do we begin if we want to learn JavaScript. well in my mind
the answer is simple we begin with the language itself, but what do I mean by that?

the human mind is made for language. the same way that a cheetah is born to run you and I
are born to use language, it's our super power and it comes naturally. parents don't have to
quote teach their children how to speak, you simply talk in front of a child and they
naturally absorb language. the human mind is able to put all the puzzle pieces together
without breaking a sweat. so let's use this strength to our advantage, because I've found that
when students view JavaScript big-picture as a language just like English, or Spanish, or
Mandarin, the learning process becomes so much easier. but on the other hand if instead you
view JavaScript as just a big long list of made-up words that you need to memorize, well in
that case, learning JavaScript feels like trying to grab a fistful of sand, very difficult to
grasp.

so right now let me give you an example of what I mean when I say that we should begin
with the language itself. let's take English as an example. so here's a sentence:

the asdf cat quickly ate the Zzyzx.

now two of the words in the sentence are made-up nonsense, but because we understand the
structure of the English language, it doesn't really matter that we don't know what these
words mean. we can still basically understand the sentence as a whole.

so we want this same level of comfort with the JavaScript language, because once you
understand the structure of a language, it gives you contextual clues to help you understand
what's going on. even if you don't understand each word individually, we still know that
there's a cat and it's quickly eating something.

at this point you might be wondering what does this have to do with JavaScript and
computer programming.

Language environments
well let me give you a metaphor. so again let's take the English language, and we know that
we speak English in many different environments. just for two quick examples let's take
your family's home and your workplace. so you speak English in both environments, but
each environment also has its own made-up words, or jargon, or slang, that are not part of
the language itself.

8
so maybe in your family's home you have a made-up nonsense word to describe the way
your dog eats its food, who knows, every home and family is different, but the point is that
you probably have unique little phrases or words that if you used with a stranger. they would
just look at you weird and have no idea what you mean.

And it's the same thing with your workplace, no matter which industry you work in it
probably has its own unique set of jargon or slang or made-up words. and people outside of
your workplace environment, probably will not understand these words or phrases.

So there's this distinction between language and environment, and it's the same thing with
JavaScript. JavaScript is also spoken in different environments. Some of the most common
are the web browser, node.js, MongoDB, and countless others, but these are just three of the
most popular. (don't worry, I do not expect you to know what node is, and I do not expect
you to know what MongoDB is, we will learn about those things later on in the course) for
now all you need to know is that there are multiple environments, in which JavaScript can
be spoken. And just like with the English environments, like our family's home and
workplace, each environment has its own unique made-up words, or jargon, or slang.

so for example here's a line of JavaScript code that you would use in the web browser
environment: (don't worry, I do not expect you to understand this code at all, I'm only
showing it right now to demonstrate the difference between language and environment)
document.addEventListener(“click”, () => alert(“Thanks for clicking”));
this code tells the web browser to show a pop up message that reads “thanks for clicking”
anytime the visitor clicks anywhere on the page.

now here's the important part: even though this is a line of JavaScript code, none of these
words are part of the JavaScript language, so for example the word document, or the
squished together phrase of addEventListener, or the word click, or alert, yes these are
words in the English language, but they are not words in the JavaScript language. These
words only have meaning within the context of the web browser environment. if you used
any of these words in a different JavaScript environment it would be like using one of your
made-up family words with a stranger.

okay but the question becomes: if these words are not in the JavaScript language then what
makes this line of code JavaScript?

well it's the periods, the parentheses, the quotes, the commas, and the other symbols. these
are the structure, or skeleton, or syntax of the language. they are the glue that holds the
sentence together, and that is what we want to learn first. that's exactly what we're going to
focus on in this first chapter. by the end of this chapter when you see a line of JavaScript
code, you're going to have the same feeling as when I showed you this sentence in English.
you might not understand every single word individually, but because you understand that
there are adjectives, and nouns, and verbs, your mind is still able to get a general idea of
what's going on.

okay so we're going to get that same level of comfort and familiarity and even predictability
with JavaScript. getting to that point has got to be our first goal. it's the first step to

9
genuinely understanding a programming language.

now if you've ever tried to learn JavaScript in the past, but got discouraged because it
seemed too difficult or confusing, it's probably because the teacher took the opposite
approach.

far too many teachers make the mistake of...


• having you begin by memorizing environmental jargon, these made-up words that
are unique to each environment. they start out by having you memorize these words
and abilities,
• before you even understand the glue that holds everything together, the language
itself, the syntax, the structure.
• they underestimate you your intellect and your attention span
• they think that if you don't build the cheesy “click me, I'm a button” app in the first
10 minutes of the course that you'll get bored and give up.
• they think that you don't have the mental capacity for abstract ideas. and they think
that you need to jump into concrete examples right away or you'll get confused.

okay but I know that that's not true. the fact that you mastered the English language is proof
that it's not true. your mind was made for language and we're going to leverage that, on our
way to becoming a full-stack JavaScript developer.

Course Overview:
so here's what we're going to do in this course:
1 In our first chapter we're going to focus on the language itself (astract). after that, once
we've built up a bit of comfort, we're then going to learn the three most popular and
lucrative JavaScript environments, which as of today are:
2 the web browser (concrete),
3 node.js (concrete),
4 and Mongo DB (concrete).

again don't worry, at this point I do not expect you to know what node, or Mongo DB are.
we will learn about that later in the course, for now all you need to know is that there are
multiple JavaScript environments, and each one has its own unique set of jargon, or slang,
or lingo, or new vocabulary, and using these words is how we perform the unique abilities
of that environment.

here's a quick example for each of these big three environments:

hey web browser, when someone clicks on this button, do this in response.

hey node, when someone visits this URL please show them this content.

10
hey MongoDB, please save this data into a database, so we can access it later on in the
future.

Obviously you can't just use plain English like this, but the idea is that each environment
has its unique jargon, or lingo, or new vocabulary, new made-up words, that you use in your
code to perform these unique abilities.

And as fun as that is, and as tempting as it might be to jump right into that, we need to begin
first with the language itself, the symbols, the syntax, the structure, the anatomy of a
JavaScript sentence. Once we're comfortable with that, then we can jump into the concrete
uses for JavaScript in the real world in these environments.

And that my friends is how we become a full-stack JavaScript developer, we combine the
abstract with the concrete, we learn the language and then we understand how to use it to
build all layers of an application. This holistic skillset is incredibly in-demand it can be very
lucrative, but more importantly it can be very fun and rewarding. so I don't know about you,
but I am very excited to get started on this JavaScript journey with you.

in our very next lesson we're going to begin coding experimenting and moving right along,
so let's get things rolling, let's start building some momentum and I will see you in the next
lesson.

1. The Language Itself


1.1 Getting Started
In this first chapter we are going to give you a rock solid foundation that you can build a
career on top of. and no prior experience or knowledge is required. so even if you have zero
experience with computer programming in general, or maybe if you've never even heard of
JavaScript, this is the perfect place to get started.

okay so right now in video number one day number one we're gonna get started in about 30
seconds from now. but first I just want to say that javascript is much bigger than the web
browser. in the modern era javascript can be used for just about anything.

having said that we are indeed going to begin in the web browser because it's super
accessible, it's something that every computer already has, so this way you don't need to go
download and install anything fancy or extra, your computer already has a web browser on
it.

so right here right now we are going to get started get your hands dirty and have you write
your first bit of JavaScript code. so right now I want you to follow along with me, and I
want you to open up a new tab, or a new window. you to right-click somewhere on the web
page and in the menu that pops up, choose the inspect option .

I want you to look for something called the console, once you've found console go ahead
and click on it.

11
once you have successfully opened the console you should see some sort of symbol, or a
blinking cursor. here is where we can experiment with JavaScript code. this is where we can
type and tell the web browser what to do, so for example on my keyboard I say:
2 + 2 and press enter.
we see 4
let's try something else so maybe:
5 * 5 press ENTER
25
now at this point you might be thinking to yourself, that this is not impressive at all, because
you've seen adition and multiplication before. right we've all used the calculator, what does
this have to do with JavaScript and learning how to program? well believe it or not these
lines of code are lines of JavaScript, and we just used JavaScript code to make the computer
solve these, or evaluate these for us.

ok but as you might have guessed computers can do much more than just basic aritmetic.
one of the most useful things that computers can do is store values in memory. let me show
you what I mean: I want you to type this out with me in your console:
let myFavoriteNumber = 7
and then press Enter, and we just stored this value in memory. so check this out, let's try
something new, let's say:
10 + myFavoriteNumber
we press Enter or return , we see:
17
because we set this myFavoriteNumber to equal or to have a value of 7 so 10 plus 7 is 17.

And we can store more than just numbers. so for example we could try storing our name in
memory. type this out with me:
let myName = “Brad”
you can use a single quote ( ' ' ), or a double quote ( “ “ ), it's up to you. we're using quotes
this time because in JavaScript, if you're just dealing with a number that doesn't need
quotes, because a number is a special type of data, but if you want a string of text, right like
a name, or word, a sentence, or even a paragraph, in JavaScript we call that a string of text
or just a string, and we always want to wrap that in quotes.

okay we just stored that in memory so now if you ever want to use it again you can just
type in:
myName
press Enter, and it's going to give you your name:
“Brad”
or for a more useful example we open up a string of text and say:
'Hello my name is ' + myName + '.'
press ENTER and the computer adds all of this up for us and generates:

12
“Hello my name is Brad.”
so you can see that addition is not only four numbers, we can also add strings of text
together.

if you're still a little bit confused on the difference between a number and a string let me
show you this quick example. so when we say:
2+2
we get: 4.

however if we say:
'2'+'2'
here we see: “22”

which doesn't make any sense mathematically. this is because when you wrap something in
quotes javascript is not going to treat it as a number, it's going to treat it as a string of text
and interpret it quite literally, so which is going to squish these together “22”. without the
quotes javascript knows to interpret these as actual numbers.

now if this distinction between numbers and strings of text is still not clear, don't worry
about it, this is a topic that we will address again later on in future lessons.

now finally let's get to the truly interesting part of this lesson.

so we've seen that we can store values in memory right so we stored myFavoriteNumber,
and we stored myName, and these are labels that I just made up. There's nothing special
about this phrases, as long as your label name starts with a letter and doesn't contain any
spaces in it you can basically create any label name that you want. The idea is we've seen
that we can store values in memory with our own custom labels.

But the really interesting part is that the environment also stores a ton of its own values in
memory. now when I say environment, what do I mean? well in this case the web browser is
our environment. so for example the web browser is storing the title of this web page, in
memory in my case that's Google.

now check this out, we can actually use JavaScript code to manipulate this title that we see
right here.

so just like we made up labels like myFavoriteNumber, the web browser environment has
created a label or object named document. now I just used a new word: object. (at this
point we have no idea what an object is, don't worry, we are going to learn about objects in
lesson number three) but for now all you need to know is that we can look inside an object
with a period and then a property ( the document object contains a property named title.).
so back in our console, if we say:
document.title
and then press ENTER, we see: “Google”

13
now here is where things finally get interesting and we start to see the big picture. We can
update, or manipulate the value of this property, and the web browser will use that new
value. So if we want it to change this, instead of saying Google to saying something
random, we could just say:
document.title = “a string of text”
press ENTER, and you can see up in my tab for the web browser, “a string of text” instead
of Google.

now let's try one more example task before we bring this lesson to a close let's try to use
javascript code to change the background color of Google from white to maybe a light blue.

so back in the console check this out we can say:


document.body.style.backgroundColor = 'lightblue'
remember that the dot or period is how you look inside an object for other properties we
will learn more about objects in future lessons but for now you could almost think of this as
a Russian stacking doll. so document contains a property named body, body contains a
property name style, and style contains a property named backgroundColor (and make sure
you type the C in color here as a capital an uppercase C, because this is case sensitive)

and as soon as I press ENTER, you can see the web page updated.

cool now that's gonna bring the hands-on portion of this lesson to a close, but I do have a
quick review for you.

so the takeaway for this lesson is the idea of values, storing values in memory, accessing
those values and then even assigning or updating to new different values, because at its core
that's really all programming is, working with values. Before we jump into lesson number 2,
I do want to stress the fact that these words (like document and body and style and
backgroundColor) these words are not part of the JavaScript language itself. so just like
earlier when you and I chose words like myFavoriteNumber and myName, just like we
did that, the web browser environment chose the words document and body, style and
backgroundColor.

these words have no meaning outside the context of the web browser environment. Because,
remember the web browser is just one of many different JavaScript environments (later on
in the course we will learn about the node environment which can be used as a server, and
also the MongoDB environment, which is used for storing and retrieving data in a
database)

so long story short, at this point in the course I do not want you to worry about trying to
memorize these words. This is just environmental jargon that the web browser uses. We can
start to remember some of these key property names later on in the course. But for now I
want you to focus on the equal sign, and the quotes, and the periods, and the plus symbols
that we used earlier. Because that is the skeleton in the core of the JavaScript language
itself. It's the aspect that never changes regardless of environment.

anyways congratulations on writing your first bit of JavaScript in this lesson, you got your

14
hands dirty with code which is already more than most people can say.

I've got a quick vocabulary note at the end here. Throughout this lesson you heard me refer
to things like myFavoriteNumber and myName as labels. label is not the technical term, I
just made that up to try and make the lesson more understandable or less intimidating, the
technical term is a variable. In the example we stored the value of 7 within a variable
named myFavoriteNumber, so we would refer to this as the identifier for the variable.

All right now looking ahead to our very next lesson, we are going to learn about one of the
most important ideas in all of programming and that is functions.

1.2 Functions
let's first talk about where we are going to type our code in this lesson. So in our previous
lesson we learned how to open up the web browsers console, but in the real world you're
going to want to write multiple lines of code at once. we want to be able to write out
multiple lines of JavaScript code, and then have the computer run everything that we just
typed.

now the easiest way to get started practicing this is actually not the console but instead a
website named codepen.io.

and right now I want you to open codepen in a new tab, so you can follow along. In my
opinion codepen is the easiest way to get started actually writing code, it's free to use, and if
you do not want to, you don't even have to create or sign up for an account. You can literally
just come to this website and click the Create button (that should be somewhere towards the
top) right and then from this menu that appears choose the new pen option so create new
pen okay

so what's going on? what is this screen? well each pen that we create is like an empty
canvas, or a playground, or play pen, or an experiment where we can code. so we see that
there are three columns, the first is HTML, and then CSS, and then js or JavaScript. now
this is a course that is focused on JavaScript, so we are not going to worry too much about
these first two columns, but the big picture idea is that these are the three languages that
web pages are created with, and how codepen works is that as you type in a column, so in
the HTML column if I say:

hello there!

as soon as I stop typing for a second, a preview is shown to me down here of what my code
creates. Perfect, except this is not a course on HTML, we want to learn about JavaScript. so
just to make it really easy to focus on javascript, for right now why don't we hide the HTML
and CSS columns. So to do that all I did was drag on the border right this vertical line right
between CSS and JavaScript, hover over that and then click and drag to the left. so that way
the JavaScript column takes up most of our screen. Because that's the language that we want
to practice.

So we now have a perfect environment to start practicing, because in this JavaScript column

15
we can now type out multiple lines and keep pressing enter, and each time we type a bit of
new code the computer is going to execute everything that we wrote all at once together,
just like an actual real-world computer program.

Let's get back to the actual goal of this particular lesson, the topic of functions. What in the
world is a function?

I like to think of functions as action words. So if we were comparing JavaScript to a


language like English or Spanish a function would be a verb. So for example if our pet dog
was a computer that spoke JavaScript we could say:
run()
jump()
sit()
so you simply type out the name of the action, or the name of the function and then you
include a pair of parenthesis.

however our web browser can't run, jump or sit, but it can do web browserish things. So for
example, we can create an annoying pop-up by calling the browser's alert function:
alert()
and we can see this pop-up appears. So this is how you can alert the visitor of the site with a
message. You can include a custom message, and within the parentheses for this alert we
can include quotes and then say:
alert(“Hey”)
and we can see in the new pop-up there is our custom message.

So the idea is that within the parentheses you can pass along a bit of data to the function,
and it's up to the function as to how it uses that data. so back to the dog example, if our dog
spoke JavaScript we could say:
jump (“high”)
jump (“low”)
So to review, you can call a function simply by including the word and then parentheses,
and then inside the parentheses we can pass along a bit of data. The technical name for a
piece of data that we pass along, is an argument. So all together we are calling or executing
the browsers alert function, and we are passing it an argument of “hey”.

So the browser has these different action words, or functions, like alert, that we can call, but
we are not limited to only those functions, because just like you can teach a dog a new trick,
we can also teach our JavaScript environment new tricks by creating our own brand-new
functions.

so for example let's type out:


greet()
The web browser does not know what this means. The browser does not have a function
named greet, so when I say greet and then parenthesis, this would be like telling a dog to
bake a cake, it's not gonna know what you mean and it's just gonna look at you funny.

16
However as a programmer we can create our own brand new function named greet, and we
simply explain what that action or function should do, and then it will be added to the
browser's vocabulary, and we can use or call it just like we would alert or any of the built-in
functions.

So, how do we create a function?

we've learned how to call, or execute, or run a function, this is how you issue a command,
you simply type the name of the function and then parenthesis, but how do you actually
create the recipe, or the instructions, or the logic for the function?

We begin by typing the word function, and then a space, and then we get to make up
whatever name we want for our new function, in this case I'm going to name it greet, then
we include a pair of parentheses, and then after the parentheses we include a pair of curly
brackets. And in between the two curly brackets I like to push Enter, and drop down to a
new line, just for visual clarity. In between the curly brackets, this is what is referred to as
the body of the function, and this is where we explain what the function should actually do.

So just as a quick test let's set things up so that when you call or run the greet function an
alert pop-up should appear that says “Hello my name is Brad.”
function greet(){
alert("Hello, my name is Brad.")
}
All we've done here is describe the function, or define the function. So this is the recipe for
our new greet action. And now if we want to tell the browser to actually perform the greet
function, maybe down here we could just say:
greet()
That's how you call a function, and there we can see the pop-up appears: “Hello, my name is
Brad.”

and we could call it again greet() a second time, it should appear twice.

So we just taught the browser a new trick, a new action, or we should say a new function.

Let's improve our function, because it would be nice if it was flexible. Remember when I
used the example that a dog can jump but you could also tell it to jump high or to jump low,
and we learned that the data you pass within the parentheses is referred to as an argument,
and it's up to the function to perhaps use that data in some way.

Well, wouldn't it be cool if our greet function was flexible and when you called it you could
pass in a name instead of hard-coding the name in the function.

so for example wouldn't it be neat if we could say greet and pass it a value of “John” and
then it would say “hello my name is John” and then you could call it again and say greet
with a value of “Jane”, and then it would say “hello my name is Jane”.

So back to the task at hand how can we make this function flexible?

17
function greet(theName){
alert("Hello, my name is " + theName +".")
}
greet("John")
Well, within these parentheses let's type theName. So by including this here we have
created a parameter named theName, and we can use this parameter within the body of the
function.

So the idea is within the parentheses for our function when we call it, we include quotes and
a name:
greet(“John”)
this data that we're passing along “John” we want to be able to access that within our
function, within the body of our function, so by including theName here as a parameter, is
going to equal the value of whatever gets passed in, so in this case it would be “John”. So
now within the body of function we can use that.

Okay so to review: greet(“John”). we are calling our greet function, we are passing it an
arguments of “John”, and then within our function definition we've included a matching
parameter, named theName, that's going to temporarily store that value, and then we can
use it however we want.

now before we move on I want to show you that you can pass along multiple arguments
when you call a function. Let's assume that we want to change our greet function to now
include the person's favorite color. If we're including two arguments when we call the
function we want to be sure that we include two parameters up in the function definition.
function greet(theName, favColor){
alert("Hello, my name is " + theName + " and my favorite color is " +
favColor + ".")
}
greet("John", "red")

perfect now practice makes perfect so before we bring this lesson to a close I want to write
one more function with you. Let's create a function named tripleMe so that when you pass it
a number it triples that number.

First we create the function definition or the recipe for the function so let's say: function
space

and then the name: tripleMe , and then parenthesis ()

and then after the parenthesis, curly brackets {}


function tripeMe(){}
Now within the parentheses let's include X as a parameter, and now we can use that within
the body of the function.

I do want to let you know that within the body of our function we do not need to call a

18
browser function like alert, instead actually a function, in its purest form, simply return a
value. So let's say return and then what do we want to return. we just say: 3 * X
function tripleMe(x){
return 3 * x
}
Then let's test this function out. So down here let's create a variable that stores a number:
let myTriplicatedNumber = tripleMe(12)
we're calling or executing the function and let's pass it a value of 12.

finally let's just alert out the value of myTriplicatedNumber just so we can see it:
alert(myTriplicatedNumber)
perfect and there we see 36. right if you triple 12 you get 36.

I know I moved a lot faster for this second example of triple meet but I just wanted to give
you something to experiment with, and if you need to re-watch this part a couple of times
that's okay if everything in this lesson was not crystal clear and you're still a bit confused
that's okay.

All you really need to have remembered from this lesson is that there are functions:
• you can create a function by saying function nombre, this creates the recipe, or the
definition for that function.
• And then you are free to run or call that function wherever you want, however many
times you want.
• And then of course we learned that you can pass it data inside the parentheses.

======================
function suma(x, y){
return x + y
}
function media(a, b){
return (suma(a, b)/2)
}
alert(media(9, 3))
(Ejemplo de otro curso)

======================

if this concept is even a little bit familiar to you, if it's making even just a little bit of sense,
then you're doing great, you're right on track and you're ready to move on to the next lesson,
so we just cover functions.

Up next, objects. So what in the world is an object?

19
1.3 Objects
In this lesson we are going to learn about objects. So what in the world is an object? well
let's not waste time talking, and instead let's just jump right into the action. Now go to
codepen and let's get started.

Before I show you what an object is, let me first show you what an object is not. So that we
understand what problems objects solve. Or in other words, before we learn how to use
objects, let's learn why we would use objects.

So first we can sort of practice what we've learned in the last two lessons. So let's imagine
that we want to store a bit of data about a cat.

To start we would need to store the name of the cat; next let's imagine we need to store the
cats age; And finally let's say that this cat should have the ability to meow. So maybe I
would create two variables and a function named meow ( so meowing is an action or a
verb ) and say:
let catName = “fluffy”
let catAge = 4
function meow(){
alert(“Meoooowwww”)
}
Now, all of this code is perfectly valid, it works without any problems, and we can access
the data by simply typing the name of the variable, or the name of the function. So for
example if we needed to access the cat's name, or their age, or to call the meow function, we
can just type out:
catName
catAge
meow()

however even though this code technically works, it is not ideal from a staying organized
perspective. Because we know that these variables and functions are related, they all have to
do with the cat, but as far as the computer or browser is concerned these variables and
functions have absolutely nothing to do with each other.

And this is not ideal for many reasons, but probably the biggest reason is if we were going
to collaborate and work with another person on this code, they would not immediately know
that these functions and variables are related. They would need to read all of the names, and
think, and use their own deductive reasoning and decide: ah yes these are all cat related.

So the question becomes: how can we write our code in a way so that it's painfully obvious
that there's a relationship between the name of the cat, the age of the cat, and the ability to
meow? Well the answer is objects.

so let me show you how I would code or write that same data but using an object instead:

20
let cat = {
name: “fluffy”,
age: 4
}
Now in this context, since this has nothing to do with a function, in this context curly
brackets are how we can create an object. So inside these pair of curly brackets we can
include multiple pieces of data. So I want you to think of an object as a container, and we
can store whatever we want inside it.

Properties
So the properties that I want to store inside this new empty object are the cat's name and the
cats age.

Now I know the syntax here is a bit weird or unfamiliar, so let's review what's going on,
because I know that in a previous lesson we learned that you can store a bit of data or create
a variable by saying:
let myName = “Brad”
This syntax that we learned, that uses let a name, and the equal sign, and the data you're
wanting to store, this is correct, however inside an object we need to do things a bit
differently.

Within an object, instead of a variable we call it a property. So inside the curly brackets:
• we just include the name of the property we want: name, age, or eye color, or fur
color.
• After that name for the property, instead of an equal sign (=) we include a colon (:)
• then we include the data we want to store.
• And then this is important, when you want to include another property we need to
separate them with a comma (,).

Before we created a variable that is a simple string of text. Now we are creating a variable
named cat, but instead of a simple string of text, or a number, it is an object. It is of the
object datatype. This object can store as many properties as we want, so we've got name,
age, we could add another one, say:
eyeColor: “blue”
So one of the advantages of using an object is that it is now immediately clear that these
properties are related to one another. The idea is that anything that has to do with this cat
lives within this object. This way instead of having a bunch of different variables floating
around with different names, we just have this one cat object, or this one cat variable, that is
self-contained, it's independent, it stores everything it needs.

Now you might be wondering: how can we access or use these properties? It's super easy. If
I want it to access the cat's name you just type:

21
cat.name
So we start with the name of the variable, cat. And then we just use the dot or the period to
look inside an object. So cat . name would evaluate to fluffy. We could say:
cat.age
cat.eyeColor
you get the idea.

Methods
However you might be wondering: what happened to the cat's ability to meow? Remember
before we had a function named meow. well check this out instead of just simple properties
that contain a string of text or a number an object can also contain functions inside it. so
after, let's say:
meow(){
alert(“Meooowwww”)
}
That's how you create a function.
• Then after the parenthesis, we have curly brackets.
• Inside the body of this function, we created an alert message that says meow.

And then, outside our object let's try to run or call the meow function:
cat. meow()
There we see our alert meow. Perfect.

In our previous lesson we learned about functions. This is how you execute, or run, or call a
function: you type out its name and then parentheses. And what we're doing here is no
different, for just looking inside our object, with the period, and them the function.

However even though technically this is a function, when a function lives inside an object,
or belongs to an object, we refer to it as a method. So the idea is that an object contains
properties and methods.

You're starting to see why an object is so useful. You can create this one single entity that
contains all of the data, and all of the abilities, or functions, or methods that that object
needs. It's organized. It's self-contained. Everything that has to do with the cat lives within
these overall curly brackets. And then whenever you want to use it or access it, you just type
out the name of the object, and look inside it, with a dot or a period.

And this is cool because it allows us to mirror our data after the way things work in real life.
So in the real world I'm a human being, I'm an object and I'm a self-contained entity. I
contain all of my properties and all of my abilities. All of the information about mem and
then I also have abilities (the name of the method or function, parentheses).

22
Brad.eyeColor
Brad.age
Brad.height
Brad.walk()
Brad.run()
Brad.jump()
Now. before we move on, I just want to clarify that outside the context of an object, when
you create a function you use the keyword function, like:
function jump(){
}
However within the context of an object, we do not need to include the keyword function.
So just like we have the names of our properties: name, age, eyeColor. We just include
another comma and then the name of the function, parentheses, curly brackets.

And again remember when a function lives inside an object, we refer to it as a method. So
this is the meow method.

Another quick note about the curly brackets

I don't want you to be confused by the curly brackets. So in programming the same
character can mean something different in a different context. So on the first line of code,
this curly bracket here is signifying the opening or beginning of our object. And then down
on the very last line this is closing our object. But then with our meow method, in this
context, the curly brackets represent the body of this function, or the body of this method.

Nesting objects

One more theoretical aspect of objects, and that is that within an object you can nest another
object.

For example maybe after this age property, let's create another new property named foods,
colon and then, instead of including a simple string of text, or a number, let's include
another object, so curly brackets to create an object (let's include a comma afterwards).
Then within these curly brackets for this new object, we could create two new properties,
may be named favorite, and then comma create another property maybe least favorite.
let cat = {
name: “fluffy”,
age: 4,
Foods:{
favorite: “Tuna”,
leastFavorite: “Oranges”
},
eyeColor: “blue”,
meow(){
alert(“Meooowwww”)
}
}
So the idea here is that within our overall objects, we have these properties: name and age.
And now, the foods property, that is an object itself. So their curly bracket starts and closes

23
the object, and then inside, it can have its own properties, like favorite and leastFavorite.

So now outside of the object, if we want it to access the cat's favorite or leastFavorite foods,
we would just type:
cat.foods.favorite
The key idea here is that we can use multiple dots within a line of code like this, to just keep
looking one level deeper inside the objects.

Practical part of this lesson


Having set all of that, let's move on to the practical or fun part of this lesson.

Let's set things up, so that anytime a visitor clicks on the webpage, opens up an alert
message that says: “hello there”.

How would we do that?

Well our JavaScript environment, in this case the web browser, it brings to the table a bunch
of its own pre-built objects. So just like how you and I created the cat object, that stored the
data and abilities of the cat, the web browser prebuilt objects that store the data and abilities
of the webpage.

And of these different objects, perhaps one of the most useful is the browser's document
object. We will learn more about the document object later on in the course, but for now all
you need to know is that it sort of represents the web page as a whole, meaning it's an object
that contains all sorts of properties, and methods.

In this case if we want to show an alert message anytime someone clicks down here on the
page, then technically speaking, that means we want to be on the lookout for the click event.

So let's look inside the browser's document object, and the document object contains a
method named addEventListener
document.addEventListener(“click”, myAmazingFunction)
So we are running or calling this method addEventListener(), and within the parentheses
we need to pass it two arguments.

So the first argument is which event we are listening for. So for example you could say
“click”, or “scroll”, or “keydown”. But we're listening for the “click” event.

And then the second argument that we want to pass into this method, is a function that we
want to run every time this event happens. And notice, and this is really important, that I did
not include a new pair of parentheses right after the function name here, to actually call the
function. Because we don't want to run, or call, or execute this function right here, right
now. Instead we are just passing along the name, a reference to the function, and it's up to
the web browsers addEventListener method to know when to call this function. In this
case it's going to call the function anytime we click anywhere on the page.

24
So maybe right below this code why don't we create our own brand-new function:
function myAmazingFunction(){
alert(“hello there!”)
}
So if I click anywhere on the preview page, we see that our function successfully runs.

We can see that the add eventlistener method is doing its job. so the idea is that we can
leverage the web browsers built-in objects, in order to make the web page do whatever we
want at just the right moment.

Now if everything in this lesson was not crystal clear that's okay. I do not expect you to
remember exactly how we created our cat object from scratch. We will practice that again
later in the course. Right now all you need to know about objects is that you can look inside
of them with the dot. If that's at all familiar to you, if it makes even a little bit of sense,
you're right on track.

In our very next lesson we are going to learn about arrays. So what in the world is an array?
Let's keep our momentum rolling, let's answer that question and I will see you in the next
lesson.

1.4 Arrays
In this lesson we are going to learn about arrays. So what in the world is an array?

well let's ask ourselves in the English language how would we use the word array. Well, for
example, a car dealership might say that they have cars available in a wide array of colors.
And that just means they have a lot of available colors. So when we hear the word array just
think of a collection. It doesn't matter what the collection is of, just that there's a collection
made up of multiple items.

That's enough of an introduction. Now let's jump right into the code in the action, and have
you roll up your sleeves and create your first array with JavaScript code. So go ahead and
open up Codepen again.

In a previous lesson we learned how to store a single value like this:


let myFavoriteNumber = 7
However, what if we wanted to store multiple numbers, so plural, a collection of numbers?
Well we could do this:
myFavoriteNumbers = [9, 2, 8, 3, 7, 4]
So in JavaScript a pair of square brackets ( [ ] ) is how you create an array. Inside the square
brackets we can include multiple values.

The idea is that an array is a collection. So now this variable, myFavoriteNumbers, is


storing a collection of all of these numbers in memory. And arrays are not limited to just
numbers. So on a new line we could say:

25
let myWords = [ "red", "orange", "yellow"]
So this array is a collection of strings of text. The first array is a collection of numbers. Or
we could even create an array that is a collection of objects:
let myPets = [{name: "Meowsalot", species: "cat"}, {name: "Barksalot",
species: "dog"}]
it's an array, so square brackets. And then instead of including a simple number, or a string
of text, within the empty pair of square brackets, these two pair of curly brackets could
represent two pets. And then, just as a quick example, we could build out these objects, so
within the pair of curly brackets, we could give it some properties.

We practiced this object syntax in our previous lesson. Inside these curly bracket, we
represents an independent entity, or an object.

Why would we want to create collections of values like this? Well the answer is because
collections like these, especially collections of objects like this, this is really no different
from how most apps or websites work. For example Facebook is really just an array of post
objects, that you scroll through; Twitter is really just an array of tweet objects, that you
scroll through; or your email inbox is really just an array of email objects, that you scroll
through.

So we had an array of pet objects, but imagine: if it was your email inbox, instead of name
maybe this property would be, from, and it would have the from email address; and then
instead of species, maybe this would be: to, and then it would have the to email address; and
then maybe there would be another property named body, and that would contain the actual
email message itself .

The point that I'm trying to make here is that a lot of programming is really just working
with arrays. For example if you were on Facebook and you posted or created a new post,
you're really just adding a new item to the array of posts. Or if you were in your email inbox
and you deleted an email, you're really just removing an item from an array.

Adding a new item to our arrays


So right now why don't we practice adding a new item to one of our existing arrays, and
also we can practice removing an item from one of our arrays.

Let's start with adding an item.

So imagine we want to write a new line of code that maybe adds the word green to our
existing myWords array. How can we write a bit of code to programmatically add the word
green on to the end of this collection? Well let's begin by working with this variable name:
myWords.push("green")
Now you might be thinking to yourself: why a dot? Isn't a dot or period how we look inside
an object? And the answer is yes it is. An array is actually just a special type of object. It's
not exactly the same type of object as we learned about in our previous lesson, but it's a
special type of object that has access to its own abilities or methods, and these are abilities

26
and methods that we do not need to add or create ourselves, but rather these are abilities that
the array just has out of the box, they are provided by the JavaScript language itself.

So for example all arrays have access to a method named push(). So we are calling this
function or method named push(), and this is how we can add an item onto the end of an
existing array. So within the parentheses for this method or function we can just include an
argument of “green”.

Ok, and now how can we test this out? How can we make sure that the array was actually
updated? Well in previous lessons we used the alert annoying pop-up to try and test
something out, but now I want to show you something a bit easier to use. So our JavaScript
environment, in this case the web browser, has an object named console, and we can say:
console.log(myWords)
and anything we include within these parentheses will get output, or logged, to the console.
So this is a great way to test your code. It lets you see your values visually, so you can
make sure that it's working the way that you expect. So we log the myWords array out to
the console, so we can see what it contains. And then, how do we actually see the console?
Well if you just right-click in the preview part of Codepen, I'm going to choose the inspect
option, that opens your developer tools, and then just look for the tab named console. And
here we see the contents of our array, and notice the last item is “green”. That means that
this line of code successfully added “green” to the end of that array. And this is cool
because we did not need to create a function or method named push. The push method is
just a native built-in part of the JavaScript language that arrays automatically get access to.

And this actually brings us to one of the neatest aspects of JavaScript.

So in the JavaScript language, almost everything, not everything but almost everything, is
actually an object, or at the very least, gets treated or interpreted as an object. So this is not
just the case with arrays, but also even simple strings of text, or numbers. Each type of data
gets access to its own set of super powers, or abilities, or we should say, functions or
methods.

So for example (and this has nothing to do with arrays, but it's important to understanding
JavaScript), so if we created the next variable, equal a string of text:
let myName = "Brad"
yes this is just a simple string of text. It does not look like the cat object that we created in
our previous lesson. However behind the scenes, JavaScript is actually going to treat the
string of text as if it was an object, and it's actually going to get access to abilities or
methods that are specific to strings of text. So for example we could say:
console.log(myName)
and log out our my name variable in the console, there you can see it.

However, if we wanted all of the letters in our name to be capitalized, instead of just
myName, we can say:

27
console.log(myName.toUpperCase())
and if I check the console there we see our name in all capital letters.

And really quick, just for fun, I want to show you that even the number datatype gets access
to its own special abilities:
let myNumber= 7.89
So this is just a simple number. It doesn't look like an object. However behind the scenes,
JavaScript is going to give it access to methods or abilities related to numbers. So on a new
line, if we log this out to the console:
console.log (myNumber)
there we see the number 7,89.

And now imagine if we wanted to round that to the nearest whole number. Well in
JavaScript we could just say:

console.log (myNumber.toFixed())

and if we check the console, 7,89 got rounded up to 8, cool.

The idea is simply that different types of data have access to different abilities or methods.

Removing an item from an array.


So let's imagine we want to write a new line of code that maybe removes the word “orange”
from the myWords array. so we can just say:
myWords.splice(1,1)
the splice(a, b) method lets us remove a particular item from an array. Within the
parentheses we want to pass this method two arguments. The first argument (a) is the index
of which item you want to get rid of. so what does that mean? well if we look at our array
up here, each item is represented with a numerical index. Now arrays and JavaScript are
zero-based, which really just means we start counting at 0 instead of 1. So red would have
an index of 0, and then 1 and then 2. So if our hypothetical goal is to remove orange, orange
has an index of 1, so in splice(), for the first argument let's say 1; And then the second
argument is how many items you want to remove starting from that index. So we're just
going to say 1 (we only want to get rid of one item). And now let's test this out, let's see if
it's doing what we expect it to do, so let's log out our array to the console:
console.log (myWords)
and now if I check the console. Perfect, we just have: ["red", "yellow", "green"]

What if we wanted to get rid of “red”? Well “red” is the first item so it has an index of 0:
myWords.splice(0,1)
, so down here in splice we would say zero, and we still only want to remove one item
starting from that index if we check the console we see that red got removed, perfect.

28
How to access the value of a particular item in an array
And this concept of the numerical index, is also how we can access the value of a particular
item in an array. So for example, let's take our myFavoriteNumbers array, and let's imagine
that we wanted to access the value of the third item in the collection. So we know that it's a
value of eight, but if we want it to access it programmatically, we could say:
console.log(myFavoriteNumbers[2])
To look up an item in an array by its index, we just include a pair of square brackets ( [ ] )
after the array, and then we include the numerical index. So if we wanted the third item we
don't type three, because remember arrays are zero based, so the third item would be to
write 2. So if I check the console cool, there we see the number 8.

Let's practice accessing an item in an array one more time.

Let's imagine that we want to access the species of the second pet in our my pets array of
objects.
let myPets = [{name: "Meowsalot", species: "cat"}, {name: "Barksalot",
species: "dog"}]
So we know that that's a value of dog, but how would we access that programmatically? So
let's say:
console.log(myPets[1])
We are interested in the second item in the array, so [1] would be the second item. This
would retrieve us the entire pet object.

But then we want to look inside that object for the species value:
console.log(myPets[1].species)
so if we check the console, cool, there we see dog.

Why arrays are so important


So in addition to adding and removing items from an array, it's also very easy to make the
computer sort an array alphabetically, or sort by some other quality. Or perhaps most
importantly of all, computers are really good at automating tasks, so once we have a
collection or an array, it's super easy to make the computer do something once for each item
in that array. For example maybe displaying it visually on to the webpage.

And then remember at the end of our previous lesson we learned how to do something
every time the user clicked anywhere on the page, well you can imagine that we can watch
for clicks on a particular button on the page, and then in response to that event, we can
maybe add an item to an array, or remove an item from an array, or sort the array, or just
work with the array in some interesting way that the user wants.

Now at this point I do not expect you to be an expert on arrays, and you don't need to have
remembered everything in this lesson, all you need to know is that an array is a collection of
items and that arrays have access to different methods like push and splice, that let us

29
manipulate or work with the array. If that makes even a little bit of sense then you're on
track and you're ready to move on to the next lesson.

Up next we are going to learn how to make decisions in our code, this is going to open up so
many doors. So let's keep things rolling and I will see you in the next lesson.

1.5 Making Decisions


In this lesson we are going to learn how to make decisions in our code. Let's jump right into
an example.

If
So let's imagine that we own an online strawberry store and we have a rule that an order
must contain at least 10 strawberries in order for a user to place that order, otherwise it's just
not worth our while to ship it. So if a visitor has added 10 or more strawberries to their cart,
so let's say:
let strawberryCount = 20
as long as this variable of strawberryCount is greater than 10, then maybe we want to
output a message on to the web page that says: “congratulations”. So we can use the web
browsers document object and it contains a method named write(), and we can include a
string of text in these parentheses so I can just say “congrats!”.
document.write("Congrats!")
And then if I take a look at the preview area of Codepen then we can see Congrats!.

Okay, but on the other hand, if strawberry count is less than 10, we don't want to say
congrats. In that case we would want to say:
document.write("Sorry, we do not ship orders that small.")
Okay, now down in the preview area, obviously we do not want to show both of these
messages. We want to show either one or the other depending on the value of
strawberryCount. So the question becomes: How can we make a decision in our code so that
our application can handle either situation and act accordingly? Well the answer is that we
can use something called an if statement. So check this out. Right above the congrats line
let's say:
if (strawberryCount > 9){
document.write("Congrats!")
} else {
document.write("Sorry, we do not ship orders that small.")
}
So what's going on? Let's review this code in detail. It really almost makes sense in plain
English. We're saying if strawberry count is greater than 9, then do this. Else, or otherwise,
do this.

So now down in the preview area we only see the congrats message because our strawberry
count is clearly greater than nine, but if we change this value up here to something that is

30
not greater than 9, like maybe 5, then down in the preview area we see the sorry message.

And that's cool it means that our tiny application is now flexible. It automatically adapts
and makes decisions on its own and that's the heart and soul of programming. Computer
programming uses if statements, or similar conditional logic like this, everywhere. For
example, on Facebook, if you are someone's friend, then you can see their entire profile and
all of their photos, else, or otherwise, if you are not their friend, maybe you just see a very
limited version of their profile.

Let's learn more about how if statements work.

So for starters, you do not need to include the else area. The else is just a fallback
insurance plan. If this condition is not true, then the else will happen. But you don't have to
have the else, so we could delete the word else and then it's curly bracket pair. And now, in
the preview area we see that if this condition is not true, then just literally nothing happens.
so the idea here is that the if statement can stand on its own, without the else block.

This area inside the parentheses, is called the condition. A condition is going to boil down
to a value of either true or false. If it's true, then obviously the code inside the if curly
brackets will run. If it's false, then either nothing will happen, or the code inside your else
block will run. Now, for the condition we are not limited to only the greater than symbol, or
operator, but before we move on to learn about other ways of comparing values, let's first
analyze what's really going on here. So as you might have guessed, the greater than
operator, is going to compare the value to its left and the value to its right, and then return
either a value of true or a value of false. Now, this whole idea of a true or false value is a
new concept to us. So in previous lessons we've learned that there are different types of
values in JavaScript. So just as an example I could say:
let testValue = 100
let testValue = "hello"
let testValue = {species:"cat"}
let testValue = ['red', 'orange', 'yellow']
and we've learned that one type of a value is a number (you don't need quotes around a
number); another type of value is a string of text (you wrap it in quotes); another type of
value is an object (with curly brackets); another type of value is an array (with square
brackets separated by commas)

Now I want to introduce you to a new type of value named a boolean, A boolean value is
either set to literally the word true or false, and it's not wrapped in quotes (if it was wrapped
in quotes, that would just be a simple string of text).

So the idea is that up in our condition for the if statement, the greater than operator, is either
going to return true or false. And that's a special type of value. And then the if statement
knows what to do with that true or false value.

31
Operators
So now that we have a general idea of what's going on, let's take a look at other ways of
comparing values:
• > the greater than operator.
• < the less than operator
• <= the less than or equal to operator
• >= the greater than or equal to operator
• == to see if a value equals something in particular. (a single equal sign = is how
we can assign a value, whereas double equal sign == is how we check for equality)
• != this will return true if the value is anything but the number.

Without a comparison operator


Also it's important to know that we do not even need to use a comparison operator at all. So
for example, our condition could literally just be the strawberryCount variable. Because in
this context where javascript is expecting a true or false, any number larger than zero will be
interpreted as true.

Obviously if we could set the variable to true or to false.

Also a completely empty string of text ( "" ) will be interpreted as a false value, but a string
of text with any actual content in it, is interpreted as true.

While
This whole idea of true or false values is not limited to just an if statement, or in other
words, the if statement is not the only place where a true or false value is useful.

Let's imagine that we want to output something on to the webpage many many times, maybe
two hundred times. So we say:
document.write("There are 2 strawberries")
document.write("There are 3 strawberries")
document.write("There are 4 strawberries")
document.write("There are 5 strawberries")
Well copying and pasting would be incredibly repetitive, and it's really just sloppy lazy
code, but luckily computers are really good at repetitive tasks. So how can we make the
computer do all of that hard work for us? The key here is leveraging a true or false value. So
check this out:
let strawberryCount = 2
//while (strawberryCount < 200){
document.write("There are" + strawberryCount + "strawberries.<br>")
strawberryCount = strawberryCount + 1
}
We begin with two forward slashes to begin a comment, and I'm only doing this because

32
Codepen automatically reruns and retests your code after every keystroke, and when you're
working with a while loop, you want to be careful to not try and execute an infinite loop,
because, without this line of code that increment the value of strawberry count, then the
while loop would just run forever, because it would never have a value greater than 200.
And computers don't like it when you create an infinite loop, they tend to freeze up or lock
up.

Within the while parentheses, we include a condition, that will return true or false. As long
as it evaluates to true, whatever lives within the curly brackets is going to happen again.
And then it's going to check the true or false nature of our condition again. And then repeat
the curly brackets again, and again, and again, until finally the condition evaluates to false.

Then instead of hard-coding and number ourselves, let's pull in the variable
strawberryCount. Also, after strawberries period I include a <br> tag, so that each sentence
sits on its own line.

After this line, but still within the while loop curly brackets, on this line of code we are
basically incrementing strawberryCount by one, so we're saying that variable should equal
itself plus one. Now a neat little trick: there is a more succinct or cleaner way of writing the
same line of code ( but before we improve or modify this line, I want to be sure to comment
out the beginning of our while loop once again, so just two forward slashes)
strawberryCount ++
when we include two plus symbols at the end of a variable like this, it will increment or add
one to that value.

It's a bit hard to understand until you actually see it in action, so let's try this out removing
the slashes to basically remove the comment .

Okay down in the preview area you can see that the computer automatically counted all the
way to 199. If we wanted it to actually include 200, we could change this to <= . Okay then,
in the preview, we see it counted all the way to 200.

What's going on? How is this working?

Basically a while loop is just going to keep repeating its body, it's area within the curly
brackets here, until the condition is no longer true, so we know that strawberryCount starts
out with a value of 2, and then each time the while loop runs, we are basically incrementing
strawberryCount by one.

And the computer counts all the way up to 199 for us. And computers are really good at
repetitive tasks like this. you could change this to 500 and it's going to count all the way up
for you anyways.

The takeaway idea here is that there are many places in JavaScript where you can leverage a
true or false value.

To circle back to the idea of this lesson: the while loop is going to keep repeating itself

33
again, and again, and again, as long as this value is true. Or to put it into common English
it's basically saying: While this is true, do this.

******

Now that's going to bring this lesson to a close, but before we move on to the next lesson I
do want to let you know that I am fully aware that these first four or five lessons have been
a bit disjointed, and I know it can be challenging to stay engaged, because we haven't yet
tried to test our knowledge by building some sort of real-world application. The fun level
has not been too high yet. But trust me, you are doing yourself a huge favor by learning this
core of the language first. Once all of these different symbols, and parentheses, and equal
signs, once this basic syntax becomes even a little bit familiar to you, you will have already
won 90% of the battle of learning to be a JavaScript developer. Because javascript is
JavaScript, it doesn't matter if we are writing it in the web browser, or if we are writing it
from node, to set up a server, or we are writing it from MongoDB, to work with a database.
If you can speak this code, if you can speak this language itself, then learning the
environmental jargon of the browser, or note, or MongoDB is a piece of cake.

Now again, I know the fun level in the course so far has been relatively low, and I know
that so many other courses take the opposite approach, they have you start building a web
application immediately, but you're really just copying what the instructor is typing, because
things are moving so fast and you haven't yet had a chance to get familiar with the syntax,
the parentheses, the curly brackets, the dots, the equal signs, the quotes. So on and so forth,
so long story short, I know, without a doubt, that this is the most boring and tedious part of
the entire full stack course, but consider this first chapter the metaphorical act of eating your
broccoli, it's not the tastiest, but it's really good for you, in the long run. So for many of
you, I know it feels like we're moving very slowly, don't worry the speed and tempo of this
course is going to pick up dramatically as we move on, but in this first introductory chapter
let's just keep eating our broccoli for a few more lessons. We are already done with day five
out of ten, and once we finish the ten days of JavaScript, we will have a rock solid
foundation and a basic understanding of the language itself, and then from there, we can get
on to the fun stuff and actually start building applications. Trust me there is a method to this
madness.

In our very next lesson we are going to learn more about functions as we answer the
question what is a higher-order function should be a lot of fun. Let's keep things rolling and
I will see you in the next lesson.

1.6 Higher-Order Functions


In this lesson we are going to learn about higher order functions. Let's begin with the
question: what in the world is a higher order function?

So the boring technical definition is:

A higher order function is a function that either:


• A) accepts a function as an argument.

34
• B) Or returns a function as a result.

That wasn't helpful at all, because if you learn the way that I learn, technical answers like
that do nothing for me. I need to see examples in order for me to actually learn anything. so
this lesson is going to be broken up into three parts.

Lesson overview
1. We will look at an example of a function that accepts a function as an argument.

2. After that, we will create our own brand-new higher-order function, that returns a
function as a result.

3. And finally, at the end of the video, we will learn about some of the most useful
higher-order functions, that are part of the core JavaScript language (and not just web
browser jargon), that you would leverage in the real world on a daily basis.

1. A function that accepts another function as an argument


So believe it or not, we've actually already seen a function that does this. so type this out
with me if we say
document.addEventListener("click", ourAmazingFunction)
function ourAmazingFunction() {
alert ("Thankyou for clicking!")
}
addEventListener() is a function or method that belongs to the document object, so we
include parentheses to run or call the function, and you might remember that it takes two
arguments: so the first argument is which event you want to be on the lookout for ("click"),
and remember that the second argument is supposed to be a function that you want to run
when this event happens (ourAmazingFunction). And then down on a new line we create a
function with this matching name. And maybe we just alert a pop-up message that says
“thank you for clicking”.

Okay. Now if I check out the preview area of this and click down here, we see the pop-up
“thank you for clicking”. We've done this before it's not impressive. The reason I'm
showing you this is I want to point out what a higher-order function is. We would say that
this addEventListener() method, or function is a higher-order function, because the second
argument that it expects to receive is a function.

If you've never worked with another programming language before, you might not see
what's so special or noteworthy about this. However in certain programming languages,
you are not allowed to pass a function as an argument, you can usually only pass simple
values, like a string of text, or a number. So JavaScript is special in the sense that functions
are not considered weird, or special entities with their own unique set of rules of where and
how they can be used. In JavaScript a function is just like any other entity, or value. To
explain what I mean by that, let's jump into our next example.

35
2. A function that returns a function as a result.
But really quick, back to the definition:

A higher-order function is a function that accepts a function as an arguments and / or returns


a function as its result.

So we just saw an example of the first part of that definition. We saw a function that accepts
a function as an argument. And now the last part of the definition, a function that returns a
function as a result. That is a bit trickier to understand.

First, let's begin with a simple function that is not a higher-order function.
function doubleMe(x) {
return x * 2
}
document.write(doubleMe(20))

We create a function and name it doubleMe. And imagine that we want this function to
double whatever number you give it, and then return that value. So within its parentheses,
we can include a parameter (x), and then inside the body of the function we just say return
that parameter, times two.

And then below this function, we test it out. So down the preview area, we see that it
worked properly, we see 40.

So the point here is that this doubleMe function is not a higher-order function. Clearly it
does not accept a function as an argument, we expect it to receive a number, and it also does
not return a function, it just returns a simple number.

Now, if you're like me, you might be scratching your head and wondering: When would it
ever be useful for a function to return a function? well let me give you an example:

so let's imagine that we also wanted a function named tripleMe and quadrupleMe:
function doubleMe(x) {
return x * 2
}
function tripleMe(x) {
return x * 3
}
function quadrupleMe(x) {
return x * 4
}
But this code is getting repetitive. Literally the only thing that's changing is the number that
we are multiplying by. So just like each one of these functions returns or generates a value,
what we can do is create a new function that generates or returns one of these multiplier
functions.

6:20 Let me show you what I mean, because it's really confusing until you see it in action.
So let's create a brand new function createMultiplier:

36
function createMultiplier(multiplier){
return function(x){
return x * multiplier
}
}
in the parentheses let's give it a parameter (multiplier); and then in the body of this
function, instead of returning a number we can literally return another function. And now
let's just pretend that this function is the doubleme function, but let's make it flexible. So
within its parentheses we could include an x as a parameter. This would represent
whichever number is getting doubled, or tripled, or quadrupled. And then in the body of this
function we would just return that number x multiplied (and then this is where we make it
flexible), so instead of doubling it, or tripling it, or quadrupling it, let's just pull in the
multiplier parameter.

(now don't worry, I do not expect this to make sense yet.)

Okay, now, check this out this is where it will start to make a little bit of sense. Down here
we can say:
let doubleMe = createMultiplier(2)
let tripleMe = createMultiplier(3)
let quadrupleMe = createMultiplier(4)
And then we can just use this create multiplier function to create our doubleMe function, so
we can say createMultiplier (2) . etc.

Okay now before we actually try to use these new functions, let's take a minute to
understand what's actually going on here, because there are two really interesting and
potentially confusing things taking place here.

So first, our createMultiplier function is considered a higher-order function, because


instead of just returning a simple string of text, or a number, or an array, it's returning a
function. Now, that may not seem very special or interesting but it's noteworthy, because in
other programming languages, functions are considered special entities with our own weird,
or unique set of rules, governing when and where they can be used. In other programming
languages, we might only be allowed to return a simple number, or string of text, within a
function right here. But in JavaScript, a function is an entity just like any other value, which
also means that not only can we return a function within a function, but we can also assign a
function to a variable, like we see down here. So just like in previous lessons, how we
would set:
let strawberryCount = 20
let strawberryCount = "hello"
let strawberryCount = ['red', 'orange', 'yellow']
so just like in the past where we would set a variable to equal a number, or a string of text,
or an array, well in JavaScript we can set a variable to equal a function, and that's exactly
what's going on here.

Now again, this might not seem super interesting, but it is, because we cannot necessarily
do this in other programming languages. So the point here is that javascript is special in the

37
sense that functions are considered first-class citizens or entities. So we can pass them
around as arguments, we can return them inside of a function, and we can even assign them
to a variable. And believe it or not, but this makes JavaScript a very flexible and powerful
language.

Okay now, just to prove to ourselves that this code works, let's test out these doubleMe,
tripleMe, and quadrupleMe functions. So let's output a sample value down into the preview
area. So maybe below our code we can say:
document.write(doubleMe(10))
document.write(tripleMe(5))
document.write(quadrupleMe(5))
And there we see: 201520

if you're still a little bit confused as to how this is working. we can take double me as an
example. So we are creating a variable and saying: let doubleMe equal whatever this
createMultiplier function returns, and we know that that function returns a function, so
then literally, the doubleMe variable is going to equal this function that gets returned :
function(x){
return x * 2
}
And then, we can call it just like any other function.

All right, so now that we've covered both halves of the definition of a higher-order function,
let's move on to the third and final part of this lesson.

3. Useful higher-order functions, that are part of the language itself


We begin this lesson by looking at an example of a higher-order function that the web
browser environment offers. And then, in the second part of this lesson, we created our own
functions. And now in this third and final part, I want to show you a few higher-order
functions, that are part of the core JavaScript language itself. And actually, some of the
most useful ones, that you would run into on a daily basis, all have to do with arrays.

So let's begin by pretending that we have an array:


let myColors = ['red', 'orange', 'yellow']
Okay so we've got this example array. Now let's imagine that we want to do something
once for each item in the array. For example, let's imagine we want to output, down on to
the preview part of the webpage, a little bit of text that says: “the color red is a great color”
and then, “the color orange is a great color”, “the color yellow is a great”. So we want to
perform this repetitive task and do it once for each item. Well check this out:
myColors.forEach(saySomethingNice)
we begin working with our variable myColors. In the JavaScript language, all arrays have
access to a method named forEach. And just based on its name, you might be able to guess
what it does: within its parentheses, for the argument, we just give it a function, and then it's
going to run that function once for each item in the collection. Let me show you how it

38
works. So maybe down, on a new line, let's create a brand new function and name it
saySomethingNice:
function saySomethingNice(color){

}
so I've got the name, and then parentheses, curly brackets. Okay, now we can spell out what
this function should do just a minute, but within the parentheses for foEach() let's pass it
that function. And now this line of code almost makes sense in plain English:
myColors.forEach(saySomethingNice)
We've got our array of colors, and we are saying for each item in that array, say something
nice. So now check this out down: in the actual function definition, within these
parentheses, we need to create a parameter, so you could just say (X), which is easy to type,
or we could say (color), but then down here in the body of the function let's say:
document.write("the color " + color + " is a great color.")
because remember we want to output something down here that says: “the color blank is a
great color.”.

So I'm just gonna say: quotes, the color, and then a space, and then add on (+), our
parameter, and then add on another string of text, begin with the space, and say “ is a great
color”.

And there we see:

The color red is a great color. The color orange is a great color. The color yellow is a great
color.

If you wanted each one to sit on its own line, it's just a matter of HTML. So right after this
period, we could just add a break tag.
let myColors = ['red', 'orange', 'yellow']
myColors.forEach(saySomethingNice)
function saySomethingNice(color){
document.write("the color " + color + " is a great color.<br>")
}
Perfect. Now, this may not seem that impressive, but it's cool because our code is now
flexible, meaning in the future, if we ever added new colors to our array, it's going to
automatically display onto the webpage. So if we, at the end of the array added on, comma
green, that's all we need to do, and now we see “the color green is a great color”.

Now the real reason we just learned about this forEach() function, is to show you that it is a
higher-order function that is part of the core JavaScript language itself. Right, for its
argument it accepts a function.

However, indirectly we also just learned why arrays can be so useful. Once you have items
in a collection like this, computers are very skilled at performing a repetitive task or looping
through the array, and doing something once for each item, so we could just as well imagine
that each one of these was an email in your inbox, or a post on Facebook, or a photo post on

39
Instagram. Okay anyways. that was a quick look at the forEach method.

Now, two of the other most useful higher-order functions in JavaScript, that I leverage on a
daily basis, also have to do with arrays. And you do not need to type this out, but they are
map() and filter():
myColors.map()
myColors.filter()
I only typed out the name of our array variable here (myColors), to show you that these are
functions or methods that all arrays automatically get access to.

Now, we actually are not going to learn about map() and filter() in this lesson, because
we've already covered enough new ground and material for one lesson. But we are going to
learn about map and filter in our very next lesson. And this is great because these functions
are the perfect segue into our next topic. Now, this next topic might seem like a minor
detail, but in actuality it's crucial to understanding JavaScript. It's a concept that might be
obvious if you're familiar with another programming language, but I know that personally,
in my own experience, I wish that someone would have stressed this concept to me when I
was first starting out. And what is that concept? It's the difference between returning a
value, and mutating a value. So what in the world does that even mean? Well we're gonna
learn all about it in our next lesson, so let's keep things rolling and I will see you then

1.7 Returning vs Mutating


In this lesson we are going to talk about the difference between returning and mutating.
Now, don't worry, I do not expect you to know what I mean by those two words right now.
And before we try to jump right into the concepts, let's first begin by just giving ourselves a
bit of sample data to work with, or experiment with. And I want you to type this out:
let pets = [{name: "Meowsalot", species: "cat", age: 2}]
We create a variable, and name it pets, and we set it to equal an array, so square brackets.
And I actually want each item in this array to be an object, so to create an object we include
curly brackets. Let's give this first object a property of name, and then colon, and then give
it a value, I'm gonna name this first pet “Meowsalot”, after the quotes for that name value,
I'm gonna include a comma, and then give it another property of species, and give it a value
of cat. And then finally, comma, one more property, I'm going to give it an age of two.

Okay so we've got one object that represents a cat.

Now , I want to create additional objects within this array. But just for the sake of staying
organized, I don't want this line of code to become super long and difficult to read. We can
just add a comma at the end of this line, and we can include another pet object, so then we
can have one per line, so it's easy to read.

40
let pets = [
{name: "Meowsalot", species: "cat", age: 2},
{name: "Barksalot", species: "dog", age: 3},
{name: "Purrsloud", species: "cat", age: 8}
]
So we create a dog this time, with a name of Barksalot, species of dog, and age is 3. And
one more animal object, so name of Purrsloud , etc.

Let's do a quick review. So two or three lessons ago we learned, that we can
programmatically add on, to the end of an array by using the method named push. So we
could say:
pets.push({name: "Puppster ", species: "dog", age: 1})
start with our variable pets, and then in JavaScript, arrays have access to a method push(),
and then we add on a dog to the array, so curly brackets to create an object, let's give it a
name of Puppster, let's give it a species of dog, and an age of 1.

Now let's test this out. Let's log out the pets array to the console, and see if the new dog was
successfully added. So we could say:
console.log(pets)
We just log out our pets variable. So if I check the console... (And just to be clear, you
want to open your console by right-clicking down in the preview area of Codepen, and then
choose inspect, and then click on to the console tab) we see an array with four items. If I
expand it... awesome, we see the final object is that new Puppster dog.

Now, this is not new. We already learned about the push method several lessons ago. The
reason I'm showing it again right now, is because it's a great example of understanding the
difference between mutating and returning. So in this context the word mutating just means
changing or modifying. What I mean by this is, when we call the push method on this
array, it's going to modify or change or mutate that original array; after this line of code
runs, the pets array has changed.

However that's not all that the push method does. It also returns a value. It returns the
number of items that are now in the array. So in this case, it would return a value of the
number four. However we are not seeing that value of four because we didn't store this in a
variable, nor did we log it out to the console, nor did we output it on to the webpage. So
right now the value that this push method is returning is just sort of sitting in outer space,
sort of in no-man's land.

Now, just as a test, we can see the value that it returns by maybe logging this entire line (the
line with the push method) to the console. So check this out. I want you to cut this entire
pets.push line into your clipboard, I'm gonna select this cut it, and then let's write out:
console.log(pets.push({name: "Puppster ", species: "dog", age: 1}))
and then in the parenthesis just paste in your clipboard.

Okay, now, if I check the console, there we see that value, that the push method is
returning. So it returns a simple number value, but the line of code also still ran, and

41
mutated the array, because when we logged out the array, we see that there are still four
items, and the Puppster object was successfully pushed on to the array. So we could almost
say that the push method lives a double life. On the one hand it performs an action on the
array, it changes or mutates the array. And then, on the other hand, it returns a value.

Now, the real question here is: why is this interesting? Well the reason this distinction
between mutating and returning is important is because, there are other array methods that
do not mutate or change the array, and they only return a value.

Now, up until this point, the array methods that we've seen, like push, and splice, well,
really the main reason you would use these methods is to mutate or change the array. And
the values, that these functions return, almost seems like a weird side effect that would
never be very useful. However, right now, I want to show you two array methods that are
extremely useful, even though all they do is return a value, they do not mutate the original
array. And those two methods that I want to show you are map() and filter()
array.map()
array.filter()
So let's do this. I'm going to erase this console.log(pets) line at the very bottom. Okay.
below this on a new line of code, I want to show you the map method.

But first let's give ourselves a goal to work towards. So let's imagine that we want to create
a new array of these same pets, except in the new array, instead of each animal being
represented as an object with these different properties like name and species and age,
maybe in this new array, we only want the name of each animal. So we would literally want
an array that just said Meowsalot, Barksalot, Purrsloud and Puppster.

So how can we achieve this?

array.map()
Well luckily the map method is perfect when you want to create a new array that is based
on another array. Let me show you what I mean:
let pets = [
{name: "Meowsalot", species: "cat", age: 2},
{name: "Barksalot", species: "dog", age: 3},
{name: "Purrsloud", species: "cat", age: 8}
]
console.log(pets.push({name: "Puppster ", species: "dog", age: 1}))
pets.map(nameOnly)

function nameOnly(){
return "hello"
}
So down on this new line of code, we begin with our pets array, and then say dot map().

So in JavaScript every array has access to a method named map(), and map() is a higher
order function. It accepts a function as an argument. Now, the map method does not
mutate or change the array that you call it from, instead it simply returns a new value, and

42
the value that it returns is a brand new separate array.

We include a function within the parentheses here, and we call it nameOnly.

Then on a new line we create a matching function nameOnly( ){ }

What the map method is going to do is call this function once for each item in the pets
array. So it's going to loop through the array. In our case our array has four items, so it's
going to call this function four times, but if your array had 500 items, it would call the
function 500 times.

Now, ultimately the map method returns a brand new array. And how it works is: each time
it calls our function, whatever this function returns, is what's going to get added on to the
brand-new array. Just as a test within the body of our function here let's return a string of
text that simply says “hello”.

Now, ultimately, on this line of code, the map method is going to return a brand new array
that simply contains the word hello four times. But as of this moment that array value, that
the map method is going to return, is going to get returned into outer space or no-man's
land. So instead, we save this into a new variable. So, at the beginning of this pets.map()
line, let's say let and any variable name, I'm going to call it ourTest

Now, just as a test down here, let's log out to the console the ourTest variable, so we can
say: console.log(ourTest).
let pets = [
{name: "Meowsalot", species: "cat", age: 2},
{name: "Barksalot", species: "dog", age: 3},
{name: "Purrsloud", species: "cat", age: 8}
]
console.log(pets.push({name: "Puppster ", species: "dog", age: 1}))
let ourTest = pets.map(nameOnly)

function nameOnly(){
return "hello"
}

console.log(ourTest)
And if we check the console, we do indeed see:
(4) ["hello", "hello", "hello", "hello"]
an array with four items. And it's simply hello hello hello hello.

This is where things might start to make sense for you. There are four items in the pets
array. And because the function that we provided, the map method simply always returns a
value of hello. That's what gets added on to the brand-new array that map is creating.

Now, let's get back to the goal at hand. Remember we wanted to create a brand new array
that was simply the name of each pet. So check this out: when map calls the function that
we provided, it passes into the function the current item that it's looping through. So down
in our function inside the parentheses, right after our function name, let's include a

43
parameter ( X ) because it's easy to type, but you could call it pet, or animal, or item. The
idea though is that the first time the map method calls our function, the parameter X would
represent the Meowsalot object; and then the second time map calls our function, X would
represent the Barksalot object.

So instead of returning the word hello, if X represents the current pets object, that's being
passed into our function, we know that you can look inside an object with the dot and we are
interested in the value of the name property. So we can just say:
function nameOnly(x){
return x.name
}
and if we check the console:
(4) ["Meowsalot", "Barksalot", "Purrsloud", "Puppster "]
Awesome! We see an array with four items, and it is simply the names of each animal.

array.filter()
Now let's change gears. So we just saw the map method in a nutshell, and before we
finally get to the fun part, or the aha moment part of this lesson, I want to show you one
more array method that is named filter.

Let's give ourselves a quick goal. Let's imagine that we want to create a new array that
only contains the dogs from the pets array. So no cats, only dogs. how can we achieve this?
Well, luckily in JavaScript all arrays have access to a method named filter. filter is very
similar to the map method, so it does not mutate or change the array that we call from, it
simply returns a value, that is a brand-new array. And it's also a higher order function. , so
check this out:
let pets = [
{name: "Meowsalot", species: "cat", age: 2},
{name: "Barksalot", species: "dog", age: 3},
{name: "Purrsloud", species: "cat", age: 8}
]
console.log(pets.push({name: "Puppster ", species: "dog", age: 1}))

function nameOnly(x){
return x.name
}

let dogs = pets.filter(onlyDogs)


function onlyDogs(X){
return X.species == "dog"
}
console.log(dogs)
We save this into a variable dogs, equal whatever pets dot filter is going to return. Within
these parentheses let's pass filter a function named onlyDogs. And we create a function
with that matching name. And just like with map, filter is going to call our function once
for each item in the pets array. The difference is that with filter, our function doesn't
specify exactly what should get added to the new array, instead we simply return either

44
true or false.

Let me explain what I mean by this.

So within the parentheses for our onlyDogs function let's include X as a parameter. And
the first time that filter calls our function, the X parameter is going to represent the first
item in our array (which happens to be the Meowsalot object). So down in our brand-new
function if we return a value of true, that Meowsalot object will be added to our brand-new
filtered array; if we return false, that item will be skipped and it will not be added to the new
array.

So since we learned about true and false values in an earlier lesson, check this out. If we
only want dogs, we can simply say:
X.species == dog
the double equal sign comparison operator is going to boil down to either true or false,
based on the values to its left and to its right (of the double equal sign). So in other words,
this is only going to return true if the item is a dog.

So let's test this out. Let's log out to the console our dog's array. So we can say:
console.log(dogs)
if we check the console we see an array with two items. If I expand it, awesome! it only
contains Barksalot and Puppster.

Now, really quick, I just want to do one more thing before we finally get to the aha moment
of this lesson.

Back in our code, right beneath our onlyDogs function, why don't we create a brand new
function and call it onlyBabies. And we could use this function if you imagine that we only
wanted an array of pets that were younger than the age of three:
function onlyBabies(X){
return X.age < 3
}
So within the parentheses let's include a parameter X to work with the current item, and let's
say: only return true if X.age is less than three.

Okay now, this is finally the aha moment of the lesson.

Let's imagine that we want to create a new array that is simply the names of the dogs that
are under the age of three. So we could create a variable and say:
let babyDogNames = pets.filter(onlyDogs)
we begin with our pets array, and call the filter method, and filter out for only dogs. And
now (this is the cool part), because this pets.filter(onlyDogs) section of code is going to
return an array, well, we can just look inside that array that it's going to return, and filter it
again.

Now, what we just did is super important in terms of understanding JavaScript. So when I

45
say that all arrays have access to these methods, I literally mean all arrays, not only arrays
that have been already saved into a variable, but even arrays that are just sort of floating in
outer space, or in no-man's land.

So as soon as this highlighted part returns its value or its array that array is just sort of
floating in memory or floating in outer space but then we can tack on to it and say hey that's
an array just like any other array it must have access to these array methods

so another dot filter and this time we can filter for onlyBabies. And finally, if we want this
array to only contain the name property, and not the age, or species, well, we know that this
is going to return an array, so we can just look inside that array, and call the map method.
And remember our old function was named nameOnly, and it also returns an array, and
that is what we can finally let get saved into our variable.

Let's go ahead and test things out by logging this to the console
(console.log(babyDogNames) ):
let pets = [
{name: "Meowsalot", species: "cat", age: 2},
{name: "Barksalot", species: "dog", age: 3},
{name: "Purrsloud", species: "cat", age: 8}
]
console.log(pets.push({name: "Puppster ", species: "dog", age: 1}))

function nameOnly(x){
return x.name
}
let dogs = pets.filter(onlyDogs)
function onlyDogs(X){
return X.species == "dog"
}
function onlyBabies(X){
return X.age < 3
}

let babyDogNames =
pets.filter(onlyDogs).filter(onlyBabies).map(nameOnly)

console.log(babyDogNames)
And if we check the console, awesome! It's an array with just one item, and it's only the
name.

The big takeaway point for this lesson is that, even though these methods do not mutate or
change the original array, they are still incredibly powerful. They are powerful on their
own, but then, once we realize that we can chain together multiple actions like this, we
begin to see the true nature of JavaScript and how creative we can get with our code.
Chaining together actions like this, is not limited to only arrays, we can do this with
basically any data type in JavaScript.

If it's not crystal clear, do not worry, because this is a concept that we are going to practice
again and again throughout the course.

46
That's going to bring this lesson to a close. In our next lesson we are going to learn about
scope and context. So what in the world do those words mean in relation to JavaScript?
Well, let's keep things rolling and let's find out in the next lesson.

1.8 Scope & Context

In this lesson we are going to talk about scope and context. So what is scope and what is
context? Well, here are my own sarcastic definitions:
• Scope is the biggest source of confusion regarding variables.
• And context would be the biggest source of confusion regarding objects.

Now, these tongue-in-cheek definitions are not actually helpful, but right away they do let
us know that scope has to do with variables, and context has to do with objects. But beyond
that let's dive deeper. So let's start with scope and then in the second half of this lesson we
can cover context.

Scope
Instead of trying to explain scope with only words, let's work through a few examples
together, where we can see scope in action. so imagine we have a variable, and now let's try
to access this variable from within a function.:
let myName = "Brad"
function amazingFunction(){
console.log(myName)
}
amazingFunction()
We create a brand new function named amazingFunction, and just as an example let's try to
log out to the console, the myName variable, just to see if we have access to it.

And then, let's actually call or execute this function to test it out.

Now, if we check the console... awesome!

This is just review. We've already done this before. So the question is: why am I showing
this to you? Well, it's because the topic of scope has to do with where we can access a
variable from.

Let me show you what I mean. So this code is working perfectly. But what if we move this
first line of code, (the definition of the variable) to live within the function? let's try that out:

47
function amazingFunction(){
let myName = "Brad"
}
amazingFunction()
console.log(myName)
Now, at first glance, as a beginning programmer, we would think that this would work.
we've got this function, that's going to create a variable named myName. Then we are
calling the function, so we know that that code is going to get executed. So we would think
that we would be able to log out to the console myName. But if I check the console, we
just see a big error message that says “myName is not defined”. So we just smashed our
head up against a brick wall, and this is our first example of running in to an issue with
scope.

Now, before we worry about what the word scope means in this sense, let's first answer the
question as to why this code is not working. Why are we receiving that error message in the
console?

Well, it's because within the body of this function, or I should say, within this block of code,
within these curly brackets, as far as variables are concerned, we are in our own little new
world, that is separate or private from the outside world. So we would say that this variable
is scoped to this block, these curly brackets, meaning it cannot be accessed from outside the
block. So down here, when we try to access that variable, as far as this line of code is
concerned, this variable doesn't even exist.

The way the code were at the beginning of the lesson will work just fine. It works because
this line when we are creating the variable, we are not inside a block or any curly brackets.
We are just out in the open, in what we would call the global scope. This works because
scope is like a one-way street, the traffic only flows in one direction. Code can reach
outwards to access a variable, but it cannot reach inwards.

Now, don't worry, I don't expect you to understand what I just said. That's why we're going
to work through a new example right now, to understand what I mean by inwards and
outwards.

Example
let myName = "Brad"
function amazingFunction(){
if (2+2 == 4){
console.log(myName)
}
}
amazingFunction()
we know that the condition will always be true. Inside the curly brackets of the if statement,
the console.log line. Okay now, if I check the console, we see that things are working just
like before. So you might be wondering: why I even added this if statement at all?

Well, it's because it's a great example to explain what I mean when I say that scope begins
inwards and moves outwards. That analogy when I said that scope is a one-way street.

48
So, when this line of code “console.log(myName)” runs, Javascripts first instinct is to see if
there is a myName variable as close to home as possible, meaning within this scope, within
this block, within the curly brackets for the if statement. So just as a quick test, within the if
statement, right above the “console.log” line, if I say:
let myName = "Brad"
function amazingFunction(){
if (2+2 == 4){
let myName = "Brad the 3rd"
console.log(myName)
}
}
amazingFunction()
and then check the console, we see: “Brad the third”.

However, if we delete this line, if JavaScript sees that there is no myName variable within
the current local scope, well it's then going to look up the scope chain, or look one level
outside of itself. So outside of this scope, the next closest scope is within the body of our
function. So just as a test if we said:
let myName = "Brad"
function amazingFunction(){
let myName = "Brad Junior"
if (2+2 == 4){
console.log(myName)
}
}
amazingFunction()
And check the console. we see: "Brad Junior".

Okay. And then finally if we either deleted this line, JavaScript would say: okay, there's no
myName inside the local block, there's no myName in the block that's one level up, why
don't we check another level up from that? And that would finally land us in the global
scope. And it would see that AHA!, that variable exists. If we check the console, it's back
to just “Brad”.

So, the idea is that when a line of code runs, and you're looking for a variable, javascript is
first going to look for that variable as close to home as possible, within the current scope. If
it's not there, it's just going to keep moving up the scope chain, one level at a time, until it
finds what it's looking for.

Now, it's important that we really understand what's going on here. So really quick. This is
not a case of these lines overriding or updating this original variable. That is not what's
happening. Even though these three variables of myName all have the same identifier, or
label name, they are three completely independent and separate variables. Let me show you
not only how we can prove that, but also what I mean. Because I remember when I first
learned programming, and I saw an example like this, I actually misinterpreted it, and saw it
backwards. I saw it as: okay, we're creating the variable in the global scope; and then we are
updating the variable in this scope; and then we're updating it again in this scope. That is
not the case. These are three completely separate variables, and I can prove that to you:

49
let myName = "Brad"
function amazingFunction(){
let myName = "Brad Junior"
if (2+2 == 4){
let myName = "Brad the 3rd"
console.log("Inside the if stament" , myName)
}
console.log("Inside our function" , myName)
}
amazingFunction()
console.log("In the global scope" , myName)
Now, if we check the console we see:
Inside the if stament Brad the 3rd
Inside our function Brad Junior
In the global scope Brad
Inside the if statement is one variable, with its value; inside our function is a different
variable with its own value; and in the global scope that's another variable with a different
value.

What was the point of this experiment? It's to show you that these are three completely
separate variables, even though they have the same identifier, or label, it doesn't matter. The
let statement creates a variable within the current local scope. It does not matter if that
identifier, or label name, has been used in outer scope. Remember that inside a block of
code, inside these curly brackets, it's like our own new private little world, as far as
variables are concerned. Meaning it's almost like we get a clean slate. We can reuse the
same variable names, and JavaScript knows that we do not want to affect any of the
variables in outerscope, we just want to create a brand new separate variable that is scoped
to this block.

Now, you might be scratching your head, and wondering: well, what if we wanted to mutate
the global original variable from within our innermost block? Is there a way we can do
that?

And the answer is: yes absolutely.

Okay now, within the if statement, what if we want it to update, or mutate, or change the
value of the global scoped myName variable? Well, all we would need to do is remove the
word let from this line of code “let myName = "Brad the 3rd" ”.
let myName = "Brad"
function amazingFunction(){
if (2+2 == 4){
myName = "Brad the 3rd"
}
}
amazingFunction()
console.log(myName)
The let statement says: create a new variable for this local scope. But if we get rid of that,
now we are just trying to work, or access the variable, and we're setting it to equal
something.

50
So here's what Javascripts going to do: it's gonna see this variable myName and ask itself:
does this variable already exist within this current local scope? It doesn't, so then it's going
to look one level up, just within the function, it's going to see that it doesn't exist there
either, and then it's going to check one level up. And it's going to say: okay, it does exist in
the global scope, that must be what you're talking about right here “myName = "Brad the
3rd"”. So I'm going to let you update, or change that variable.

This is what I was talking about earlier, when I said that scope moves in one direction; it's a
one-way street. Inside code can reach outwards for variables, but outside code cannot reach
inside for variables.

So long story short: we set it to equal “Brad the third”, and now we are logging out to the
console in the global scope. And then our variable, if we check the console we see: “Brad
the third”. Awesome!

Var and let

Now, there's one more scope related thing we need to cover. So throughout this course
when we've been creating, or declaring a variable, we've been using the word let. However
until about three or four years ago there was no let in JavaScript. And instead, we had to
create variables by saying var and then the label or identifier, and otherwise the syntax is
the same. So if you're looking at older code, or if you inherit a project from someone, you
might see var being used instead of let. Now, there are several subtle differences between
var and let, but right now I want to show you the one big huge glaring difference between
the two. The biggest difference between var and let is that let uses block scope, whereas
var uses function scope. So, what in the world does that mean? Let me show you:
function amazingFunction(){
if (2+2 == 4){
let myName = "Brad the 3rd"
}
}
so within our if statement, if we put the word let here, we know that that's going to create a
variable that is scoped to this block., scoped to the if statements curly brackets. So let is
going to look for the nearest enclosing block. And a block can be several different things:
an if statement uses a block (these curly brackets); a while loop uses the curly brackets in a
block; clearly the body of a function uses a block. Okay, but the idea here is that let is
going to make it, so that this variable is only accessible from within the nearest enclosing
block. So right now, we would not be able to access the variable outside of the if statement.

However if we change this to a var instead of a let:

51
function amazingFunction(){
if (2+2 == 4){
var myName = "Brad the 3rd"
}
}
var uses function scope instead of block scope. So var is gonna say: I don't care that the if
statement has curly brackets and that it's a block, since I'm a var, I only care about the curly
brackets of a function (because var uses function scope, instead of block scope).

This means that this var variable is accessible anywhere inside its enclosing function, even
outside of the if statement. So we could access myName right here within the function.

Now again, historically that's how we created variables in JavaScript, but in the last three or
four years javascript finally got access to let, and the reason that 99% of developers used the
word let instead of var is because almost all other programming languages, besides
JavaScript, use block scope instead of function scope. Block scope is just what most of us
are used to. It's a paradigm that we are familiar with, and it's a super popular opinion that
block scope leads to less confusing code, less scope confusion, and just less problems
overall.

So long story short, that's the difference between let and var. But in the current year, and
looking forward I encourage you to always use the word let and never, or I should say
basically never, use the word var.

All right and that's scope in a nutshell. If you're still a bit confused, regarding scope, that's
okay, that's completely normal. In fact, I have worked with professional mid-level
developers, who were even sometimes still confused by scope.

Big picture, you do not need to be a scope guru at this point, I just want the topic to be on
your radar. It's something you need to be aware of, and if your code isn't working you might
want to double, or triple check your scope, and make sure your variables are pointing
towards what you think they are pointing towards. Remember, you can always use
console.log to check the value.

Okay, at this point let's change gears. We've talked about scope, now let's talk about
context.

Context
So scope is about variables, context is about objects. So with this in mind let's go ahead and
give ourselves an example object to experiment with.

52
let john = {
firstName: "John",
lastName: "Doe",
driveCar(){
console.log(this.firstName + " " + this.lastName + " is driving a
car.")
}
}
john.driveCar()
We create a variable, and give it a name of john, and set it to equal and object. Let's give it
the properties of firstName and lastName. And then let's also give this object a method
named driveCar. And let's imagine we want this method to log out to the console a bit of
text that says: “John Doe is driving a car”, only we don't want to necessarily hard code
“John” into the string of text, instead it would make more sense to pull in the value of the
firstName property . So the question is: inside of a method like this, inside this function
that belongs to the object, how can we reference this property?

Well, instead of just saying firstName, we instead want to say this.firstName.

Now, the entire topic of context in JavaScript is centered around the this keyword.

Now, let's test out this method. We have said: john.driveCar(). And if we check the console
we see: “John Doe is driving a car”. Awesome.

This is nothing new. The reason I'm showing it to you this time, is because this is a chance
to dissect the keyword this. what in the world does this mean?

Well, that's a loaded question. Even some of the best JavaScript developers in the world, if
they're being honest, at one point in their career they were definitely confused by the this
keyword.

So in our current example the this keyword is pointing towards our John object. So if we
use our imagination we are basically saying John.firstName, John.lastName. We know that
to look inside an object you just say -dot- and then whichever property you're interested in.

Now at this point you might be thinking: what's the big deal? What's so confusing? This
seems really straightforward. You might be thinking that within a method, the this keyword
simply always points towards the enclosing object. However that's not the case. So in a
search for the truth, let me confuse you on purpose, just for a minute, to show you why the
this keyword gives developers so much trouble. check this out:

53
let john = {
firstName: "John",
lastName: "Doe",
driveCar(){
function ImAFunctionNotAMethod(){
console.log(this)
}
ImAFunctionNotAMethod()
console.log(this.firstName + " " + this.lastName + " is driving a
car.")
}
}
john.driveCar()
Right above this console.log line, but still within our driveCar method, we create a brand
new function named ImAFunctionNotAMethod(). we are nesting a function inside of this
method. And inside the body of this function we log out, to the console, the this keyword.
Now, currently this function would never actually run. This is just a function definition, or
the recipe for the function. So then, right below it, we call that function.

And if I check the console. right above our “John Doe is driving a car” we see this window
object.

Let's not get too hung up on what window is. For now, I can tell you that in the web
browser, window is the root or global object. We could say that it's the top-level object that
houses or contains all of the web browsers other objects. For now let's just call window, the
global object.

Now, the important concept here is, that the this keyword is pointing to two different things
at two different times. In this context this line of code:
console.log(this.firstName + " " + this.lastName + " is driving a
car.")
the this keyword pointed towards our John object.

But then on this line of code:


console.log(this)
that this keyword is pointing towards the global object.

So the million dollar question is: how does Java Script decide what the this keyword should
be pointing towards?

Well, here's the answer: the this keyword does not point towards the enclosing object (the
john object). Clearly that's not the case. If that was the case, then this instance of the this
keyword (console.log(this)) would be pointing towards John. But it's not.

So the real answer is that:

The this keyword points towards the object that is executing, or calling the current
function.

54
Or in other words, instead of focusing on these two lines of code, that used the this
keyword:
console.log(this)
console.log(this.firstName + " " + this.lastName + " is driving a
car.")
What we should really be focusing on, are the two lines of code where we are calling the
functions:
ImAFunctionNotAMethod()
john.driveCar()
On this second line of code, the object that is calling or executing the function is the john
object. So that's the object that the this keyword is going to point towards, inside that
function.

Now, here's where the confusion comes from. You might be thinking to yourself: well, this
line of code - console.log(this) - lives inside that driveCar function, so why is the this
keyword also not pointing towards john?

Well, the answer is because that's not the context in which this function is actually being
called, or executed. The only reason that this function ever actually runs is because we are
calling it right here - ImAFunctionNotAMethod() -.

Now, on this line of code - john.driveCar() - it's painfully obvious which object is calling,
or executing the driveCar method. But on this line of code - ImAFunctionNotAMethod() -
it's not as obvious (It's not like there's an object in front of it and then a dot). So in cases
like this, when we are calling a regular old function, javascript essentially says: Let's say
that it's the global object that is calling, or executing this function. So that's what the this
keyword gets set to, when the function runs.

Don't worry, I do not expect you to fully grasp this yet. My only goal, right now, is for you
to just be aware that the this keyword exists, that what it points towards changes, depending
on the context, and that it's a source of confusion for developers of all different skill levels,
not just beginners.

In the future, when you are creating applications I guarantee that you're going to run into the
this keyword. And I can also guarantee that, at some point, your code is not going to work
the way that you want it to work. And there's a good chance that it's because the this
keyword is not pointing towards what you think it's pointing towards.

Don't worry this is a concept that we can review and practice again later on in the course.

Why we would use the “this” keyword

Now, really quick, before we bring this lesson to a close I want to answer the question of
why. Why does the this keyword even exist? We just spent a lot of energy trying to
understand how to use it, but what about, why we would use it?

So let's give ourselves a quick goal. Now, right now, we just have this one object named

55
john, but imagine we had 500 other objects that represented people, and cats, and dogs. And
imagine that we wanted to give all of those objects a method named breathe. And maybe
the breathe method logs out to the console a message that says their name, and then it says:
“they just inhaled and exhaled”.

Now, technically we could just type out a function like we did for driveCar and then copy
and paste it into all 500 objects, but that would be terrible code. So let me show you what
else we can do.

maybe down here let's create a brand new function. Let's call it breathe() .

Now, if you're more experienced in programming and you're just watching these lessons as a
review, you might be screaming at the screen right now, wondering why I wouldn't just use
a prototype or class syntax and inheritance. But those are concepts that we have not
gotten to yet in this course. So bear with me.

So we've got this new function and imagine inside that we say:
function breathe(){
console.log(this.firstName + " " + this.lastName + " just inhaled and
exhaled.")
}
So now, we've got this new function named breathe.

Now, what if we want to let our john object use the breathe function, so we would expect it
to say: “John Doe just inhaled and exhaled.”

Well, at first glance this function looks hopeless, because it's a standalone function, not a
method that belongs to an object. Meaning, how in the world do we expect this to point
towards anything meaningful? If we tried to call, or execute the breathe function down
here, because it's just a regular old function, JavaScript is going to consider the global
object, the object that is calling it. Meaning that's what the this keyword is going to get set
to, the global object, and clearly there's no firstName and lastName properties attached to
the global object.

However check this out: here's an example of why it's so amazing to be comfortable with
the this keyword.
breathe.call(john)
we can begin with our breathe function, and in JavaScript a function is an object, just like
any other object or entity. And functions have access to a method named call(), so we can
include the name of our function and then, instead of parentheses – breathe( ) - right after
it, to call it directly, we can say: – breathe.call( ) - and the call method is going to call, or
execute our function, but not before first giving us a chance to control the this keyword,
meaning whatever we place inside these parentheses here. Call will make the this keyword
point towards that. So if we want our john object to be able to use the breathe function,
well, this function would make a whole lot of sense if that this keyword was pointing
towards John. So inside the call parentheses, so let's just pass in our john object.

56
let john = {
firstName: "John",
lastName: "Doe",
driveCar(){
function ImAFunctionNotAMethod(){
console.log(this)
}
ImAFunctionNotAMethod()
console.log(this.firstName + " " + this.lastName + " is driving a
car.")
}
}
john.driveCar()

function breathe(){
console.log(this.firstName + " " + this.lastName + " just inhaled and
exhaled.")
}
breathe.call(john)

And now if we check the console: “John Doe just inhaled and exhaled”. Awesome!

So maybe now you're starting to see the purpose of the this keyword. It allows our code to
be flexible. If we had another object named Jane or Meowsalot or Barksalot we could
just, as easily, include that here, and thanks to the this keyword this function is flexible
enough, that it would still make sense, and work perfectly.

In the future, we will learn about other situations where you use the this keyword that are
even ten times more useful than this example.

Okay that's going to bring this lesson to a close. To be fair, you probably didn't need to
know this much about scope and context this early on in your JavaScript career. I usually try
to err on the side of protecting you from complicated topics early on. But really, I just feel
like scope and context are such a common source of confusion for developers, that even if
none of this makes sense right now, we at least planted these seeds in your mind. And
maybe a week or two down the road, if your code is not working, and you're super confused
and frustrated, maybe a little light bulb will go off in your mind, and you'll go, aha maybe
it's scope that's causing the problem, or maybe it's context that's causing the problem. And
you might even need to come back and re-watch this lesson. But, big picture, I think you're
going to be happy that you learned about these topics.

Now, looking ahead to our next lesson we are going to learn about miscellaneous features of
the JavaScript language, that are super useful, but maybe didn't need an entire video just for
themselves. So it's gonna be sort of a fun grab bag of useful tips and syntax and tricks. It's
going to be a much shorter lesson than this one, I promise you that. So let's keep our
momentum rolling and I will see you in the next lesson.

57
1.9 Miscellaneous Info
In this lesson, we are going to learn about five or six different topics that are all important,
but maybe each one didn't deserve its own standalone dedicated lesson. Okay now, without
further ado let's jump into the first topic

Anonymous functions
so what in the world is an anonymous function? Well, throughout this course usually when
we create a function we give it a name. So we would say:
function myCoolFunction(){
}
well as the name suggests, an anonymous function would simply be if we got rid of the
name. So if we just had this:
function(){
}
Now, at first glance you might think: well, what is the point of this? if it doesn't have a
name, how can we ever call or execute it later on in our code? Well, let me show you an
example of when we could use an anonymous function.

So, let's give ourselves a goal. Let's imagine that we want to set things up so that whenever
the user clicks anywhere on the webpage, we want to show an annoying alert popup
message that says “thank you for clicking”. Now, we've already done this in an earlier
lesson, but this time I want to show you how we can use an anonymous function.
document.addEventListener("click", b)
So because we are speaking JavaScript in the web browser environment, we have access to
the document object, and we can look inside it and call the addEventListener method. And
then remember, we give this method two arguments: the first is the event that we want to
look out for (in this case click); and then the second argument is a function that this method
will call at the appropriate time.

Now, up until this point in the course we've always included the name of a function here.
And then maybe, created that function with the matching name down here, and that's a
great approach if you think there's even a 1% chance that you would ever need to call or use
that function somewhere else in your code, besides just this line.

But what if we're pretty darn confident that this is the only place where we would need to
use the function?

Well, in that case we can actually just include an anonymous function right here, for the
second argument. Or in other words, instead of just the name of a function here, we can
actually include the recipe for the function itself. so check this out: we can get rid of b, and
say:

58
document.addEventListener("click", function(){
alert("Thank you for clicking")
})
Okay now, if I come down to the preview part of the webpage and click anywhere in here...
awesome! we can see that that function successfully executed.

Now, again, because this is an anonymous function, it has no name, so we have no way of
referencing it or calling it anywhere else in our code, but that's not a bad thing if we don't
need to call it anywhere else.

Arrow functions
An arrow function is a special type of function that uses an alternate syntax, or we could
say a cleaner, or more minimalistic syntax, and it also has a few other key differences from a
traditional function.

But first let's start with the syntax of an arrow function. So check this out. It's very easy to
convert this traditional function into an arrow function.

We begin by removing the word function, but keeping the parentheses. Okay now, in
between the parentheses and the curly brackets we include an arrow symbol ( => ) and that's
all we need to do.
document.addEventListener("click", () => {
alert("Thank you for clicking")
})
So congratulations you just created your first arrow function.

Now, believe it or not, but we can actually make the syntax for an arrow function even
cleaner, or even more minimalistic.

So let's do this inside the curly brackets for our function let's not jump down to a new line
like we usually do, to put it all up on a single line.
document.addEventListener("click",()=>{alert("Thank you for
clicking")})
And now, with an arrow function, if the body of your function sits on a single line, we
actually do not need the curly brackets surrounding the body.
document.addEventListener("click",()=>alert("Thank you for clicking"))
and if we test out our code and click down here, we see that it works just the same.

So, an arrow function really lets our code be a bit cleaner.

Now, there are two more features of the arrow function that I want to show to you.:

The first feature is that when the body of our function sits on a single line like this, the
arrow function is automatically going to return whatever we include here. Now, in this case
we don't need to return the alert message, but in the case where you do want to return a
value, this can save us even further typing and let our code be even more minimalistic. Let

59
me show you what I mean:

let's imagine we have an array myNumbers. Now, let's imagine we want to use the map
method to create a brand new array, where each item from this array has been doubled. So
we could create a new variable to store the new array, we could call it doubledNumbers
and set it to equal the original array myNumbers, and then call the map method, and now
(practice makes perfect, so let's do this) within these parentheses let's first include an
anonymous function, that's just a traditional function, and then we can practice converting it
into an arrow function. So for an anonymous function that would spell out the word
function, and then parentheses, curly brackets. We know that each time the map method
calls our function it's going to pass into it, whichever item from the array it is looped to, so
within our function parentheses we want to include a parameter to work with the current
item. And then, in the body of our function we would just return that number, or that
parameter times two, to double it.

So now, let's test this out. Let's log out to the console our new array.
let myNumbers = [10, 500, 2000]
let doubledNumbers=myNumbers.map(function(x){
return x * 2
})
console.log(doubledNumbers)
And if we check the console, we see that the numbers from the original array were
successfully doubled.

Now, let's make it our goal to turn this into an arrow function.
• So first we just get rid of the word function, but we keep the parentheses with our
parameter.
• Then in between the parentheses and the curly brackets we include an arrow
symbol.
• And then let's adjust it, so that the body of the function sits on the same line.
• If it sits on a single line, we don't need the curly brackets.
• Also, if it sits on a single line, we do not need to include the word return here
(return is just sort of implied in this sense).
• And another tip to clean up our code, we do not need the parentheses around our
parameter if it's just one single parameter (we only need the parentheses if we have
zero parameters, or if we had multiple parameters)
let myNumbers = [10, 500, 2000]
let doubledNumbers=myNumbers.map(x=> x * 2)
console.log(doubledNumbers)
Now, at first this syntax looks really weird, because it's not what we've practiced throughout
the course. However, as we can see it has the potential to really clean up our code. Instead
of having a separate function down here, with the word function, and a function name, and
parentheses, and curly brackets, and the word return, we literally just have these few
characters.

60
Now, there's just one more feature of the arrow function that I want to show you.

This example should look familiar from our previous lesson, when we were learning about
context, and the this keyword. And right now I want us to focus on this inner function (in
black).
let john = {
firstName: "John",
lastName: "Doe",
driveCar(){
function ImAFunctionNotAMethod(){
console.log(this)
}
ImAFunctionNotAMethod()
console.log(this.firstName + " " + this.lastName + " is driving a
car.")
}
}
john.driveCar()

Because remember in this context, that this keyword is pointing towards the global object,
instead of the john object, and this behavior of JavaScript can be confusing, it can seem
unintuitive. But that's just the way it is. When we call a function that doesn't belong to an
object, or I should say, when we call a function that isn't a method, javascript considers the
object that is calling, or executing that function to be the environments global object. So
that's just review, we learned that in the previous lesson.

Now the question is: what if within this function we really, really wanted the this keyword
to point towards john.

Well, we have a few different options. We could use the call method that we learned about
in our previous lesson. But remember, the topic at hand right now is arrow functions.

So the final feature of arrow functions, that I want to talk about, is that they do not have
their own new this keyword. So if for whatever reason, we really wanted to break our code
up into an inner function like this, and we really wanted that this keyword to still point
towards the john object, we could just use an arrow function.

so I'm gonna get rid of this entire function declaration. I'm going to keep the call to the
function but I will get rid of the function declaration, and if we instead could create a
variable and call it I'mAFunctionNotAMethod and set that variable to equal an arrow
function. And just as a test I will log out to the console the this keyword inside of this
function.

61
let john = {
firstName: "John",
lastName: "Doe",
driveCar(){
let ImAFunctionNotAMethod=()=>console.log(this)
ImAFunctionNotAMethod()
console.log(this.firstName + " " + this.lastName + " is driving a
car.")
}
}
john.driveCar()
Okay, we're still calling it just like a regular old function, but if I check the console right
above “John Doe is driving a car” we see that this keyword is pointing towards our John
object instead of the global object. Awesome!

The reason this happens is because arrow functions do not have their own new this keyword
the way that a regular traditional function does. And arrow functions use the same variable
lookup strategy, that we learned about in the previous lesson with scope. So JavaScript is
going to say: okay, does the this keyword exist within this current local scope or within the
body of this function? No, it doesn't. So I'm going to look one level up, or one level outside
of this, which would be the block for our driveCar method, and we know that inside that,
we know that the this keyword does exist, and it's pointing towards exactly what we would
expect it to point towards, the john object.

I know that was a bit of a ramble, but this can be a really confusing topic so I wanted to go
over it in slow motion. So long story short, a simpler way of wording this is that arrow
functions do not change the value of the this keyword. Whatever the this keyword was
pointing towards in your current context, that's still what it's going to be pointing towards,
even inside of your function.

And this makes arrow functions a really nice tool to have up our sleeve.

function hoisting
Well, let me show you an example. Let's imagine we have a function named cool(), and
maybe it just logs out to the console a bit of text that says “this is super cool”. Okay now,
imagine right above this function declaration, up on the very first line, I try to call the
function.
cool()
function cool(){
console.log("This is super cool.")
}
If I check the console, we see: “This is super cool.”

So our code is working successfully. However, the only reason this code works is because of
function hoisting. What I mean by this is, usually the ordering of our lines matters in
JavaScript.

Like if down here, I created a variable called strawberryCount and set it to a hundred, I

62
can only access the strawberryCount variable, below this line of code. I can't expect to be
able to access strawberry count, before it's been created.

So if above this line I tried to log out to the console strawberry count
cool()
function cool(){
console.log("This is super cool.")
}
console.log(strawberryCount)
let strawberryCount= 100

and then try to check the console we see:


uncaught reference error: strawberryCount is not defined.
So clearly the ordering of our lines matters. So the question is: why are we able to call this
function before we've even created the function?

Well, the answer is because JavaScript has something called function hoisting. As far as
javascript is concerned this section of code (the function declaration) might as well be up, at
the very, very, very top of our code (hence the name hoisting). We can consider this code
(the function) hoisted, or moved up to the very top, even though it's not there physically in
our code.

However, not all functions get hoisted. So yes a function declaration like this will be
hoisted. A function declaration is where we actually use the keyword function and give it a
name. But we know that there are other ways to create a function. So check this out: what
if instead, we create a variable and call it cool, and set it to equal an anonymous function,
and then we try to log out to the console and say: “Hey!”.
cool()
let cool= function(){
console.log("Hey!")
}
Well, if we check the console, we just see:
uncaught reference error: cool is not defined
So just be aware, that unless you create a function with the actual keyword function and
then the name, your function is not going to get hoisted.

So in this case with this example, we would need to call the function below where we are
creating the function, like this:
let cool= function(){
console.log("Hey!")
}
cool()
Now it works just fine.

So big picture: with the traditional function declaration, you can get a bit lazy with the
ordering of your lines. But if you create a function in any other fashion, you need to pay
attention to your line order.

63
template literals
So, let's imagine we have a variable called myName, and we set it to equal whatever your
name is, and then imagine we want to log out to the console a bit of text that says: “hello my
name is blank”, and then it pulls in the variable, and then we also add on “and the sky is
blue”
let myName="Brad"
console.log("Hello, my name is " + myName + " and the sky is blue.")
So, if we check the console, all together we see that that pulls in the value for the myName
variable. So our code is working as we would expect.

But this syntax can be really awkward. I'm sure, if you're being honest, there was a point
throughout the course so far, where you got frustrated with the having to open up a quote,
and then close the quote, and then plus symbol, variable, plus symbol, new quotes... It just
gets awkward to type, and it's not ideal.

So right now, I want to show you a new tool called a template literal, which is going to
make our life a lot easier.

So let's get rid of this entire string of text ,and instead use two back ticks (``). So instead of a
string of text, we would call back ticks like this, a template literal, but really we can just
think of it as a string of text with superpowers. So check this out:

We want to do something dynamic, we want to include an expression, or we want to pull in


the value of this variable. So within a template literal, when you want to do something
dynamic, you just include ${ } and inside here we can include an expression - ${ 2 +2 } - or
what we really want to do is just pull in the variable.
console.log(`Hello, my name is ${myName} and the sky is blue.`)
Awesome! So that gets the job done, and in my opinion, this is so much easier to type out
and work with.

semicolons
so let's give ourselves a goal. What if we wanted these two lines of code here, to be
squished together, and just sit on a single line of code, that's really long?
let myName="Brad"; console.log(`Hello, my name is ${myName} and the
sky is blue.`)
If we just place a semicolon ( ; ) to separate the two lines, everything's fine. This is
perfectly valid JavaScript code.

So the idea is that a semicolon is sort of the period at the end of a javascript sentence. It's
our way of taking a breath, or letting JavaScript know that this thought is complete.

Now, here's the interesting part:

Without the semicolon here, the code break. But if we just drop down to a new line (like

64
was berfore), everything is fine, this code will run perfectly. This is because the JavaScript
language has something called automatic semicolon insertion, meaning behind the scenes
javascript is going to automatically add a semicolon here, for us.

So as long as we keep our code organized, with line breaks, and whitespace, we don't need
a semicolon here.

Now, I do want to let you know that this is just my personal subjective opinion. In the
JavaScript community, this is one of the most hotly debated arguments of all time, the
debate of whether we should include a semicolon here or not.

Now again, if our code is squished together on a single line, there is no debate, we flat-out
need a semicolon here, or JavaScript cannot make sense of what we're trying to do.

The debate is if we stay organized with whitespace, and line breaks, do we omit the
semicolon here and let JavaScript automatic semicolon insertion do its job? or do we
manually include the semicolons? Now, I don't want to brainwash you and tell you to never
use semicolons, I'm just letting you know that that's my personal preference. So you're not
going to see me use semicolons in the course.

In our next lesson day 10, the finale of this first chapter, we are going to finally build
something practical and concrete. We are going to use the web browsers objects and
vocabulary or lingo, to build a simple to-do list web application. This is going to leverage
everything we've learned so far in the course.

It should be a lot of fun and something that you can show to your friends and family. So
let's keep things rolling and I will see you in the next lesson.

1.10 Building To-Do App


In this lesson we are going to finally move from theoretical to practical, or from abstract to
concrete. I want to begin by showing you the finished product of what we are going to build
together in this lesson:

• So we've got a headline: To-do App.

65
• And then we have a form or input field, which I can type into: “feed cat”,
• submit it. it gets added to this Need to do list. And I can add a few others.
• if I want to get rid of one (maybe I completed that task) I can just click the delete
button, for that one.

This app is very simple, there's not a whole lot going on here. However, it gives us enough
to sink our teeth into, for us to really learn a lot about front-end JavaScript and working with
the web browser. So without further ado, let's jump right into the action.

HTML
Go ahead and create a brand new Codepen. And instead of JavaScript let's actually begin
with a bit of HTML.
• An h1, that reads “To-Do App”.
• A <form> , inside this form, let's give it two things, a text input field for the user to
type into, and then a button that they can click on, to submit the form.
• So to create the field <input>, let's give it a type of text, I'm also going to set its
autocomplete to off just, because I don't like the annoying little popup on the
field, that tries to suggest things that you've typed in the past.
• let's include the <button> that the user clicks. And let's have the button read
“Create item”
• An h3 that reads “Need To Do”
• A bulleted list with a few hard-coded example items. So <ul> for unordered list
• inside, let's create a couple of list items. Ultimately we want the user to create these,
we don't want to preemptively hard-code them, but let's just do this to give ourselves
something to work with. So I will say “buy carrots”
• and then we want to include a <button> here, that says “Delete”
• and I'm just gonna copy and paste this a few times, just so we have something to
look at. So maybe “buy apples”, “buy lettuce”

So this is our basic user interface for the app.

66
Now, when a user visits the app we don't want there to actually already be items like this.
We would expect this to be empty, and then the user would use the input form to add the
items. So big picture: it's the job of HTML to display content on the web page, but it's the
job of JavaScript to make this come to life.

Now, before we jump right into the JavaScript column and start coding, let's first adjust our
HTML to give the form element a unique identifier. In other words, we need some sort of
way to hook on to this form in JavaScript. so in our HTML on this opening form tag we can
just give it an id, so maybe say: id=”ourForm” , the idea here is that now we can search for
the element that has this id over in our JavaScript.

Also, we are going to need to be able to access the input field from within our JavaScript.
so let's give it an unique Id so we have something to hook on to. Right after the word input
let's give it an Id= “ourField”.

Also, we need to give the unordered list an Id, so that we can hook on to it from within our
JavaScript. So on the opening <ul> tag just say Id = “ourList”.

<h1>To-Do App</h1>
<form id="ourForm">
<input id="ourField" type="text" autocomplet="off">
<button>Create item</button>
</form>
<h3>Need To Do</h3>
<ul Id = "ourList">
<li>Buy carrots <button>Delete</button> </li>
<li>Buy apples <button>Delete</button> </li>
<li>Buy lettuce <button>Delete</button> </li>
</ul>

JavaScript
Now, in the past we've learned about the document object, which represents the webpages
content and abilities. And in the past when we wanted to be on the lookout for an event, we
would use addEventListener. This is how we would listen for click events.
document.addEventListener()
However, in this case, we don't want to use addEventListener for the web page as a whole.
So we don't want to use it directly on the document object. Instead, we want to select just
that one particular <form> element. So check this out:
document.getElementById("ourForm")
For the argument we just give it the Id, so we called it ourForm. And this method is going
to return an object that represents that HTML form element. Now, since that's what this
method is going to return, we could just add a dot here and say addEventListener(), all on
one line:
document.getElementById("ourForm").addEventListener()
But instead, what I like to do is save the object, that this is going to return, into a variable:

67
let ourForm = document.getElementById("ourForm")
This way our code just stays a little bit easier to read.

So then, on a brand new line we can say:


let ourForm = document.getElementById("ourForm")
ourForm.addEventListener("click", ()=>{
alert("thanks for clicking the form")
})
Just as a quick test, because we are familiar with it, let's pass it click, and then remember,
the second argument is the function that you want to run when this event happens.

So let's just use an arrow function: so parentheses; and then the arrow symbol; and then
curly brackets; and we can drop down inside the curly brackets, and just as a test when
someone clicks anywhere on the form, let's show an annoying alert popup message that
says: “thanks for clicking the form”.

Okay, now let's test out our code. If we come down to the preview area, notice that if I
click somewhere random on the webpage like the title, nothing happens; but if I click on to
the form, we see the alert. Awesome!

I think you can already see, that adding an event listener to a particular element, instead of
the document as a whole, this already opens up so many doors.

Now, we don't actually want anything to happen when the user simply clicks on to the form.
So instead, the event that we want to be on the lookout for, is actually called submit.

So up in our JavaScript code instead of click, let's say submit. So anytime the user submits
this form, we want to do something in response.

However, the default behavior of a web browser when you submit a form is, that it's going
to try to send that data off somewhere. In this case, we want to handle things completely
from within our JavaScript, so we don't want the web browser to try and send the data
anywhere.

So what we can do is: within the parentheses for our function let's include a parameter (I'm
going to call it e - from event, because the add eventlistener method is going to pass our
function a bunch of information about the event that just happened -). And then, inside the
body of our function, basically we want to say: e.preventDefault( ) , to call the method.

I realize this is a bit confusing, and not very intuitive. It's just one of the intricacies of the
web browser, that we have to deal with. It's default behavior is to try and refresh or reload
the webpage and send that data off somewhere. We don't want that to happen, so we are just
preventing it.

68
let ourForm = document.getElementById("ourForm")
ourForm.addEventListener("submit", (e)=>{
e.preventDefault()
alert("thanks for clicking the form")
})
Okay now, let's check out our app again. So now I'm free to click on to the form and
nothing happens, but as soon as I try to submit it... Awesome! we see our alert.

Okay now next, we don't actually want to show this annoying pop-up. So when the user
submits the form what we really want to do is grab the value of whatever they typed into
this field, and then add it as a new item into the list.

We can access this input field from within our JavaScript, becouse we gave it a unique
Id=”ourField” in the html file, so we have something to hook on to.

So then over in our JavaScript, just like we did with the form, remember, we created a
variable that stored the object that represents that HTML element. Let's do the same thing
for ourField.

So up here, I'm going to say:


let ourField = document.getElementById("ourField")
Okay now, in our function that runs when the form gets submitted, instead of this annoying
alert pop up, just as a test let's log out to the console whatever the user has typed into that
input field. We want to practice accessing the users input. So we know that that field is
represented by this ourField object, so we can just say ourField, and in the web browser
the object that represents that form field has a property, so we can look inside the object for
the property named value.
let ourForm = document.getElementById("ourForm")
let ourField = document.getElementById("ourField")
ourForm.addEventListener("submit", (e)=>{
e.preventDefault()
console.log(ourField.value)
})
Let's test this out. So back on our web page, be sure to open up your console. If I type into
this field “hello there” and submit... Awesome! In the console we see “hello there”.

Now we don't actually want to just log it to the console. What we really want to do is add
a new item to the bulleted list.

Because we gave this unordered list an Id = ”ourList” in the HTML file, we can hook on
to it from within our JavaScript.

So in our J's code, up at the top let's create an object that represents that unordered list
element:
let ourList = document.getElementById("ourList")
Okay now, we could write the necessary code right within this arrow function, but I want to
stay organized. So down at the very bottom of our code, let's create a brand new function
and name it createItem .

69
function createItem(){ }
Okay now, up in our arrow function, instead of logging to the console that value that the
user typed in, instead, we just pass it to our new function createItem.
createItem(ourField.value)
Okay now, if we are passing this - ourField.value - as an argument into the function, we
want to be able to receive it as a parameter. So in our createItem(x) function let's just
include an x, or something easy to type for the parameter.

okay now here's the fun part. In the body of this function let's select our ourList object
(remember, this object represents that bulleted list) and then let's look inside it, and call a
method named insertAdjacentHTML( ).
function createItem(x){
ourList.insertAdjacentHTML(a, b)
}
So we give this method two arguments:

The first argument is where in the element do we want to add the new bit of content. Well, I
would expect that a new item gets added to the very end of the list, so in our code for the
first argument I'm going to say “beforeend”;

And then the second argument is just the content or HTML that you want to add to this
element. So we could just say a string of text that says” hello” or some sort of test, but
instead we know that we can just include our parameter here, because this parameter
represents whatever the user typed into the field. Because that's what we're passing into our
function - createItem(ourField.value) -. so for the second argument I'm just gonna say x.

let ourForm = document.getElementById("ourForm")


let ourField = document.getElementById("ourField")
let ourList = document.getElementById("ourList")

ourForm.addEventListener("submit", (e)=>{
e.preventDefault()
createItem(ourField.value)
})

function createItem(x){
ourList.insertAdjacentHTML("beforeend", x)
}
Now let's test this out. So if we come down to our app I will type in “wash my car” and
then submit the form. Awesome! it gets added to the end of our list.

Now, it doesn't look quite right, and that's because we need to wrap it in an <li> tag just like
we did with the other elements.

So let's actually go back into our HTML, and we don't need these <li> examples anymore.
We want the list to be empty when the user comes to the app. But why don't we copy and
paste one of them as an example to save ourselves a bit of typing in the JavaScript. And then

70
we can get rid of all of these hard-coded items. But keep the empty hollowed-out unordered
list.
<ul Id = "ourList">
</ul>

Okay, and then back in our JavaScript down in our createItem( ) function, instead of just x,
we want to add a bit of HTML.

So here's what I'm going to do:

Inside this function - createItem(x) - let's create a variable and call it ourHTML. And
then let's create a template literal. So two backticks; inside the template literal, let's just
paste in our clipboard (so this is the template for an item), and then we want to do
something dynamic, so in a template literal you can say: ${ }, and that is where we would
pull in the x parameter, whatever the user typed in.

okay so now we have this HTML template for the new item we saved it into this variable -
ourHTML - so down here instead of adding x into that unordered list, let's just add our our
HTML variable - ourHTML -.
let ourForm = document.getElementById("ourForm")
let ourField = document.getElementById("ourField")
let ourList = document.getElementById("ourList")

ourForm.addEventListener("submit", (e)=>{
e.preventDefault()
createItem(ourField.value)
})

function createItem(x){
let ourHTML =`<li> ${x} <button>Delete</button> </li>`
ourList.insertAdjacentHTML("beforeend", ourHTML)
}

So let's test this out. Down in our app let's say: “feed cat”, submit. Awesome!

Let's do two more things:


• First let's set it up so that when you submit this form, it erases the current item that
you've typed. Because if we successfully added “buy carrots” to the list, we don't
need that in the field anymore. We want to be able to just type a new item in,
instead of having to select it and delete it.
• And then, let's also make it, so that when you click the delete button for one of
these, something actually happens.

Auto clearing the field when you submit it

So up in our code, inside our createItem function, why don't we just add a new line and
say:

71
ourField.value = ""
ourField (the object that represents that element), let's look inside it to access its value, and
then let's just set its value to equal an empty string ( “” ).

Okay, also if the user clicks the submit button, instead of hitting Enter or return on their
keyboard, I think it would be cool, if when they submit, if the text field got automatically
selected or focused again, so that, if they wanted to add another item, they wouldn't need to
manually click the field again, it would just already be selected and ready for them to type.

So in our code we can also say:


ourField.focus()
we call a method named focus.

Okay, let's test this out and see how it works:

so, “buy carrots”. ENTER, It got rid of it for me, and I can just keep typing;

“ feed cat”, and even if I use the submit button this, it automatically selects it. Awesome!

The delete functionality

So we want to respond to the event of the delete button getting clicked. Now, our first
instinct might be to try and use the addEventListener method, so maybe try to select all of
the delete buttons, and then call addEventListener, but we would run into an issue. And
that is, that when the app first loads, or when the web page first loads, there aren't going to
be any items, so there would be no delete buttons, and in JavaScript you cannot add an event
listener to something that doesn't exist yet.

Now, there are several ways around this problem, this issue of adding events for future
elements that don't exist yet. But right now, I'm going to show you probably the simplest
way of handling it.

Down at the very bottom of our code, let's create a brand new function:
function deleteItem(){
alert("Delete requested")
}
just as a test let's create an alert pop-up that says “delete requested”

Okay now, the question is: how can we run, or call, or execute this function when the user
clicks on one of the delete buttons?

Well, in our createItem function, remember this line of code where we are creating the
HTML template for an item?
`<li> ${x} <button>Delete</button> </li>`
Well, here's the HTML for the delete button. So check this out:

72
`<li> ${x} <button onclick="deleteItem()">Delete</button> </li>`
On the opening button tag we can just say onclick equals and then we can just give it a little
bit of code to execute, so we can just say deleteItem( ), to call that function.

So, let's test this out:

down in our App, if I add an item... “by carrots”, and if I click the delete button...
Awesome! We see that “delete requested” pop-up.

Okay now, we don't actually want to show a pop-up, what we really want to do is delete
this list item from the list.

However, imagine we have maybe several items in the list. When we click a button, we
need to know which item just got clicked on. We need to know which list item to delete.

So check this out:


`<li> ${x} <button onclick="deleteItem(this)">Delete</button> </li>`
Within our HTML template, inside the parentheses for deleteItem( ), when we're calling it,
we can just say ( this ). because the web browser considers each HTML element an object,
well, when this function runs - deleteItem( this) - , what is the object that is calling it? You
guessed, it it's the element (the button). So if JavaScript considers that, the object that is
executing this function, that's what it's going to set the this keyword to. Awesome!

So that means the element that needs to get deleted from the page - ( this ) - , is going to get
passed into our function - deleteItem( ) -

So in these parentheses we can create a parameter, I'm going to call it elementToDelete.


Okay, and then, instead of that annoying pop-up, let's just access that element.

So elementToDelete, now this is going to point towards the delete button, they got clicked,
but we don't just want to get rid of the delete button, we want to get rid of the entire bulleted
list item. So we can just say: - elementToDelete.parentElement - and that's going to
select the HTML element that is housing this element.

Okay, so once we've selected that, then we can just call -


elementToDelete.parentElement.remove() - to remove the element.

73
let ourForm = document.getElementById("ourForm")
let ourField = document.getElementById("ourField")
let ourList = document.getElementById("ourList")

ourForm.addEventListener("submit", (e)=>{
e.preventDefault()
createItem(ourField.value)
})

function createItem(x){
let ourHTML =`<li> ${x} <button
onclick="deleteItem(this)">Delete</button> </li>`
ourList.insertAdjacentHTML("beforeend", ourHTML)
ourField.value = ""
ourField.focus()
}

function deleteItem(elementToDelete){
elementToDelete.parentElement.remove()
}
Altogether let's test it out:

“buy carrots”; “walk dog”; “feed cat”. And if I want to get rid of “walk dog”, let's click
delete. Awesome!

where we go from here


Now that's going to bring the hands-on portion of the lesson to a close, but let's talk about
where we go from here, because there's one huge glaring problem with our app, and that is
that every time the web page gets reloaded, or refreshed, all of the users items and data is
going to get reset.

If I come up to our code and even just add a couple of forward slashes to force Codepen to
reload the page, all of our data is gone.

Obviously, this is a big problem. So in the real world we would need to store this data
somewhere.

Now, we could save it to the user's physical device, using a web browser feature named
local storage, but that's not ideal because if the user switched from their phone to their
laptop, to their desktop, to their work computer, their data is not going to follow them
around.

So, in the real world the only practical solution for some sort of persistent data is to send it
to a server, or some computer that's “in the cloud”, in order to save it to a database.

23:30 Now, databases do not understand web page elements, meaning we can't exactly just
send a bulleted list of HTML content over to a database. Instead, we want to send raw
playing data like strings of text, or objects, or arrays. So that's why we spent so much time
in this chapter learning about the JavaScript language itself, and working with raw data.
Because, as we saw in this lesson, working with the web browser is relatively easy. The

74
challenge comes when we've realized that we need to manage two completely different
things. So, one is the raw data, for example write an array of the users items like this:
['buy carrots', 'walk dog', 'feed cat']
Servers and databases want raw data like this. But raw data like this doesn't mean anything
to the users that are actually using our app. So, the other thing that we need to manage is the
visual user interface. Now, managing those two different things at the same time can be very
overwhelming, and this is why libraries like react, and Vue Js, and Angular are so incredibly
popular. Now, ultimately, in the real world I do recommend using one of those libraries.
However, until you can clearly understand and describe the problem that these libraries are
solving, I recommend staying away from them, because I've seen countless beginning
developers suffer from the disease that is called:

“trying to learn everything at once and getting confused, and giving up”.

This is a disease that plagues millions of people around the planet.

Now, I'm not proposing anything extreme, I'm not saying that you need to be skilled enough
to create your own library before you use someone else's. I totally disagree with that line of
thinking. All I'm saying is, give yourself a chance to understand the bigger picture; how all
the puzzle pieces fit together. And at least, understand the problem that a library is solving,
before using said library. Because I guarantee, if you genuinely understand the need for a
library and how it fits into what you're trying to achieve, it makes learning the library 500%
easier, it makes it a piece of cake.

Okay, but learning a particular library is not the goal of this course. Our goal is to
understand the full scope, the full stack of an application.

In this lesson, we saw the general idea of how Java Script can control the web browser. So,
up next, in our next chapter, we're going to dive deeper into why we need a server, or at
least a third party service where we can send our data to.

Now, a lot of people get intimidated when they hear the word server, or cloud, but I can tell
you right now, that with the right guidance, there's nothing to be scared of. We're going to
walk through the server side of things together, and it's actually surprisingly simple.

So let's keep things going, because this is where our progress is just going to start
skyrocketing.

Course overview
1. Genuinely understand the language itself (abstract).
2. The web browser environment (concrete)
3. Node.js environment (concrete)
4. MongoDB environment (concrete)

We understand the basics of the JavaScript language itself. And now it's time to just see

75
how all of the different environments work together.

We just took a look at the web browser.

Up next we're going to learn about node.

And then eventually we can learn about MongoDB and how to save our data in the
database.

If you can seamlessly tie these three environments together, you are a full-stack developer,
and you are incredibly in demand. So let's keep our momentum rolling and I will see you in
the next chapter.

Congratulations on finishing the 10 days of javascript. In the full course we build an


application together, complete with user registration, users sign-in and sign-out, user
generated content asynchronous, or live on the fly actions in the browser, that are talking to
a server and database. And a whole lot more. The full premium course is not officially
launched yet, but if you subscribe to this channel you'll be notified as soon as it's out, or if
you're watching in the future, it's already available. Thank you so much for coming along
on this 10 or 11 day journey with me. I hope you feel like you learned something and stay
tuned for more web development tutorials take care.

2. Server Basics
Here's a quick summary of what we're going to learn:
• The basics of computer programming in general.
• The JavaScript language itself.
• The node.js environment, and how to use it to power a server.
• About the web browser environment, and how to use javascript to control it.
• What a database is, in particular how to use the MongoDB database system.
• How to relate one piece of data to another. For example letting one user follow
another user.
• How to update the browser in real time, with fresh data from the server.
• How to create real time two-way communication of data. We will use it to power a
chat room, but you could use the same technology to power a simple game, or just
about anything.
• About authentication, both stateful with sessions. and stateless with JSON web
tokens.
• About the MVC architecture pattern.
• What an API is, and then how to create our own API. And much, much more.

A cohesive course that you could start from scratch with, and follow all the way to the end,

76
in order to gain a big picture understanding about all the puzzle pieces fit together. A course
that explain the why, and not just the how.

I would love to have you come along on this journey with me, and if you're ready to launch
your career as a full-stack JavaScript developer, then I'll see you on the inside.

2.1 Why Do We Need a Server?


2:49

Let's take a quick look at where we are:


• We've learned the basics of the JavaScript language itself.
• We've also learned the basics of how to use javascript in the web browser
environment.
• And now, our next step is to learn how to use javascript in a server environment.

But why? So we need to ask ourselves a few questions. What is a server? And why do we
want to use one?

What is a server?
So when I visit google.com, my web browser sends off the request to the Google server.
And the Google server sends back a response with the HTML to display this page.

3:33 Now, when I search for something so if in the main Google field I search for JavaScript
my web browser sends off a request to the Google server with JavaScript as my search term
and then the Google server sends back a response with the data needed to display these
results so what is a server? Well, my own oversimplified answer is that:

A server is the thing that we can talk to, in order to send and receive data.

As a user of an app, or website, we can send requests to a server, and then the server sends
back a response.

For now that's as deep as we need to go in terms of what is a server.

Why we want or need a server?


I would say there are two main reasons:

1. Communication (let users acces our app). is directly related to what his server is
right communication our app needs to be a good listener right it needs to listen for
incoming requests and then it can send back a response or in other words we need a
way for our users to access our app and that's the case even if we're building the
simplest website ever even if it's just a simple brochure website that is literally just a
headline that says hello even in that case we still need a server that visitors can't
connect to in order to view the page even if that server is just serving up the file

77
system and sending back statically created basic HTML files it's still a server that's
listening for incoming requests.

2. Trusted enviroment for our code. If we want to build something a bit more
complex than just a static read-only brochure type of website, and we want to let our
visitors actually perform actions, instead of just viewing pages, we need a server of
some sort. And the reason for this is because we cannot implicitly trust the web
browser or incoming requests. Let me explain why and also just sort of what I'm
talking about. For example let's imagine that we wanted to use our bank's website to
transfer money from one bank account to another so instead of Google com imagine
right now I was logged in to my bank's website. Well, from a code perspective
perhaps the bank website would send a bit of JavaScript to me and my web browser
so maybe they would send over an object

money transfer and you don't have to type this out this is just for a quick explanation
there's no need to follow along with this code but maybe the bank server would send
over to me an object so say money transfer equals and they would set the from
account to whatever my logged in user is right and then the to account would be
whoever I wanted to send money to so they would probably pull this value from the
input field of whoever's name I bin and we could imagine there would be a property
named amount which again would pull in the value of a user input field of how much
I want to give to someone and then finally we could imagine there would be a
property named message which is a place for a memo or a brief description of the
money transfer.

Now, most people are not evil and most people are not familiar with code and their
browsers console however what if we were an evil or malicious user we could log
into our bank's website come into our browser's console and we could just change
this stuff programmatically right we could fire up our console and say money transfer
dot from account should not be the logged in user that I actually am it should be
really rich person Smith and the to account should be me give me the money and the
amount should be some disgustingly large amount and the message should be: “ha ha
ha, my money now”.

now, I could add that into my web browsers memory and then if I went back to the
bank screen I could click a button that says perform money transfer and if the bank's
server implicitly trusted me I would now be a very rich man right the request would
go through now obviously that's not the world we live in if server is implicitly trusted
you in your requests the world would spin out of control into complete chaos in about
two minutes the reason we have any sort of sanity in this digital age is because a
server has the job of making sure that you really are the person that you're claiming
to be now you might be thinking to yourself why couldn't we just use JavaScript to
send over an if statement to the web browser right we already learned how to make
decisions in our code so imagine the bank assigns you a variable when you first log
in maybe let user equal your name right and then maybe you think we could use an if
statement and say only if the following is true only if user equals money transfer dot
from account right so only if this is the case only if the user is who they say they are

78
then let the money transfer go through. Well, this line of thinking is good this is
similar to the line of thinking that we would use on the server side. The problem is
just that we cannot rely on this on the client side or the web browser side or the user
side, because there's nothing stopping a malicious user from simply saying well user
should equal really rich person Smith right they could modify the user variable in
their web browser and then this if statement would evaluate to true. Or better yet, a
malicious user could simply modify the JavaScript that you send over to them and
just get rid of the if statement check or a malicious user could just completely disable
JavaScript and their browser entirely. So getting back to reason number 2, of why we
want a server trust issues we need to run this decision-making code in a trusted
environment and we can never truly trust the users web browser so the idea is that
with a server we can write JavaScript code we can write if statements and all sorts of
things to make sure that it's a legitimate request. So long story short, a server is
really just a place where we can write code that cannot be tampered with or
manipulated by the user of the application.

And for now that's really as deep as we need to go in terms of why we want or need
a server.

Now, before we bring this video to a close, and start talking about our next steps, I first want
to address two common questions that you might have right now:

Question 1. you might be thinking, okay sure so you could write this if statement on the
server side but couldn't the user still just send along a fake user value and try to impersonate
someone and the answer is yes malicious users will try to do that however I don't want you
to worry about that right now we are absolutely going to learn about authentication later in
this core but I don't want you to burden your mind with it right now don't worry we have a
lot of tricks up our sleeves on the server side we can get creative in terms of making sure
that users are who they claim to be for now all you need to know is that if our app is even
going to have a chance of being secured we need to run our verification and authentication
code in a trusted environment not in an environment that the user is in control of so we need
a server.

Common question 2. hey Brad what about serverless applications? I keep hearing this
phrase serverless app it's a really popular buzzword right now there's a lot of hype
surrounding it so if an app can be serverless do we really need a server and my answer to
this question is that it's really just a matter of semantics serverless apps still use servers the
difference is that instead of writing an entire server and then pushing it up onto the internet
with a serverless app you're just writing individual functions and then you're handing those
functions off to a big company like Amazon Google or IBM and then those billion-dollar
companies are hosting your functions for you. It's the same idea though you are writing
server-side functions you are having a place that is trustworthy and private it's just that
you're letting some other company host or individual functions instead of you needing to
host your entire server yourself.

Now, if everything I just said made zero sense, and you've never heard of the phrase
serverless apps, that's okay, you can just forget the last 60 seconds ever happened. Rest

79
assured that later on in the course I will briefly talk about and explain serverless apps but for
now we do not need to worry about that.

node.js
And I can tell you with the utmost certainty that whether you want to create a traditional
app, or a serverless app, you are going to need to write server-side code. And in the
JavaScript universe, as soon as you want to start writing code outside the context of a web
browser, you need to learn about something named node.js. After the web browser, node is
by far, the most common or popular JavaScript environment.

Now, node can be used for just about anything, so I don't want you to think that it's just for
creating servers. That just happens to be one of its many use cases. Big picture: learning
about node is going to open up so many doors for us. And it's exactly what we're going to
start learning about in our very next lesson. This is an exciting portion of the course,
because when you start to learn about node you can legitimately call yourself a JavaScript
developer. So let's keep our momentum rolling and I will see you in the next lesson.

2.2 Node.js Intro


14:10

In this lesson we are going to get started with node.js. However, before we download and
install node on to our computers, let's first ask ourselves what exactly is node?

So very early in the course we learned that there are multiple environments in which we can
speak the JavaScript language. And each environment has its own unique made up words,
or slang, or lingo that relate to its super powers or abilities.

So, the web browser is a JavaScript environment, and it's special abilities include viewing
webpages and responding to user events like clicks and keyboard presses, so on and so
forth.

Well, Node.js is another JavaScript environment. And it's special abilities include things
like: being able to create new files and folders on your computer's hard drive; being able to
listen for incoming Network requests. And much, much more.

In other words, the web browser can do web browser'ish things, whereas node is more
open-ended, node can do general computer'ish things. For now that's all we need to know
about node. So that's enough talk for now. Let's get to the action.

Let's download and install Node.js


Here is the official node.js website: nodejs.org

From the website we want to download it. now, the version numbers that you see in this
video are going to be different when you actually visit the website yourself, because node is
constantly releasing new updated versions of the software. That's ok, your version number

80
does not need to exactly match my version number.

Now, there are two different download options that we see here: one with the absolute
newest latest and greatest features; and another one that is slightly older but is super
reliable, and stable, and dependable. Either download link will work just fine, you can't go
wrong, but personally I usually recommend the long-term support version. So go ahead and
click on that to begin the download.

Once the download finishes, go into your computer's downloads folder, and open up the
install file. All of the default options and the automated installer are okay, so you should be
able to just click next, next, next, without any trouble.

Once the Installer is complete, our next step is to make sure that node was successfully
installed. To do this we want to open up a command line on our computer (I know from
firsthand experience that when you first see a command line it can be terrifying, but whether
we like it or not, if we want to become a full-stack developer, we absolutely need to use a
command line, there's just no getting around it).

How do you open up a command line on Windows?


1. Open up the Start menu.
2. Start typing “command prompt”
3. It show up in the list of programs so go ahead and open it.

or another way:
1. Hold down the windows key and simultaneously press the R key. This will open up a
run prompt.
2. Click into the run prompt field and type cmd, and then push enter.

Now, I want you to type this in:


node -v
Push enter and in response your computer should output a version number of node, that
means you have successfully installed node.

If there was a problem when you tried to install node, you can try restarting your computer
and then opening up the command line and trying this again. Or you could try running
through the node installer file again. Or you might need to do a bit of personal Google
research. I'd recommend searching for: “install node.js problem windows 7, 8, 10”. And as
you're digging through Google results, I want you to be on the lookout for any
stackoverflow.com results. A common joke in the programming world is that developers
get paid to Google and find answers to the problems on Stack Overflow.

Our first taste of node


In the command-line I want you to simply type node, no space, nothing else, and then push
enter.

81
By doing that, we have now entered into an interactive node environment. In other words,
we can start speaking the JavaScript language, and our computer will understand us. So we
can say 2+2, and push enter, we see 4. this is very similar to earlier in the course, when we
first started to experiment with the web browsers console.

Basically, right now, we are in the node console. So we are free to speak the JavaScript
language. We could create a variable:
let myFavoriteNumber =10
push enter, that gets stored into memory. And then I could say:
7 + myFavoriteNumber
push enter. We see 17

Now, what if instead of just simple JavaScript language features, we want it to leverage
nodes unique abilities and superpowers? for example, what if we want to create a server
and listen for incoming network requests?

Well, doing that with node is relatively easy, but it's going to take more than just a single
line of code like this. And if we're going to be writing more than just single line code
examples, we really should be doing our typing in a dedicated text editing program, instead
of the command line, just like earlier in the course, when we moved from the web browsers
console into Codepen, so we could write multiple lines of code easily.

Now, we're going to move from our command line, into a text editing program. Ultimately,
the reason we are doing this, is so we can begin to do actually interesting and complex
things with node.

If you're scratching your head right now, and still not really seeing the point of node, and
you're not sure what the goal of all of this is, and why node is necessary, don't worry, that's
to be expected. I think the bigger picture of what's going on, is going to come into focus,
and become very clear over the next several lessons. Trust me, when we finally do
something interesting with node, and we see how that can interact with the web browser,
and how the puzzle pieces fit together, you are going to have an unbelievable aha moment.

Exiting node
To exit the interactive node environment in your command line you can just press: ctrl C
twice.

Or another way of exiting node is just to type:


.exit
It's not the end of the world if you don't exit node like this, but it should make closing your
command line window a bit easier.

2.3 Text Editor Software


24:33

82
hello everyone in this lesson we're going to make sure that you have access to a text editing
program on your computer before we worry about downloading and installing a text editor
let's first go over why we want one in the first place so in our previous lesson we installed
node J s and then we learned how to access it from our command line so if I type node I can
then start speaking JavaScript 2 + 2 you get the idea however if we want to do something
complex and interesting we are going to need to write multiple lines of code so almost as if
you were writing a play or a movie or TV show you would need to write a fairly long script
well it's the same thing here we want to be able to write a long script or a bunch of code and
then feed that all into note at once now the way that this is typically done is by using a text
editing program to create a JavaScript file on our computer's hard drive and then we can
feed that file into node now there are many many different text editor programs in the world
and many of them are free to use the program that I personally use and also that I strongly
recommend is named Visual Studio code it's also often referred to as vs code so you can
google for Visual Studio code or as of this recording the official website is code dot Visual
Studio comm it's completely free and completely safe to use and it's available for Windows
Mac and Linux it's the text editing program that I'm going to be using throughout the course
so if you want to follow along with me step-by-step I strongly recommend you also
download and install Visual Studio code a little bit later on in this very lesson I will explain
why I think vs code is such a great option however I don't want to be dogmatic so I don't
want to force my preferences or opinions on you there are many other text editors that you
can use for example atom is a very popular text editor that's also free also sublime text is
another very popular text editor technically it's not free it's available for purchase but you
can use it for free to evaluate it and decide if you'd like to buy it indefinitely the point that
I'm trying to make is that there are many many different text editing programs out there so I
don't want you to feel bad if you really don't want to use Visual Studio code however having
said that my opinion is that you should give it a try because I think it's amazing anyways
having said all of that right now I recommend you pause this video lesson while you
download and install vs code alright at this point I will assume that you've had a chance to
install vs code or you already have an existing text editor and you're fairly comfortable with
it so now let's give ourselves a goal of creating our first javascript file and then feeding it
into node now instead of just creating a JavaScript file directly on our desktop or in some
random folder why don't we create a new folder on our computer specifically for this
javascript file so it doesn't matter where we create this folder but for example on my desktop
maybe I will create a brand new folder and the name of the folder doesn't matter but I will
name it first node experiment you could name this folder testing or pizza or unicorn the idea
is that we just created a new empty folder and now I want to open this folder with our text
editor program so right now go ahead and open up vs code and there are several different
ways to open a folder in this text editor program so you can use the top left File menu and
just choose file and then either open or open folder or an even easier way is just in Windows
or Mac to find that new folder that you created and you can just drag and drop the new
folder on 2vs code so if you're on Windows you can just drag this folder onto the vs code
program window or if you're on Mac you can drag your new folder onto the vs code icon in
your dog okay now once you've opened that folder with vs code you should see a few
options right about here first of all we can go ahead and close the welcome screen or any
sort of welcome tabs okay and then this left hand middle menu that we see here here we see
the name of the folder that I just opened up and if I hover over that little tab I have a few

83
different options so this first icon will create a new file within that folder that's what I'm
interested in doing I want to create a new file in that brand new folder so you can either
click this icon here or you can click file new file it's up to you or you could even just right
click anywhere in this empty space right about here and choose new file at the end of the
day all we really want to do is create a new JavaScript file and the name doesn't matter I
will name it test dot J s the dot J s tells our computer that this is a JavaScript file so the first
part of the name doesn't matter you could name it Pizza J s or unicorn dot J s okay after we
create that file V s code opens it up and within this main part of the screen we can start
typing so just like before in the Codepen examples we are free to write multiple lines of
JavaScript within this new file so why don't you type this out and follow along with me let's
create a variable so let's say let strawberry count equal 20 okay then below this let's write an
if statement and say if strawberry count is greater than 10 log out a message to the console
that says you have enough strawberries otherwise else log out a message that says you do
not have enough strawberries so say if parentheses curly brackets within the parentheses for
our condition we can say if straw berry count is greater than 10 then within the curly
brackets we can drop down and say console.log you have enough strawberries okay and
then if this is false if strawberry count is not greater than ten down here after the closing
curly bracket we can just say else curly brackets log out to the console you do not have
enough berries okay then push ctrl s or command s to save this file or you can just use file
save and now the moment we've all been waiting for let's feed this file into node right so
instead of having the web browser execute this JavaScript code we want the node
environment to execute our code now in our previous lesson we learned how to run node
right you need to open up your command line however this is one of the biggest reasons
why I'm a huge fan of vs code while you're in vs code I want you to hold down the ctrl key
on your keyboard and simultaneously press the tilde key which is the key to the left of the
one key or it's also the back tic key the key right above tab so hold ctrl + the tilde key and
that opens up a command line directly within our vs code program this is incredibly
convenient and it makes our lives a lot easier you can also access the command line in vs
code by looking in the top view menu and then clicking on terminal now if I was not using
vs code I would need to open my command line like we did in our previous lesson right the
command prompt for windows or the terminal for mac but in vs code you don't need to
jump back and forth between two separate programs between your text editor and your
command line in vs code your command line is just conveniently right here another thing
that's cool is vs code automatically points your command line towards the current folder that
you're working in so usually in the command line you would need to say CD space and then
type out the directory of where you want point towards with vs code we don't need to do
that our command line is already pointing towards our new working folder so check this out
all we need to do to feed our JavaScript file into node is down in the command line right
node and then a space and then the name of our file so in my case that's test J s we actually
do not need to include the dot J s so you can just type the actual name of your file and then
push enter awesome we see you have enough strawberries and if we come up to our
JavaScript code and change the strawberry count to something really small like three and I
save the file and then I come down here and run that code again so I say node test you do
not have enough berries and again if you named your file something different than test J s
you would not say no test for example if you named your file pizza J s then in the command
line you would write node space pizza really all we are doing is passing our file into node

84
we're just saying hey node execute our file cool now there's nothing very interesting or
impressive about a simple if statement right however we now have everything we need to
really start rolling we've installed node onto our computers we have a text editor program
and now we know how to use the command line to feed a JavaScript file into the node
environment so I've got some good news this means that in our very next lesson we are
ready to use node to build our own small simple server this is where the big picture of what
we are trying to accomplish is going to come into focus I am so excited to write our first bit
of real-world node code with you so let's keep our momentum rolling and I will see you in
the next lesson

2.4 Our First Basic Server

19:53
hello everyone in this lesson we are going to create our very first server without further ado
let's jump right into the action so go ahead and make sure that you have the folder that you
created in the previous lesson open in a text editing program and here we can see that I have
opened the test J's file that I created in the previous lesson let's go ahead and erase or delete
everything inside that file and give ourselves a clean slate or if you wanted to you could just
create a brand new file within that same folder okay so we've got a clean slate what is our
goal for this lesson well we want to create a server that listens for incoming requests so that
we can visit that server in our web browser and have the server send back a response that
says something simple like maybe hello world or welcome to our web page so back in our
text editor the question is how can we use code to create a server the answer is that we need
to use environmental jargon so the first step is to realize that we are writing code for the
node environment not the web browser environment so back when we were writing code for
the web browser environments we could use the JavaScript language itself right the core of
the language we could say something like let favorite number equal 7 right and that's valid
JavaScript no matter which environment we are in however back in the web browser if we
wanted to do something web browser ish like respond to a click event or select an element
we needed to use special words like remember the web browser has an object named
document and document is not part of the JavaScript language itself it's just a word that the
web browser brings to the table so that we as programmers can leverage the environment
that we are in well we need to do the same thing with node so we are in the node
environment we want to do something no dish like setting up a server so we need to use
nodes special words so type this out with me HTTP and then we want to look inside that and
call a method named create server parentheses to call the method and just a quick note if
you're using vs code as your text editor like I am you might notice that when you type
HTTP it gives you all of these suggestions and if you try to type a dot right after that it's
going to use one of the suggestions so what you can do is type HTTP and then either hit the
Escape key on your keyboard to get rid of the suggestions or just push the arrow keys on
your keyboard to move around a little bit and then you can include the dot and then create
server parenthesis now HTTP is not part of the JavaScript language itself but just like the
web browser has the document object that we can leverage the node environment has this
HTTP object that we're going to leverage now we don't want the server that this method is
going to create to just float around in outer space so instead let's store it in a variable so at

85
the beginning of this line we can just say let and then I'm going to say our app equals but
you could choose whatever variable name you want you don't have to use our app you could
call it pizza or a unicorn or anything okay but the point is is that we now have this variable
that is a server and we know that the job of a server is to listen for incoming requests so let's
tell the server to begin listening so on a new line I'm going to say our app dot listen right so
just like way back in one of our very first lessons when we had a dog object and told it to
jump or we had a cat object and told it to meow in this case we have a server object and we
are telling it to begin listening next what we need to do is tell the server what exactly it
should do when it does receive a request right what should the server do in response to an
incoming request well that's exactly what these parentheses upon the first line of code are
for when we call the HTTP dot create server method we want to pass it a function as an
argument and then the server is going to run or execute or call that function every time it
receives an incoming request so you could make up a name for a function here and then
down here define a function with that matching name however since we don't really need to
call this function anywhere else why don't we just go ahead and create an anonymous
function right within these parentheses so I'm going to say function parentheses curly
brackets and feel free to drop down inside the curly brackets and actually before we start
writing the body of our function here let's first give our function two parameters so right
after the word function within these parentheses let's say req which is short for request and
then let's include a comma and include another parameter and name it our es which is short
for response technically you could make up any two names you want for the parameters but
these names make a whole lot of sense request and response okay and now within the body
of our function we can leverage the request and response objects that the server is going to
pass in to our function every time it calls the function now we will learn more about the
request object in a few minutes but for now all we really need is the response object so
remember our goal for this lesson when someone sends a request to our server we simply
want to respond by saying hello and welcome to our website so within the body of our
function let's use the response object and call a method named end right we want to end our
response by sending a little bit of text that says hello and welcome to our website okay now
before we save this file until node to actually run it there are two tiny details that we need to
address so first in the node environment whenever we use a special node word or ability in
this case HTTP we need to explicitly tell no to load or import or require in that functionality
or that ability so even though HTTP is part of node we still need to add a new line of code
up at the very top of our file and say let HTTP equal and then we tell node to load or import
or require in that ability so we just say require parentheses and in those parentheses we say
quotes HTTP node we'll know what we mean with this chunk of code and then we are
storing that functionality in a variable named HTTP so then in our code down here node
we'll know what we mean when we say HTTP okay there's only one more detail that we
need to take care of before we save the file and take it for a test drive down on our very
bottom line within the parentheses for the listen method we need to pass it a port number as
an argument let's say 3000 don't worry I do not expect this number of 3000 to make sense
right now but it will come into focus very soon okay now let's go ahead and save this file
and then let's use the command line to tell node to run or execute our file if you're using vs
code you can open up your command line by pushing control and the tilde key or you can
always click the View menu and then choose terminal okay in the command line let's say
node and then a space and then the name of our file so my file is named SJS yours might be

86
named something different so keep that in mind but after you type in node in the final name
push enter and now at this point our server is up and running right now I want you to jump
over to your web browser and let's try to send a request to the server so up in the address bar
type this in with me clear out the address bar and let's say local host local host is the address
for your own computer and then we can say : and then the port number that our server is
running on and remember we chose a port number of 3000 so local host : 3000 push enter
awesome there we see the response from our server hello and welcome to our website so at
this point we've accomplished the original goal of this lesson we created a server that listens
for incoming requests and it sends back a response well that didn't take too long so let's give
ourselves another new goal for this lesson so with a real-world website or web application
we know that you can visit different URLs to visit different pages for example a lot of
websites have an about page or an about Us page so if we came up into the address bar and
after the 3000 added a slash about and tried to visit that URL we still see the exact same
response so let's give ourselves the goal of sending back different responses depending on
the URL that the visitor is trying to visit how about if someone visits the base URL just
localhost 3000 we send back text that says hello and welcome to our home page and if they
visit maybe slash about we say thank you for the interest in our company so how can we
accomplish that well let's jump back into our text editor and this is a great time to learn
about the request object remember that every time the server receives an incoming request
it's going to run our function now we've already leveraged the response Bob that gets passed
into our function right we called response dot end to send back this response well now let's
leverage the request object that gets passed into our function the request object contains a
bunch of information about the current incoming request so if we want to be aware of which
URL the users trying to visit all we need to do is dig into the request object let me show you
what I mean within the body of our function here maybe right before this response dot end
line let's add a brand new line and say console dot log and what we want to log is req a
request and then dot and look inside it for a property named URL okay go ahead and save
the file and then we need to close or quit the current instance of node that is running our old
file or

our outdated file so down in the command line push ctrl + C on your keyboard at the same
time okay that just told node to stop running our previous version of our code because the
listen method is open-ended or ongoing it's just going to keep listening until we tell it to
stop listening so we stopped our server and now that we've saved the changes to this file we
just want to start the server back up again so just run the exact same command node test or
whatever the name of your file is okay now if we go back into the web browser and if we try
to visit localhost 3000 slash about and then jump back into the command line you can see
that that got logged out to the console that slash about so now each time a request comes
into the server our functions going to run and we're going to see that value so if you typed
slash pizza and tried to visit that URL you better believe that you're going to see that in the
node console and back in the web browser if we just visited the base URL localhost colon
3000 we just see a forward slash with nothing after it now this might seem basic but this
really opens up the door to a lot of possibilities let me show you what I mean so back up in
our code let's get rid of this console dot log line and then let's go ahead and cut this response
dot end line into our clipboard so cut that okay now let's use an if statement to send back a
different response depending on the URL the user is trying to visit let me show you what I

87
mean so let's say if parentheses curly brackets and for the condition in the if parentheses we
can just say if request dot URL equals quotes and then just a forward slash that would be the
homepage so within the curly brackets for the if statement you can paste in your clipboard
and let's adjust it to say hello and welcome to our home page okay and then right below this
if statement let's just set up another if statement say if parentheses curly brackets for this
condition let's say if request dot URL equals and again that's double equal sign to check for
equality instead of assigning a value if it equals quotes slash about well then within the
curly brackets for that if statement paste in your clipboard let's send back a response
relevant to the about page say thank you for the interest in our company okay now let's go
ahead and save the file and test it out so down in the command line let's quit this instance of
node so ctrl C be sure to click on to the command line area of your screen before trying to
push ctrl C and we just want to fire the server up again using the newest version of our code
in this file so again we just say node test and over in the web browser let's try it out so if we
visit just localhost 3000 hello and welcome to our home page if we visit slash about thank
you for the interest in our come Bini awesome now while we're at it why don't we add a
fallback so that if someone tries to visit a different URL the world doesn't end and our
server doesn't just sit there and hang or throw an error let me show you what I mean back in
our text editor if neither of these if statements is true meaning if someone tries to visit a
URL that is not the base URL nor is it slash about well we just want to handle that situation
so maybe right below this second if statement let's just paste in our clipboard or you can just
manually type it out and say response our es dot end and say we cannot find the page you
are looking for okay I'm going to save the file come down to the command line click
anywhere in this command line area and push ctrl C to stop the old server and then fire up
the latest version of our codes of node tests come back to the web browser so we see that
our about page still works the home page still works but if I try to visit a bogus URL we
cannot find the page you are looking for at this point I want you to give yourself a pat on the
back because you just created your first server now I realize this super basic server might
not seem very impressive but it does open the door to all sorts of possibilities so the
question becomes what's next where do we go from here well so far our server or app can
respond to the URL of the incoming request but do you know what would make our server a
thousand times more interesting if we could respond to the value that users type in to form
fields and that's exactly what we're going to learn about in the next lesson we will learn how
to work with user submitted data in our server so perhaps we could include a question on
our web page that reads what color is the sky on a clear sunny day and then we could have a
text input field where the user can type and then we can have a mid button that they can
click and then we can use our server to evaluate their answer and either send back a
congratulations response that says yep that's the correct answer or send back a sorry
response that says nope try again that's incorrect this process of working with and evaluating
user submitted data is crucial to becoming a full stack developer however Before we jump
into that next lesson I do have an important quick note to share when it comes to the server
that we built in this lesson I want you to know that you are the only person who can access
or view your server remember that's what the localhost in our address stands for it means
your specific computer in the real world we would want other people to be able to access
our server or application so in the real world we would send our code our code that creates
the server we would send that to a hosting company that company would host our server for
us and make it publicly available and then instead of local host 3,000 the address for our

88
server could be our app comm or super awesome app comm or whatever your domain is the
big picture for right now you can rest assured that later on in the course we will indeed learn
how to make a server publicly available and when that time comes you will be able to share
the address to your server with your friends and family and they will be able to access it and
see what you built because let's be honest sharing something that you created with the
people in your life that you care about is the funnest aspect of learning anything new and
that includes programming but for now we are just getting started we are just learning the
basics so it's okay that we are using localhost and that we are the only ones that can view the
server okay having said that we are ready to move on to our next lesson and learn how to
work with user submitted data let's keep our momentum rolling and I will see you in the
next lesson

2.5 Express Intro (Part 1)

10:13
hello everyone in this lesson we are going to learn how to receive form data from a visitor
and work with that data in our server let me show you what I mean by giving you a sneak
peek of the finished product of what we're going to build together in this lesson so we see a
bit of text what color is the sky on a clear and sunny day and then here is a text input field
now if I type in an incorrect answer so if I say orange and then click to submit we see sorry
that is incorrect but if I click back to the home page and then type in blue and submit we see
congrats that is the correct answer now this may not seem very impressive or exciting but
trust me being able to respond to user input like this marks a huge milestone in your journey
towards becoming a full-stack developer right if you think about how you log in to your
bank's website or your email or any online accounts you have to fill out a user name field
and then you have to fill out a password field and then you submit and then the server
decides if what you typed in is correct or not so we're starting simple here and just checking
to see if the user types in blue or not but we need to learn how to walk before we can run so
how can we start building this together where do we begin well in our previous lesson we
used the HTTP functionality of node to set up a basic server so as we've already seen we can
technically create a server this way but the truth is is that you can use node to build just
about anything not just web servers now this open-ended nature and flexibility of node is
great but in the real world we have a specific goal right we want to create a web server so it
makes more sense to use a solution that is less open-ended and instead is specifically
designed for the purpose of creating web servers and that's exactly we're something named
Express comes into play so what in the world is Express well let's start with their official
description or slogan and then I will explain it so it says that Express is a fast unup Enya
nated minimalist web framework for node.js but what does that mean in plain English so I
would say that Express is a bunch of pre-written JavaScript code for the node environment
that we can leverage so Express takes care of a thousand different details for us so that we
can avoid reinventing the wheel and also so that we can keep our code more organized now
personally I'm not always a fan of leveraging pre-written JavaScript code like this however I
am a huge fan of Express largely because of these two words that I've highlighted here
because it is unopp Enya nated and minimalist Express doesn't automatically do a ton for us
it doesn't babysit us so much that it prevents us from learning and it doesn't really force any

89
rigid or dogmatic ideas on us it simply provides functions or methods that are specifically
designed for creating web servers you can think of it like this node on its own without
express is like Legos there's all kinds of different Lego block types some that you'll want to
use a bunch that you will not need to use and you can use these Lego blocks to build
anything on the other hand if we use Express we are still using node but Express gives us
new Lego block types that were specifically designed to be used to build the one thing that
we're trying to build a web server if that metaphor didn't make any sense that's okay let's
keep things moving but before we move on I do want to let you know that Express is not
some small seldomly used framework so by us using Express I'm not forcing some odd
opinion on you Express is absolutely the industry standard when it comes to creating web
server with node in the real world you are going to run into express all over the place to give
you a frame of reference just in the last week alone Express has been downloaded over five
million times so at this point the question becomes how do we use or download Express
well we actually do not download anything from the Express website instead let's jump back
to our text editor or more specifically jump back to our command line so I'm using vs code
so I can just click view and then terminal and then in your command line I want you to run
the following command n p.m. and then a space and then install and then a space and then
Express now before I push enter to actually run that command I want to explain what's
going on here so first of all what is n p.m. well when you installed node on your computer it
automatically installed something else named NPM these letters stand for node package
manager for now we can think of NPM as a giant grocery store of pre-written JavaScript
goodies that we can leverage right so for example if you were baking a cake in real life you
probably are not creating your own flour from wheat instead you're probably just going to
the grocery store and picking up a bit of flour so NPM is the centralized place where we can
grab all sorts of pre-written JavaScript goodies or packages right node package manager and
then the second word here is install we want to install something what do we want to install
Express that's the name of the package that we are interested in so let's go ahead and push
enter to run the command give it a few seconds and now you'll notice that in the left-hand
sidebar NPM automatically created a new folder for us named node modules and if we look
inside that older and if you look through this list you'll see aha Express if you're wondering
why NPM downloaded all of these other packages aside from Express is because Express
depends on these other packages to be honest there's never really a need to actually open the
node modules folder and look at all the different packages I'm only doing that to show you
that NPM successfully downloaded the package for us you'll also notice that NPM created
this new file named package lock JSON for now we do not need to worry about this file
later on in the course we will learn more about it before we move on I do want to let you
know that when you run an NPM install command NPM is going to create these files and
folders for you in whatever directory your command line is currently pointing towards
remember in my case I created that folder on my desktop named first node experiment and
that's the directory that my v/s code command line is pointing towards but if you're not
using vs code and you're using a standalone command line that's just something I want you
to be aware of okay now moving on we have successfully used NPM to download or install
Express so now let's begin using Express in our code so within my test dot J's file the file
that we've been writing all of our code in so far I actually want you to select everything and
delete it we want a completely brand-new clean slate in this file this time around we are
going to create a server using Express so things are going to be a little bit different now just

90
to jog your memory remember that our goal is to create this application that receives the
user input and then we evaluate whether they typed blue or something else okay so back in
our text editor our first step if we want to leverage Express is to import or include or require
in Express so type this out with me and then I will explain it so say let Express equal require
and then parentheses inside the parentheses quotes express now this syntax is identical to
when we said let HTTP equal require HTTP the difference here is that Express is not a built
in part of node meaning before we wrote this line of code we needed to use NPM to actually
go out onto the internet and download Express for us so when we say require in the express
package node we'll know to look inside a folder named node modules and it will know
where to look okay so this line of code gets expressed ready now we can actually begin
leveraging Express and that's exactly what we're going to do in the next part of this lesson
so with this first part of the lesson coming to a close you'll know that you're on track if you
ran the NPM install Express command and it created a node modules folder in your project
folder as long as you've got that you're good to go you're right on track so let's keep things
rolling and begin writing code to actually use Express and to get to that I will see you in the
next part of this lesson

2.6 Express Intro (Part 2)

19:48
hello everyone welcome to part two of this lesson let's pick up right where we left off in the
first part of this lesson we used NPM in the command line to download Express and up in
our file we've written this line of code to get Express ready now we can actually begin to
write code that uses Express to build a server so let's create a new variable so let and then
you can name it anything you want but I'm going to name it our app and let's set it to equal
and then just call Express so this will create or return an express application or server right
that's leveraging that pre-written JavaScript code that we downloaded and now we have a
server that lives in this variable named our app so now let's tell our server to begin listening
for incoming requests so on a new line we can just say our app and then dot and call the
listen method and let's listen on port 3000 okay and then right above this listen line let's add
a new line to tell our server what it should do if someone sends a request to our home page
so let's use our our app variable and then call a method so dot and the method is named get I
will explain what the word get means in this context a bit later on in the lesson but for now
all we need to know is that we give it two arguments so we could say a comma B as
placeholders the first argument is the URL that you want to be on the lookout for so let's just
say quotes and then a forward slash this represents the homepage or base URL alright and
then the second argument is a function that express is going to run anytime someone sends a
request to this URL so instead of this placeholder B let's write an anonymous function so
function parentheses curly brackets and then drop down inside those curly brackets when
express calls this function it's going to pass it two arguments so inside these parentheses let's
include two parameters our EQ comma our es okay now within the body of our function
here what do we actually want to do well when someone sends a request to the home page
URL in response we just want to send back a bit of HTML that would create this page with
this text and form field so back in our code within the body of our function we can use the
response object from express and then look inside it with a dot and then call an express

91
method named send and what do we want to send well instead of just simple quotes for a
string of text let's actually use back ticks remember this is the key to the left of your one key
or right above your tab key and in between the back ticks we are free to break down onto
separate lines like this you don't have to do this I'm doing this just to stay organized because
I think HTML is easier to read for the human eye if it's on separate lines so now we can just
start writing HTML let's create a form element so an opening form tag closing form tag
inside that form why don't we create a paragraph and inside the paragraph we can say what
color is the sky on a clear and sunny day maybe right below that paragraph let's create a
form input field that the user can type into so just create an input element input does not
need a matching closing tag but on the opening input tag let's give it a name so name equals
and then quotes and let's say sky color I just made this name up of sky color it doesn't matter
it could be unicorn or pizza or anything okay let's also give this input an attribute named
auto-complete and set that to off you don't need to do this I just don't like the annoying pop-
up auto suggestion feature in the browser okay and then right below the input element let's
create a button so the user can click on it to submit the form so opening button tag closing
button tag and we can say submit answer okay now before we save the file let's address the
opening form tag let's give it a couple of attributes let's say action quotes and let's say
forward slash answer okay and then after those quotes let's give it one more attribute named
method and set that to equal quotes and say all capital post post-911 slash answer or what
method equals post means don't worry we will circle back to that in just about a minute
from now for the time being let's go ahead and save this file and then come down into the
command and take it for a test drive so let's run the command node test or whatever your
file is named push enter and then if you jump over to your web browser and visit localhost
3000 you might need to refresh the page but you should see something that looks almost
identical to this now here's where things get interesting let's try to fill out and submit the
form fields right so click into the field doesn't matter what you type but just go ahead and
submit the form and we see some good news and some bad news the good news is if you
look up in the URL or address bar our our form redirected us to a slash answer URL that
means that we typed out the HTML for that form correctly and as you might have guessed
this is where the slash answer comes into play whatever you set as the action for an HTML
form well that's the URL that the browser is going to send the form results to now I just
randomly chose the word answer here but there's nothing special about that you could have
set this to pizza or a unicorn or anything okay so that explains the action attribute but what
about the method attribute what in the world does method equal post mean well this controls
the type of request that the browser is going to send to the server in the land of the internet
and HTTP requests there are actually many different types of requests but for now in the
context of this lesson we really only need to be aware of two different types of requests a
get request and a post request so in your web browser when you visit a URL so if I typed in
google.com my browser just sent a get request to the Google servers or if I clicked on one of
these navigation links at the top of Google like if I clicked on there about link to go to the
about page my browser sent a get request to that about URL so when you're surfing the web
a get request is sort of the standard type of request if you manually type in a URL or if you
click on a traditional navigation link it's a get request you're saying to the server you want to
get a bit of information so if I go back to local host : 3000 my browser sends a get request to
the server however if I fill out this form and then tried to submit it my browser not only
wants to get information about that new URL of slash answer but it also needs to send along

92
its own data to that URL right it needs to send along whatever I typed into the form fields so
it needs to send that data or in other words it needs to post that data hence the word post so
if I submit this form we see cannot post to slash answer and that's because we never told our
Express server what it should do in response to receiving a request to the slash answered
URL now before we worry about actually evaluating the users answer let's first make sure
that we actually understand the difference between a get request and a post request trust me
I've seen many different full stack development courses and I feel like they always gloss
over this difference and it's usually confusing and a bit blurry so let's run through a quick
exercise to make that difference between get and post crystal-clear back in our code perhaps
this method named get right here is starting to make a bit more sense we are telling our app
what it should do if it receives a get request to this URL so let's do this let's scroll down to
the bottom of this code and maybe right above this listen line let's add a new line and say
our app and then instead of dot get let's say dot post so we are going to tell our app what it
should do if it receives a post request to the slash answer URL okay just like with the get
method we want to give the post method a second arguments of comma and then we include
a function that express will run in response to this request occurring so after this comma
include an anonymous functions function parentheses curly brackets inside the parentheses
for the function include the parameters R EQ and re s inside the body of our function let's
just send back a bit of text that reads thank you for submitting the form so we can use the
response object and call the send method a bit of text thank you for submitting the form
okay now before we save this and test it out I want to do something to make the difference
between a get request and a post request crystal-clear what I want you to do is select these
three new lines of code that we just wrote copy them into your clipboard and then right
below this but before the dot listen line just paste in your clipboard so duplicate it and on
this new copy I want you to change this word post to get so on the second copy it's our app
dot get so if someone sends a post request to this slash answer URL this makes sense but if
someone sends a get request to that same URL let's do this instead let's just send back a bit
of text that says are you lost there is nothing to see here okay at this point let's go ahead and
save the file and then test it out in our browser so let's come down into the command line
and press control C to stop the old server and then let's just run node test to fire up a new
copy of the server with our latest code all right and then back in the browser if I just go to
localhost 3000 and fill out the form submit thank you for submitting the form so this is in
response to the post request to slash answer however if I go back to the home page and then
up in the URL address bar if I manually type in slash answer that is a get request so that's

why we see are you lost there is nothing to see here so hopefully this illustrates the
difference between a get request and a post request a get request happens when you type in a
URL or you click on a traditional navigation link a post request typically happens when you
submit a form right when the user wants to send or post a bit of data to the server so even
though in both cases the URL ends with slash answer our server is able to respond
differently depending on whether it's a get request or a post request all right so now that we
have at least a very general understanding of what a post request is let's get back to the
actual task at hand so when someone submits the form we don't want to just say thank you
for submitting we want to actually evaluate their answer and tell them if it's correct or
incorrect right and we are asking them what color is the sky on a clear and sunny day so the
question becomes how can we access the data that the user submits from within our server

93
well the good news is that Express makes it very simple so let's jump back into our code and
within the our app dot post area right this is what's going to occur when someone submits
the form let's actually get rid of this response dot send line so now we just have an empty
body of the function because before we send back a response we need to decide if they
typed in the correct answer or not so we know that in JavaScript we have a tool to do just
that and that is the if statement so let's say if parentheses curly brackets inside the curly
brackets let's drop down right after those curly brackets we can say else new set of curly
brackets okay and let's fill in the condition so in the parentheses right after the word if let's
say if X equal equal sign blue now I just typed in X as a temporary placeholder so now the
million-dollar question is how do we actually access the user's typed in value here well
instead of the placeholder X get rid of that and let's say our EQ for request this is the request
object that express passes into our function which contains all sorts of information about the
incoming requests so within our if statement we can say if re Q dot body dot sky color
equals blue so the request object and then body is the body of the post of what they're
sending it's the main meat and potatoes and then we are looking inside that for the sky color
property because in HTML form could contain multiple fields so we need to specify which
specific field or value we are interested in if you're wondering where this name sky color
came from remember that this will be exactly whatever you typed in for the input name
when we were building the HTML for our form okay so if this evaluates to true then the
user typed in the correct answer so within our if statement curly brackets let's just send back
a congrats message so response dot send I'm going to include back ticks so I can drop down
onto multiple lines and in between the back ticks let's just send an HTML paragraph that
says congrats that is the correct answer and then maybe right below the paragraph let's
include an HTML link that they can click on to go back to the home page so a for anchor in
the middle let's say back to home page and on the opening a tag let's give it an H ref and
then let's just say forward slash to represent the home page ok but if the user types in
something other than blue that's incorrect so we need to fill in this else part of our code so to
save a bit of typing let's just copy and paste these lines right here from the start of our es to
the end of the closing parenthesis for the send so I'm just going to select that and then copy
it and then in the else brackets I'm going to paste in my clipboard this time around we just
want to change the message that's in the paragraph so this time we'll just say sorry that is
incorrect all right now before we save our file and test it out we need to do one more thing
by default out of the box Express actually will not add the user's inputs to the body object
that belongs to the request object so in order for this code that I'm selecting right now in
order for this to work we need to tell Express to enable that feature so do this with me scroll
up to the very top of our file and right below this line where we say let our app equal and
then we call Express right below that let's add a new line and let's just say our app dot use
and now the rest of this line of code is not going to be educational in the slightest this is
more of boilerplate code that you would find on the Express documentation website and
then you would just copy and paste it and include it in each of your new express projects so
this is not something that you need to memorize but let's say Express dot URL encoded
parenthesis to call that method then we give it an object so curly brackets inside those
brackets we include a property named extended and then colon and set it to false you might
need to pause the video lesson for a minute to type this in with me but again I'm not going to
explain it because this is just boilerplate code and it's not educational all it's doing is
enabling that feature in Express so that the users input is easily accessible from the request

94
body object okay at this point let's go ahead and save our file come down to the command
line stop the old server fire up the new server let's go back to the browser i've refreshed the
home page and type in something other than blue submit sorry that is incorrect but if i go
back to the home page and type in blue congrats that is the correct answer now you might be
thinking to yourself what if someone types in all capitals blue or just the first letter
capitalised we see sorry that is incorrect even though that is the correct answer so really
quick to make our code case-insensitive instead of case-sensitive all we need to do is come
into our if statement and right after the request body dot sky color just say dot to upper case
parentheses to call that method so whatever the user typed in will be converted to all
capitals and then we can just check to see if that equals and then for here we can just say all
uppercase blue so let me save that and then restart the server jump back into the browser if i
type blue or maybe leave the e lowercase just to really prove a point and submit congrats
that is the correct answer and that's actually going to bring this lesson to a close in our next
lesson we are going to do two things number one we will review why this example app was
so important and number two we will identify the missing ingredient that is going to let us
create more advanced applications let's keep our momentum rolling and I will see you in the
next lesson

2.7 What's Next? (Big Picture)

14:03
hello everyone this is sort of a bigger picture video we are not going to be writing any code
instead in this video we are going to answer three questions so number one why was the app
that we built in our previous lessons so important number two what is the missing ingredient
that will let us build more advanced apps and finally number three what are we going to be
doing for the remainder of this course let's start up at the top with number one and ask
ourselves why was this application that we just built so important well it's because we are
now at least a little bit familiar with the process of receiving an incoming request making a
decision based on the user's input and then sending back a response now understanding this
basic cycle of request and response request and response is insanely powerful because that's
really all any application does the real question becomes what do we do in between the
request and response so I want you to think of a sandwich typically the most interesting part
of a sandwich is whatever is in between the bread so if we think of the incoming requests as
one piece of bread and the response that our server sends back as the other piece of bread
that would mean that the peanut butter and jelly or the meat of our sandwich is our if
statement that checks the users sky color value now granted that's a pretty boring and simple
sandwich that we made but that's not the point the point is that we now know how to make a
sandwich at all that's huge now we just need to learn how to put more interesting ingredients
into our sandwich which brings us to the second question of this video what is the missing
ingredient that will let us build more interesting or advanced applications well if we look at
our course overview we are now at least a little bit familiar with the first three items so as
you can probably guess the missing ingredient is MongoDB technically the missing
ingredient is any database system but in this course we are going to be using MongoDB in
particular now before we worry about what a database is let's first look at the big picture so
the app or server that we built in our previous lesson can read the users input right we were

95
able to determine if they typed in blue or not but as soon as the server sends back its
response that data that the user typed in and submitted is gone our server does not remember
it now for certain simple applications that's okay but for most complex applications we need
to have some sort of permanency right eventually we are going to want to remember or store
the users data and this is where databases come into play so for example what if instead of
asking the user what color is the sky what if instead we were asking them to register for a
new account so they would need to enter a username and a password well we would want to
permanently remember those values that they choose so that we can reference them the next
time they try to login that's just one example there are millions of examples databases are
everywhere anytime you post a comment on Instagram it's getting saved into a database or
anytime on Twitter you send out a new tweet that's being saved into a database really
anything you do on the internet that is permanent likely involves database now instead of us
learning about databases in a cold soulless academic isolated vacuum we are going to learn
about them within the holistic context of creating applications to be more specific full stack
JavaScript applications which segues nicely into the third and final question of this video
what are we going to do for the remainder of this course well aside from a few bonus or
extra credit topics at the very end of the course we are going to spend the rest of our time
together building two applications let's call them app number one and app number two app
number one is small unorganized and messy and oversimplified on the other hand app
number two is big organized and very real-world now you might be wondering why we're
going to build two apps instead of just one right you might think why not just skip the small
unorganized project and just focus all of our effort on the big organized project right away
well trust me there is a method to my madness so right now our focus is on learning the very
basics of a database however if we jumped straight into app number two we would need to
worry about things like templating engines user registration user authentication security
error handling how to keep our code and files organized and much much more trust me we
don't want to deal with all of that in this moment so for the time being we need a project that
is complex enough to need permanency in a database but simple enough that we don't
overwhelm ourselves with all of these topics on the screen right now that's actually my
biggest pet peeve with other courses and instructors they structure their example projects in
a way to where you're being introduced to ten new topics at once and you just drown in a
sea of new topics all fighting for your brains horsepower at the same time so the idea in this
course is that app number one will get us comfortable with the big picture the basic
mechanics of building a full stack app and then once we've absorbed some of that and some
of it becomes second nature we can move on to app number two where we do worry about
real-world complications and best practices so on and so forth now really quick right now I
want to show you a sneak peak of both app number one and app number two just so you
know what to expect so here is app one and this is the finished final product that we are
going to be building together it's a very simple to do app and you can see there's a text field
here and if i type in feed the dog and then to push enter or click the blue submit button it
adds it down here and let me have a few more items maybe pay attention to the cat and
maybe buy fruits and vegetables okay so now I've got this list of items and each item has
two different actions you can edit it or delete it so if I click Edit on feed the dog this little
pop-up appears and I can type something new and I can say feed the dog maybe add the
word today at the end of it push okay you can see it gets updated and then obviously I'm
free to delete any of the items I want so if I want to delete by fruits and vegetables just click

96
delete we see this little pop-up do you really want to delete by fruits and vegetables
permanently yes I do so click OK and it's gone now the whole point of this application is
that our list of items is being permanently stored in a database so even if I closed my web
browser and then came back and revisited this app maybe a year or two from now this data
these items would still be here waiting for me or better yet I could step away from my
computer and maybe use my phone or tablet and my data would still be available to me
because instead of just localhost we are also going to learn how to push this app up onto the
internet so you can share it with your friends and family so in the address bar if I instead
visit this URL because our data and database lives in the cloud you can access it from any
device so this is pretty fun you will get a URL that you can share with your friends and
family this is just my example temporary URL you will receive a new unique URL for
yourself and then you can see them add new items to the list big picture there's not a whole
lot going on with this app but it is great practice of learning how to stitch together our three
environments the web browser nodejs for the server and Mongo DB for the permanency or
database layer okay so that's a review of app number one that we are going to build together
now let's take a look at the more complex app number two so this what the home page looks
like if you are not logged in it shows you a registration form to sign up for a new account if
you try to sign up for a username that already exists that someone has already used you get a
real-time feedback message that username has already taken so if I add unique at the end of
it good to go if you add something that is not a valid email address you get a warning in
real-time you get the idea now instead of creating an account in this moment let's just log in
to an existing account to show you around up in the header you can log in as soon as I sign
in you can see the home page looks very different by the way this is a journal or diary type
of application so you can see the home page now that I'm logged in reads the latest from
those you follow this is essentially a very basic social network type of application these are
articles or journal entries written by the people that I follow so I can see this one's titled
destroying furniture is fun written by Kitty doe so if I click on that here is their article and I
can even click on their name to go to their profile up in the top right menu bar I can click on
my own circle to go to my own profile so I have three posts I have one follower I'm
following two accounts we can click on that you can see I'm following barks-a-lot and Kitty
Doe also back up in the header I can click on this icon to search for the content that I'm
interested in so if I search for the word furniture in real time we get search results so we see
destroying furniture is fun that existing article by Kitty doe if I search for something that's
going to return multiple results like the word post there we go because I use that word in my
title you get the idea let's close this live search results feature I can click on this green create
post button to obviously create a new post or article obviously a user is able

to edit or delete their own existing articles ok changing gears if we look up in the header we
can see a chat or conversation looking icon if you click that it opens a chat box connects you
to the chat room and this is not a one-on-one direct mess using inbox system this is more of
an old-school traditional public chat room so I can type in a message and say hello and any
and all users that are logged in will be placed into this same chat room with me in the real
world the public chat room like this would probably just be taken advantage of by weirdos
and creeps and malicious users but in the context of this course I think it's a fun
programming exercise so I'm logged in as the Brad user in this browser but I actually have a
secondary browser in this window I'm logged in as the kid IDO account so if I connect to

97
the chatroom here I can say meow and back in this window you can see that that message
appears again this is just a fun programming exercise to see what a server can really do
being able to have real-time to Direction communication of data like this is a lot of fun to
setup okay and then finally if I jump back to the home page of the application remember this
is my personalized feed because I'm logged in however if I use this button in the top right to
sign out you can see the home page now correctly treats me as if I'm a guest alright and that
concludes the sneak preview of the finished product of app number two that we are going to
build together in this course now to bring this full circle what do a penumbra to an app
number one have in common well they both use a database to store data permanently in the
case of this simple app number one that's just the to-do list items in the case of the more
complex app number two the database is storing the user names the passwords the article
posts the relationships of which users are following which other users so on and so forth so
where do we go from here well in our very next lesson we are going to begin learning about
databases in particular a system named MongoDB and as soon as we learn even just a little
tiny bit about MongoDB we can begin to create this to-do list app together I'm super excited
because this the point in the course where we can finally begin to build real meaningful fun
applications we've eaten enough of our metaphorical broccoli we worked through the ten
days of JavaScript to understand the programming language itself we learned a bit about the
web browser as a JavaScript environment we just learned a little bit about nodejs and how it
can be used to create a server and what the whole point of a server even is and now finally
we just need to fold in a little bit of understanding of what a database is and we will be off
to the races so let's keep our momentum rolling let's get excited for databases and I will see
you in the next lesson

98
3. Database Basics
03:34:24
First Taste of a Database

10:57

Note for Advanced Students

00:51

CRUD: Actually Working With A Database

14:04

Initial Setup for App #1

18:02

Save Time: Automatic Node App Restarts

09:12

Quick Note About MongoDB Warning in Command-Line

00:30

Connecting Node App to Database

19:58

Installing NPM Packages Without Stopping Server/App

00:27

Reading Data from a Database

17:24

99
Updating a Database Item (Part 1)

19:58

Updating a Database Item (Part 2)

19:55

Deleting a Database Item

12:55

Create New Item Without Page Reload

19:57

Client-Side Rendering

10:17

What About Security?

19:54

Quick Note For Mac Users

00:27

Pushing Our App Onto The Internet

19:19

Pushing Future Changes To Your Heroku App

00:17

4. Starting Our Complex App (App #2)

100
05:16:19
What's Next?

08:03

Let's Begin App #2

18:39

Important Note About Package Versions To Save You Frustration

01:32

What Is A Router?

14:11

What Is A Controller?

17:52

Security Note

00:24

What Is A Model?

19:58

Adding Validation To Our Model

19:58

Quick Misc. Clean Up

08:01

Quick Note About Connecting to Database

101
00:25

Connecting To Database In a Reusable Fashion

17:12

Best Practice Time Out: Environment Variables

10:10

Quick Note

00:09

Letting Users Log In

18:37

What is a Promise? (Part 1)

19:32

What is a Promise? (Part 2)

14:24

Running Multiple Promises Efficiently When Order Doesn't Matter

00:30

Hashing User Passwords

13:53

How Can We "Identify" or "Trust" a Request?

19:17

For Those Who Are In a Hurry (Security Note)

102
00:42

Understanding Sessions

19:07

Letting Users Logout

11:57

Adding Flash Messages

16:28

User Registration Improvements (Part 1)

17:41

User Registration Improvements (Part 2)

12:01

Adding User Profile Photos

15:36

5. User Created Posts


04:03:44
Letting Users Create Posts (Part 1)

17:31

Letting Users Create Posts (Part 2)

12:17

103
Post Model (Part 1)

19:59

Post Model (Part 2)

07:16

Viewing a Post (Part 1)

07:45

Viewing a Post (Part 2)

19:10

Performing a Lookup in MongoDB (Part 1)

16:50

Performing a Lookup in MongoDB (Part 2)

08:14

User Profile Screen

18:10

View Posts by Author

19:47

Is the Current Visitor the Owner of the Post?

12:53

The "Edit" Screen for a Post

08:50

104
Updating Posts in Database (Part 1)

10:51

Updating Posts in Database (Part 2)

18:57

Miscellaneous Improvements

14:55

Markdown: Safe User Generated HTML

15:44

Make This Quick Edit To Your Code

00:37

Let Users Delete a Post

13:58

5. Live Search Feature


01:41:08
Staying Organized: Front-End JavaScript

19:57

Showing and Hiding Search Overlay

16:54

Responding to Key Press Events

105
19:12

Back-End Aspect of Search

15:40

Generating HTML for Search Results (Part 1)

10:05

Generating HTML for Search Results (Part 2)

10:47

Fixing The Month for Post Dates in Search Results

00:21

Sanitizing User Generated HTML on the Front-End

08:12

6. Letting Users Follow Each Other


02:08:16
Letting Users Follow Each Other

12:25

Saving a "Follow" Action Into Our Database

12:25

Stop Following a User (Part 1)

13:48

106
Stop Following a User (Part 2)

13:16

Profile Followers Screen (Part 1)

10:26

Profile Followers Screen (Part 2)

15:25

Following Screen (Part 1)

13:29

Following Screen (Part 2)

17:30

Homepage Feed (Posts From Those You Follow)

19:32

7. Live Chat (Socket.IO)


01:23:18
Beginning Chat Feature

19:37

Socket.IO (Part 1)

10:43

Socket.IO (Part 2)

107
11:42

Finishing Chat (Part 1)

13:39

Finishing Chat (Part 2)

19:56

Quick Misc. Feature: Dynamic Title Tag

07:41

8. Live Validation for Registration Form


01:16:09
Live Form Validation (Part 1)

18:41

Live Form Validation (Part 2)

18:22

Live Form Validation (Part 3)

19:58

Live Form Validation (Part 4)

19:08

108
9. What is CSRF? (Security)
33:02
Preventing Cross-Site Request Forgery (CSRF)

19:58

Adjusting Our App To Use CSRF Token

13:04


10. Let's Create an API
01:04:15
Setting Up The Skeleton for an API

19:41

JSON Web Tokens (Part 1)

11:37

JSON Web Tokens (Part 2)

13:47

Finishing API and Understanding CORS

19:10

109
11. Deploying Complex App to Heroku
29:40
Pushing Our Complex App Up Onto The Web

14:15

Sending Email From Our App

15:25

12. Where Do We Go From Here?


19:53
Next Steps & Career Advice

19:53

110

You might also like