Afrikaans
Akan
Albanian
Amharic
Arabic
Armenian
Azerbaijani
Basque
Belarusian
Bemba
Bengali
Bihari
Bosnian
Breton
Bulgarian
Cambodian
Catalan
Cebuano
Cherokee
Chichewa
Chinese (Simplified)
Chinese (Traditional)
Corsican
Croatian
Czech
Danish
Dutch
English
Esperanto
Estonian
Ewe
Faroese
Filipino
Finnish
French
Frisian
Ga
Galician
Georgian
German
Greek
Guarani
Gujarati
Haitian Creole
Hausa
Hawaiian
Hebrew
Hindi
Hmong
Hungarian
Icelandic
Igbo
Indonesian
Interlingua
Irish
Italian
Japanese
Javanese
Kannada
Kazakh
Kinyarwanda
Kirundi
Kongo
Korean
Krio (Sierra Leone)
Kurdish
Kurdish (Soranî)
Kyrgyz
Laothian
Latin
Latvian
Lingala
Lithuanian
Lozi
Luganda
Luo
Luxembourgish
Macedonian
Malagasy
Malay
Malayalam
Maltese
Maori
Marathi
Mauritian Creole
Moldavian
Mongolian
Myanmar (Burmese)
Montenegrin
Nepali
Nigerian Pidgin
Northern Sotho
Norwegian
Norwegian (Nynorsk)
Occitan
Oriya
Oromo
Pashto
Persian
Polish
Portuguese (Brazil)
Portuguese (Portugal)
Punjabi
Quechua
Romanian
Romansh
Runyakitara
Russian
Samoan
Scots Gaelic
Serbian
Serbo-Croatian
Sesotho
Setswana
Seychellois Creole
Shona
Sindhi
Sinhalese
Slovak
Slovenian
Somali
Spanish
Spanish (Latin American)
Sundanese
Swahili
Swedish
Tajik
Tamil
Tatar
Telugu
Tigrinya
Tonga
Tshiluba
Tumbuka
Turkish
Turkmen
Twi
Uighur
Ukrainian
Urdu
Uzbek
Vietnamese
Welsh
Wolof
Xhosa
Yiddish
Yoruba
Zulu
welcome to the complete JavaScript
course in this course we're going to
learn how to build complex websites
using JavaScript from a beginner to a
professional level and by the end of
this course we're going to build
amazon.com so this is an interactive
multi-page website where we can add
products to our cart create an order and
even track our
order along the way we're also going to
build some smaller projects like a rock
paper scissors game a to-do list and a
calculator now you don't need any
previous coding or technical experience
to follow along this course will cover
everything that you need to learn
JavaScript we're going to start from the
very basics of JavaScript and we're
going to build our way up step by step
we're going to learn the major features
of JavaScript and also how to use
JavaScript together with other
Technologies like HTML and
CSS we're also going to learn more
advanced features like objectoriented
programming backend callbacks promises
and async await and we'll use these
features together to build a complex
project which is the Amazon
Project this will let you practice what
you learn and deepen your
understanding you can find the different
lessons of this course course below the
video
here and
here if you need to you can adjust the
speed of the video
here and after each lesson I'm going to
give you a bunch of exercises that you
can do on your own to practice the
skills that we learned in total this
course will have over
250 exercises so with that said let's
get started
before we begin if something in this
course is not working properly make sure
to check the first comment below the
video for a list of
solutions I'm going to be doing this
course on Windows but the steps are the
same if you're using a Mac we're going
to start from the very basics of
JavaScript and build our way up step by
step first of all what is Javascript
JavaScript is a technology that we use
to create websites a website is like
youtube.com or
amazon.com it's how we access YouTube
and Amazon on our computer if we were
using a phone we usually use an app but
on our computer we use a
website so there's actually three
technologies that we use to create
websites HTML CSS and JavaScript each of
these Technologies has a specific
purpose when creating a website HTML
creates the content of a website it
creates all the buttons the text and the
images CSS changes the appearance of the
website by adding CSS we can make our
website look nice and finally JavaScript
makes our website
interactive so if we only have HTML and
CSS and we click one of these buttons
our website doesn't do anything but once
we add JavaScript we can make our
website do something when we click a
button such as add a product to our cart
or create an
order so this course is focused on
JavaScript if you want to learn HTML and
CSS in more detail I have a full whole
course just like this one that you can
find in the video
description let's get started with
JavaScript the first thing we need to do
is to install a piece of software called
a web browser a web browser lets us view
websites that we create in this course
the most popular web browser for web
development is Google Chrome so I
recommend using that if you don't have
Google Chrome you can open the default
web browser on your computer for windows
it's Microsoft Edge and for Mac it's
Safari type in google.com at the top and
press enter search for Google
Chrome click the result and follow the
instructions to download and install
once we've installed Chrome we're ready
to
begin we're going to start by learning
what exactly is Javascript and how does
it work the easiest way to understand
JavaScript is we're basically giving
instructions to a computer and then the
computer follows our
instructions I find the best way to
learn this is to jump in and give it a
try so first let's open Google
Chrome next we're going to click at the
top
here and type
super
simple
dodev slj
s- Basics and press
enter and now we'll learn how to give
our computer some instructions to follow
to do that we're going to go to a blank
area of the web page we're going to
rightclick click
inspect and then click the console
tab now if your console doesn't show up
at the bottom like this you can click
these three dots here here and then
select this
icon okay so inside the console we can
give some instructions for our computer
let's learn our first instruction we're
going to type here and we're going to
type
alert Open Bracket single quote hello
single quote close bracket and
semicolon make sure to type this out
exactly as I have it here in JavaScript
if you don't type things out correctly
it won't work so this is an instruction
to create a popup with the text hello
inside to get the computer to follow our
instruction we can just press
enter and as you can see the computer
does exactly what we tell it to do it
creates a popup with a text hello
inside now let's press
okay and let's give another instruction
to the computer so we're going to type
here again and we're going to type alert
again Open Bracket single quote but this
time we're going to type a different
message in the
popup good job and single quote close
bracket and
semicolon so this is an instruction to
create a popup again but this time with
a text good job in inside the popup if
we press
enter the computer does exactly what we
tell it to do and it creates a popup
with the text good job inside and that's
basically the main idea behind
JavaScript we're giving instructions to
a computer and then the computer follows
our
instructions so note that we can open
and use this console on any website
we're just using superimple dodev as an
example
let's press
okay and we're going to learn some
terminology or
naming the instructions we give to our
computer these instructions are called
code when we press enter and the
computer follows our instructions this
is called running the code now there are
many different languages we can use to
write code called programming languages
it's similar to how we have many human
Lang languages that we can use to
communicate some examples of programming
languages are JavaScript Python and Java
so here we're writing our code using the
JavaScript programming language so we
call this JavaScript
code now that we understand the basic
terminology let's look at some more
examples of what we can do with
JavaScript code another thing we can do
is
math let's go back to the console and
type here and we're going to type 2 + 2
so this is an instruction or code that
tells the computer to do some math to
calculate 2 + 2 when we press
enter the computer follows our
instruction or runs this code calculates
2+ 2 and gives us the result which is
four let's do another example we're
going to type 10 minus 3 and press enter
to run this code again the computer does
this math calculates the result and
gives us seven so as you can see
JavaScript can do many different things
like create popups and do math let's
look at one more example of what
JavaScript can do we're going to go to
the bottom and type out this code
document.body do inner Capital
HTML equals single quilt hello single
quilt and
semicolon make sure to write this out
exactly as I have it here with the dots
and the capital letters because
JavaScript is case
sensitive let's press enter to run this
code what this code does is that it
removes everything on the page and
replaces it with the text hello in this
example we use JavaScript to modify the
web page modifying the web page is one
of the most important features of
JavaScript and we're going to be using
this feature throughout this course and
that's the basics of JavaScript we're
giving instructions to a computer these
instructions are called code and then
the computer follows our instru
instuctions this is called running the
code and also don't worry about
memorizing all this code you can find a
copy of all the code that we write in
this course in the video
description now that we understand the
basics of JavaScript let's learn more
about the JavaScript language
itself if we take a look at this code
alert and hello you might be wondering
ing what the brackets and the quote mean
all of these characters have a special
meaning in the language this is
something called
syntax syntax are the rules that we have
to follow when using a programming
language like JavaScript this is sort of
like in English we also have rules that
we follow called grammar the difference
is that in English we don't have to
follow the rules of grammar perfectly
people can still understand us but in
programming we have to follow the rules
of syntax exactly otherwise the computer
won't understand our code for example if
we scroll down and we type this code
alert Open Bracket quote hello quote
close bracket and semicolon but this
time we remove the first bracket and
press
enter it will give us a syntax error
we're not following the rules of syntax
so the computer doesn't understand this
code now JavaScript has a lot of syntax
rules and we can't learn them all at
once right now instead we're going to
learn the syntax rules one by one as we
go through the course for now we'll just
learn enough syntax to do the exercises
at the end of this lesson what we need
to know is that if we scroll up
this part of the code tells a computer
to create a popup the text between these
quotes is the text inside the popup if
we change this text we can change the
text inside the popup same thing for
this code down
here if we change the text between the
quotes it will change the text that
appears on the page and that's all we
need to know about JavaScript Syntax for
now we'll learn exact ly what the other
characters like the brackets quotes and
semicolon mean later on in this course
so in this lesson we learned that
JavaScript is basically giving
instructions to a computer we wrote our
first few lines of JavaScript code we
learned how to run our code using the
console in our web browser and we
learned about syntax which are the rules
that we have to follow when writing our
code
thanks for watching this course so far
if you want to support this channel you
can check out the premium version of my
courses just like this one where you can
get a certificate of completion and a
Better Learning platform if you're
interested in extra videos from me more
in-depth videos and behind the scenes
content you can check out these links
here you can also support the channel by
liking the video subscribing and sharing
this video with others
thanks again and let's continue with the
course here are some exercises you can
try on your own to practice what we
learned in this
lesson you can find the solutions to
these exercises in the video
description now that we understand the
basics of JavaScript we're going to
learn about each feature of the language
language in this lesson we're going to
focus on numbers and math first we can
close the console for
now so I've actually prepared a project
that we can use for this lesson to open
this project we're going to go to our
browser click up here and type
super simple
dodev SL
projects SL Amazon
and press
enter so this is actually the final
project we're going to create in this
course this is an e-commerce website
similar to Amazon where we can add
products to our cart and then view our
cart by clicking the top
right and on this page we can see the
products in our cart modify our cart and
create an
order for this lesson we're going to
focus on this right section which
calculates the cost of our cart
including the cost of the products
shipping and
taxes this section is a great way to
learn numbers and math in
JavaScript first let's open the console
again so we can write JavaScript code
we're going to find a blank area of the
web page rightclick click
inspect and then click the
console so we already saw some examples
of math in the previous lesson for
example we wrote the code 2 + 2 if we
press
enter the computer adds these two
numbers and results in
four we also did 10 minus 3 if we press
enter the computer subtracts these two
numbers and gives us
seven in addition to adding and
subtracting we can also multiply and
divide to multiply we're going to type
10 star 3 and press
enter so star is the character for
multiplying to divide we're going to
type
10
slash2 and press enter
so forward slash is the character for
dividing now let's learn the syntax
rules for numbers and math the Syntax
for math is pretty straightforward in
JavaScript we just write it out like
normal math we can also do math with
more than two numbers for example we can
add two plus 2 and then plus another two
if if we press enter the computer will
add these three numbers together and
result in six and finally JavaScript can
handle decimal numbers like
2.2 plus
2.2 if we press enter it will calculate
these decimal numbers and result in
4.4 now let's do some practical examples
we're going to calculate the number
numers here in our final project but
first let's set up our cart so we have
the same products in our cart so make
sure in your cart you have two socks
with free shipping and you have one
basketball with
$4.99 of shipping and nothing else in
your cart if you need to you can modify
your cart by clicking update or delete
or or by going to the homepage by
clicking in the top left and adding any
products that you're
missing once you have the same products
as me in your cart and you have the same
numbers on the right we're ready to
begin let's start by calculating this
number up here this is the cost of the
products before shipping and taxes to
calculate this number using JavaScript
we're just going to add the cost of the
products so in our console we're going
to add the cost of the socks which is
$10 and
90 we have two of them so we're going to
multiply this by
two and then we're going to add the cost
of the basketball so plus
$20.95 if we press
enter the computer will do this math
calculation
and give us this number and if we scroll
to the top of our
project you'll see that the number that
we got matches what we have on the page
so that's how we use JavaScript to
calculate this number here let's do
another example we're going to calculate
this third number which is the cost of
the products plus shipping feel free to
pause the video if you want to try it
yourself first otherwise we'll do it
together let's go back to our
console and we're going to add the cost
of the products again which is
$10.90 * 2 plus
$20.95 but this time we're going to add
the cost of shipping which is
$4.99 so
4.99 and press and
enter the computer will do this
calculation and give us this number
which matches what we see in the final
project next we're going to learn a very
important feature of math called the
order of
operations adding subtracting
multiplying and dividing these are
called operations and the characters in
the middle are called
operators now there's a certain order
that we do these operations for example
if we go back to our console and type
the calculation 1 + 1 * 3 and press
enter notice that it multiplies 1 * 3
first which equals 3 and then adds 1
which equals
4 notice that it does not add 1 + 1
first
which equal 2 and then 2 * 3 =
6 the way math normally works is that
multiply and divide are done first add
and subtract are done after this is
called the order of operations and
JavaScript follows the same rules
multiply and divide are done first add
and subtract are done after the order of
operations is also called operator
precedence in
JavaScript one thing to note is that
multiply and divide have the same
priority so if we have both in a
calculation it will calculate from left
to right add and subtract also have the
same priority if we have both in the
calculation it will also calculate from
left to right another feature of the
order of operations is that we can use
brackets to control which part of the
calculation gets done first for example
let's type out this calculation again 1
+ 1 * 3 but this time we're going to add
an Open
Bracket and a Clos bracket around 1 + 1
if we press
enter now the calculation inside the
brackets will be done first so it will
add 1 + 1 = 2 and then 2 * 3 = 6 so when
we use brackets JavaScript will always
do the calculation inside the brackets
first and then do the rest of the
calculation brackets have the highest
priority in the order of
operations now let's learn the syntax
rules for brackets
so we just have to have a matching Open
Bracket and close bracket so something
like this doesn't work because we have
two Open brackets and no Clos bracket we
also need to have a complete calculation
in the brackets so this also doesn't
work because 1 + 1 multiply is not a
complete
calculation now let's do some practical
examples using the order of
operations first we're going to do some
more setup in the final project so we're
actually going to remove all the
products in our
cart and then once our cart is empty
we'll go to the homepage by clicking the
top
left and this time we're going to add
some new products so we'll add one
basketball and two T-shirts
now let's go back to our cart by
clicking the top
right we'll scroll down and we're going
to calculate the numbers in this section
again let's calculate this number at the
top which is the cost of the products
we'll go back to our
console and add the cost of the
basketball which is
$20.95 Plus the cost of the
t-shirts which is
$799 and we have two of them so we'll
multiply this by two if we press
enter this will give us the number that
we see in the final project here notice
that in this calculation we're taking
advantage of the order of
operations even though multiply is
written last
we still multiply these two numbers
first so we calculate the cost of two
T-shirts first and then we add the cost
of the basketball
after okay now let's try something a
little more difficult we're going to
learn how to calculate this 10% tax here
so how do we calculate 10% of something
unfortunately we can't just multiply by
10% in JavaScript instead
we have to calculate the percent
manually so how do we do that 1% is
actually equal to 1 / 100 that's what
percent means so 10% is equal to 10 /
100 which equals
0.1 so to calculate 10% manually we just
multiply this number by
0.1 so we'll type 30 3
6.93 multiplied by 10% or
0.1 if we press
enter it will give us a number that is
close to what we have in the final
project it's the same amount of money
but our number is more accurate than we
need so later in this lesson we'll learn
how to round this number down to exactly
what we have on the web page for now
let's do some more practice with the
order of
operations let's calculate the tax again
except instead of using the final number
36.9 3 Let's calculate this number
individually like here so at the bottom
we're going to add the cost of the
basketball
20.95% 2 and then multiply this by the
tax percent time
0.1 and press
enter unfortunately this number doesn't
match what we got up here and that's
because if we look at this calculation
according to the order of operations
multiply is done first so it will
multiply these three numbers first and
then add 20.95%
after however this is not what we want
we actually want to calculate this
number first this is the cost of the
products so how do we get the computer
to calculate this first and then
multiply by the tax percent
0.1 to do this we can use brackets to
control which part of the calculation
gets done first so let's create this
calculation again 20
.95 +
7.99 * 2 but this time we're going to
add brackets around this part of the
calculation to make sure that this gets
calculated first and then at the end
we'll multiply it by the tax percent
0.1 and now if we press
enter we will get the same number that
we had before
so that's how we use math and the Order
of Operations to calculate the numbers
in this section of the final project so
don't worry you don't have to be good at
math to learn JavaScript this is just to
show you how math Works in
JavaScript in the rest of this lesson
we're going to learn some more details
about numbers and math the first detail
we're going to learn is a weird behavior
of math in JavaScript
first we'll need to learn some
terminology in programming whole numbers
like 2 3 and 4 are called integers
decimal numbers like
2.2 and 2.5 are called floating Point
numbers or floats and unfortunately
computers have a problem working with
floats for example if we go back to our
console and type the calculation
0.1 plus
0.2 and press
enter it will give us this weird number
here that's close to 0.3 but a little
bit
inaccurate so this problem is not
specific to JavaScript many programming
languages also have this problem the
reason this happens is because of how
computers store numbers I'll give a
simplified explan
computers can only store zeros and ones
while humans can count from 0 to 9 so
there's sort of a mismatch between our
number systems for integers this is not
a problem the computer can just use a
bunch of zeros and ones to store it
however for decimal numbers or floats
sometimes the computer can't store the
number properly for example here's how
the computer computer tries to store
0.2 using only zeros and ones at the top
is what the computer stores at the
bottom is what this is equal to in human
numbers we can see that the computer
gets closer and closer to 0.2 but never
actually reaches it and this is why we
get these inaccuracies when calculating
with floats because computers can't
store some floats properly note that
this doesn't happen with all floats for
example computers can store
0.25 without any problems so these
inaccuracies only happen with some
floats but not all of them however when
calculating money we definitely want to
avoid any inaccuracies so let's learn
how to do that first we're going to set
up our cart again so make sure in your
cart you have one basketball with free
shipping and this time you have one
t-shirt so we're going to click
update change this to one and click
save and this t-shirt also has free
shipping now let's scroll up and we're
going to calculate this number at the
top again which is the cost of the
products let's go into our
console and we're going to add the cost
of the basketball
$20.95 plus the cost of the
t-shirt which is
$7.99 if we press
enter calculating with these floats
causes the inaccuracies that we saw
earlier so how do we avoid this problem
the best practice when calculating money
is to calculate in cents instead of
dollars so instead of
$20.95 we're going to calculate
2,95 plus
$7.99 notice we're not using floats
anymore so we avoid the
inaccuracies but now this number is in
cents so we need to convert back to
Dollars to do that we'll surround this
calculation with brackets to make sure
we calculate this first and then at the
end we'll divide by 100 to convert back
to dollars because there are 100 cents
in each dollar if we press
enter and scroll
up that's how we get the exact number
that we see on the page so remember in
programming calculations with floats are
sometimes inaccurate and when working
with money the best practice is to do
the calculation in cents and then
convert back to dollars at the
end the next detail we're going to learn
is how to round a number in JavaScript
rounding just means taking a number and
moving it to the nearest integer to
round a number we can use this
code capital m
math. round Open Bracket close bracket
so make sure you use a capital M because
JavaScript is case
sensitive now between the brackets we
can put a number that we want to round
like
2.2 if we press enter it will round this
number down to
two if we do capital M math do round
Open Bracket close bracket and between
the brackets we put
2.8 and press
enter it will round 2.8 up to three now
let's do a practical example with
math.round we're going to calculate the
tax again but this time we're going to
round the result to exactly this number
on the page so first let's calculate the
tax we'll go into our
console and add the cost of the product
products in cents so
2,95 for the
basketball and plus the cost of the
t-shirt which is
$7.99 and we'll surround this in
Brackets to make sure we calculate this
first and then we're going to multiply
this by the tax percent or
0.1 and finally we'll convert this back
to dollars so let's surround this in
Brackets as well to make sure we
calculate this first and at the end
we'll divide by 100 to convert back to
dollars so notice here we can have
brackets inside brackets in this
situation JavaScript will calculate the
inner brackets first and then the outer
brackets and then everything else if we
press enter
here this gives us
2.89 which is close to the number on the
page it's the same amount of money but
our number is more accurate than we need
so now let's learn how to use math.round
to round this number to exactly
2.89 first let's create a copy of this
calculation so we'll select it right
click copy
and down here right click and
paste by the way if you paste in the
console you might see this warning
message to fix this you can type allow
pasting and press enter and now you can
paste so let's continue and we were
trying to round 2.89 4 to exactly
2.89 so one thing we might try to do is
to round this entire
calculation however this will round 2.89
4 to 3 because it rounds to the nearest
integer instead what we want to round is
this number here so remember that this
number is the result in cents which is
289.50
if we round this number it will round
down to
289 which is exactly
$289 so to round this calculation at the
front we'll type capital M
math.round so we already have brackets
around this so we don't need extra
brackets so this this will round to
289 and finally we'll convert this back
to dollars at the End by dividing by 100
if we press
enter that's how we rounded this
calculation to get the exact number on
the
page so to summarize we first calculate
the result in cents and then we round
this to the nearest scent and then at
the end and we convert back to
Dollars again don't worry you don't have
to be good at math to learn JavaScript
these examples are just for learning
almost all the math we do in JavaScript
is more simple than this I'll give you
some exercises at the end of this lesson
to help you get more practice the last
thing we're going to learn in this
lesson is how to use Google when you're
learning to code so far I've been giving
you different pieces pces of code like
alert and
math.round you might be wondering where
do I find this code these pieces of code
are features of JavaScript and I find
this code by searching on Google so
we're going to learn how to use Google
to learn new features of JavaScript on
our own let's go to our browser and
create a new tab at the
top and we'll click here and type
google.com and press
enter and we'll search in Google so the
trick to searching in Google is to
search for what we are trying to do for
example if we want to round a number we
would search for
JavaScript how to round a
number if we press enter
sometimes you might get the code right
away in the first result and sometimes
you might have to go into the other
results to find the code that you need
in my example I see the code math.round
in the first result so I can click into
this result read about what this code
does and also see some examples of how
to use it one thing to keep in mind is
that when you're searching in Google you
might not understand understand all the
code that you get in your results for
example here there's a lot of code that
we haven't learned yet and actually
that's okay we just need to look for the
pieces of code that look familiar to us
like this part of the code we can then
use this part of the code in our own
code we don't have to understand every
bit of code that we get from Google and
don't worry as we move through this
course we we will understand more and
more of this code that we get from
results these days we also have some
artificial intelligence or AI tools that
can help us search for code I'll provide
links to some of these tools in the
video
description by the way to find the links
mentioned in each lesson you can click
here in the
description and this page contains all
the links mentioned in each
lesson and that's the end of this lesson
in this lesson we learned how to work
with numbers and math we learned the
order of operations and brackets we
calculated the numbers in the final
Amazon Project we learned that
calculations using floats can be
inaccurate and how to avoid this problem
when working with money we learned how
to round numbers using
math.round and we learned how to search
for code on our own here are some
exercises to help you practice numbers
and math
in the previous lesson we learned how to
work with numbers and math in this
lesson we're going to learn how to work
with text and we're going to create the
text in this section of the final
project first make sure you have the
final project open and you're on the
checkout page also make sure you have
the console open on this page if not you
can go to a blank area
right click click
inspect and then click the
console now we're going to learn a
feature of JavaScript called strings a
string represents text let's go to our
console and create our first string
we're going to type single quote hello
and single quote and press
enter this is a string and it represents
the text hello and we've actually seen
this code before in the first lesson the
first piece of code that we learned was
alert Open Bracket single quote hello
single quote close bracket and
semicolon this code creates a popup on
the page if we press
enter it creates a popup now in inside
these brackets we actually created a
string this string is the text that
appears in the popup so as you can see a
string represents
text let's press
okay and now let's learn the syntax
rules for strings to create a string we
just write some text like hello and then
surround this text with single quotes
one at the beginning and one at the end
we can also add strings together for
example let's type the string
sum plus the string
text and press
enter when we add two strings it
combines the strings together into a
bigger string and this makes sense we're
adding two pieces of text together we
can also add more than two strings at a
time
for example we can type the string
sum plus the string
more plus the string
text if we press
enter the computer will combine all
three strings into one big string by the
way this is called concatenation when we
combine strings together now in in the
previous lesson we learned about numbers
numbers and strings are two different
types of values in JavaScript they
represent different things and we can
actually check what type of value
something is using this code type of and
then space and then a value like the
number two if we press
enter type of will tell us that two
is a number if we do type of quote hello
quote and press enter it will tell us
that hello is a
string now what if we added a string and
a number together for example let's type
the string
hello plus the number three and press
enter
so when we add a string and a number
JavaScript will automatically convert
this number into a string so this gets
converted into the string hello plus the
string
three and then it combines them together
into the string hello 3 this feature is
called type coersion or automatic type
conversion okay now that we understand
understand the basics of strings let's
do some practical examples we're going
to use strings and numbers to create the
text in this section of the project
first make sure that in your cart you
have one basketball with free shipping
and you have one t-shirt also with free
shipping and you have no other
products let's scroll up and we'll start
by creating this text in the top right
so this is the cost of the products but
this time we're going to have a dollar
sign so instead of just a number this
will be
text so one thing we can do to create
this text is just type out the string
directly like quote doll
28.94 and
quote however let's actually calculate
this number using math
remember the advantage of JavaScript is
that it's able to do
calculations so instead of typing out
28.94 we're just going to create the
string Dollar Sign Plus and we're going
to calculate this number using math so
we're going to add the cost of the
basketball which is
$2.95
plus the cost of of the t-shirt which is
$7.99 if we press
enter unfortunately this doesn't look
right instead of doing math and adding
these two numbers together it just sort
of put the numbers one after another
into the string so why is this happening
JavaScript adds from left to right so
the first step is to add these two
values and as we learned if we add a
string and a number JavaScript will
automatically convert this number into a
string so the result of this calculation
will be the string doll
2.95 and
quote the next step is to add
7.99 so it will add
7.99 and now we're adding again a string
and a number
so JavaScript will automatically convert
this number into a string and combine
them together that's why it puts
7.99 at the end of this string instead
of doing
math so what we actually want to do here
is to add these two numbers first and
then combine the total with the string
so how do we do this the solution is
that strings also follow the order of
operations just like numbers and
remember in the order of operations we
can use brackets to control which part
of a calculation gets done first so
let's type this calculation out again
the string Dollar Sign Plus 20.95%
close bracket around this
calculation this tells the computer to
calculate this number first using math
and then combine this result with the
string after if we press
enter now this is doing math and it
solves our original problem
unfortunately now we have another
problem this math is inaccurate so
remember from the previous lesson doing
calculations with floats can sometimes
cause
inaccuracies and the best practice when
calculating money is always calculate in
cents and then convert back to dollars
at the end so at the bottom here we're
going to add the string
Dollar Plus open bracket and instead of
$20.95 we're going to add
2,95 Plus
$7.99 and close bracket and then at the
end we're going to convert this number
back to Dollars by dividing by 100 if we
press
enter this will give us the text that we
see in the final
project again strings follow the same
order of operations as numbers brackets
are always calculated first multiply and
divide are done next and add and
subtract are done after so adding this
result to the string is the last
step now let's do a more complicated
example let's use strings and numbers to
create this entire line of text not just
the dollar text to create this we're
going to go from left to right let's go
back in our console and we're going to
start with the string
items Open Bracket and here we could
just type two and close bracket but
let's actually calculate this number as
well using math so this number is the
quantity or the number of products in
our cart let's go back to our console
we're going to end the string here and
we're going to add and we're going to
calculate the quantity
so we have one basketball plus one
t-shirt again we run into the same
problem as before this gets calculated
first and results in a string and then
it will just combine the one at the end
of the string instead of doing math to
solve this we're going to use brackets
again so around the 1 + 1 we're going to
add Open Bracket and close
bracket this tells the computer to add
the numbers first and then combine it
with a
string all right let's keep going from
left to right we're going to add the
rest of the string quote close bracket
colon and let's just use a space to
represent the space between these two so
we'll type a space dollar sign and then
we're going to calculate this number
again and add it to the string so we'll
end the string and then plus and we
already did this calculation up here so
we can select this and then
rightclick
copy and here right click and
paste and press
enter by the way if you paste in the
console you might see this warning
message
to fix this you can type allow
pasting and press
enter and now you can
paste and that's how we create this
first line of text using strings and
numbers we break up the string into
Parts calculate the numbers and then add
the parts back
together all right now let's take these
strings that we created Creed and do
something with them let's create a popup
and display this first line of text
inside the popup we'll go back to our
console and type the code for creating a
popup
alert Open Bracket close bracket
semicolon and then inside the popup
we're going to display this string so
let's just make a copy of this code
we'll select it right click
copy and between the brackets right
click and
paste if we press
enter the computer displays a popup with
the first line of text of the final
project
inside so that's how we use strings to
create the text in the final project and
once we create the strings we can use
them in other JavaScript
code in in the rest of this lesson we're
going to learn more details about
strings in JavaScript there are actually
three ways to create a string the first
way is to use single quotes which we
already learned for example we can type
single quote hello and single quote and
press
enter the second way to create a string
is to use double quotes for example
double quote hello and double quote and
press
enter this creates the exact same string
as single quotes so which one should we
use to create a string single quotes or
double quotes in JavaScript I recommend
using single quotes by default they're a
little easier to read and type there is
one situation where double quotes might
be useful and that is is if we have a
single quote inside the string for
example if we type the
string I'm
learning
JavaScript and single quote and press
enter this doesn't work because there's
a single quote inside the string and
this single quote will end the string
early to solve this we can create the
string using double quotes for example
double quote I'm
learning
JavaScript and double quote and press
enter so now this works because we
created the string using double quotes
the single quote no longer has a special
meaning and it will no longer end the
string early so this is a situation
where double quotes might be useful
otherwise we use single quotes by
default now there's actually another
solution to this problem other than
using double quotes and that's by using
an escape character so a character is
one letter number or symbol in a piece
of textt for example the text hello has
five characters h e l l
o a character can be a letter in number
or also a symbol these are all
considered
characters now in addition to these
characters we have a special set of
characters we can also use in a string
called Escape characters an escape
character looks like this a backslash
and then another character like single
quote this combination actually counts
as one character in a string this
character creat creat a single quote
that is just text it doesn't have a
special meaning and it doesn't start or
end strings for example we can create
this string with single quotes again so
single quote I and this time we'll use
the Escape character back slash single
quote and then M
learning
JavaScript and single quote and press
enter and now this works because the
Escape character back SL single quote
creates a single quote that is just text
it doesn't start or end the
string another Escape character that's
useful to know is back SL double quote
this creates a double quote that is just
text it doesn't start or end a
string the last Escape character we'll
learn in this lesson is back
sln this is called the new line
character this Escape character doesn't
create the letter N anymore it creates a
new line of text for example let's
create a popup using
alert Open Bracket close bracket and
semicolon and then inside the brackets
we're going to create a string sum and
then back
sln text and single quote if we press
enter you'll notice that this Escape
character created a new line of text in
the popup and that's why we call this
the new line character so that's how
Escape characters work they are a set of
special characters that start with back
slash and we can use them in a
string now let's press okay
and we're going to learn the Third Way
of creating a string in JavaScript which
is using back ticks for example let's
type in our console and we'll type
backtick hello and backtick and press
enter this creates the same string as
single quotes and double quotes strings
created with backx actually have a name
we call these template strings and they
have a name because they have some
special features the first special
feature of template strings is called
interpolation interpolation lets us
insert a value directly into a string
for example let's say we want to create
the first line of text in our project
earlier in this lesson we created this
text with concatenation which means we
broke it up into parts and added them
back together in interpolation gives us
a much easier way to do this we'll go to
our console and we'll create this text
using a template string because
interpolation is only a feature of
template strings so we'll type backtick
items Open Bracket close bracket and
back tick and now between these brackets
we want to insert the quantity or the
number of products in our cart to insert
this with interpolation we're going to
type Dollar open curly bracket close
curly bracket so this combination of
characters allows us to insert values
directly into the string between these
curly brackets we can calculate the
quantity which is one basketball plus
one
t-shirt this will add 1 + 1 which equals
2 and then insert it directly into the
string
let's keep going and create the rest of
this line so we're going to type at the
end a Colin space and dollar and now
we're going to insert another value into
the string which is the cost of the
products to insert another value we're
going to type Dollar open curly bracket
close curly bracket again in between the
curly brackets we're going to calculate
the cost of the products
which is
2,95
plus
$7.99 and we'll surround this in
Brackets to make sure we calculate this
first and at the end we're going to
convert back to Dollars by dividing by
100 if we press
enter this creates the first line of
text again in our final project
if we compare this code which uses
interpolation to our previous code which
uses concatenation you can see that
interpolation is a much cleaner way of
inserting values into a string so
interpolation is a recommended
solution next template strings have
another special feature called
multi-line strings let's go to our
console and we're going to type a
backtick
sum and then press
enter and text and back tick notice that
this string is on multiple lines so we
call this a multi-line string and this
feature is only available for template
strings if we press
enter you can see that the new line in
the string just creates the new line
Escape character that we learned earlier
so that's the multi-line string feature
of template strings we're going to use
multi-line strings a lot later in this
course but for now I just wanted to
introduce you to this feature now you
might be wondering again what should we
use to create a string single quotes or
template strings even though template
strings have more features I find that
most JavaScript code still uses single
quotes by default so my personal
recommendation is to use single quotes
by default and if we need to insert a
value into the string or type the string
on multiple lines then use template
strings and that's the end of this
lesson in this lesson we learned about
strings a string represents text we
learned how to use strings and numbers
to create the text in our final project
we learned three different ways of
creating a string single quotes double
quotes and back ticks or template
strings we learned about Escape
characters and we learned two useful
features of template strings
interpolation and multi-line
strings here are some exercises to help
you practice working with strings
so far in this course we've learned some
basic features of JavaScript like
numbers and strings in this lesson we're
going to learn how to use HTML CSS and
JavaScript together because as I
mentioned at the beginning of this
course we use all three Technologies to
build build a full
website HTML creates the content of a
website like the buttons and the text
CSS changes the appearance of the
website and JavaScript makes the website
interactive the first thing we're going
to do is review the basics of HTML and
CSS that we will need for the rest of
this
course now in order to write HTML and
CSS code we need to install another
piece of software called a code editor a
code editor helps us write and organize
our code the most popular code editor
for web development is called vs code or
Visual Studio code to install vs code
you can go to google.com in your
browser search for VSS
code click the result
and follow the instructions to download
and
install once we've installed VSS code
we're ready to review the basics of HTML
and
CSS we'll start with
HTML HTML stands for hyper text markup
language and just like JavaScript HTML
is also giving instructions to a
computer now unlike JavaScript we can't
use the console to write and run HTML
code instead we write HTML code inside a
file using our code editor let's do that
right now we'll start by going to our
desktop so I'm going to close my browser
to go to my
desktop and then we're going to create a
new folder so we can right click new
folder this folder is going to contain
all the code that we write in this
course let's name this folder JavaScript
dasc next we're going to open this
folder in our code editor so let's open
vs
code and then we'll click
file open
folder and find the folder that we just
created for me it's on the
desktop and it's this folder right right
here so we're going to select the folder
and then click select
folder now we can close this startup
message and we're going to create an
HTML file we're going to click this icon
to create a new
file and we're going to name this file
website do
HTML and press
enter ending the file name name with
HTML tells a computer that this file
contains HTML code rather than just
text now let's review some basic HTML
code we're going to type the code less
than button greater than and we also
need to type less than slash button
greater than but our code editor might
autocomplete this for us so this code
tells a computer to create a button and
inside the button we're going to have
the text
hello now let's save this file by
clicking
file
save or by typing contrl s on Windows or
command s on
Mac now to run this HTML code we're
going to open this file in our browser
let's go back to our desktop
we're going to open the folder that we
created find the HTML file select it and
then right click open with Google
Chrome as you can see we have a website
and we created a button with the text
hello inside and if we look back at our
code that's exactly what we told the
computer to do
so just like JavaScript HTML is also
giving instructions to a
computer let's review some more HTML
code first I'm just going to rearrange
my windows here so that it's easy to see
the website side by
side next we're going to click the end
of the first line and press enter to
create a new line and we're going to
type the code less than P greater than
and we also need to type less than SLP
greater than so this code creates a
paragraph and inside the paragraph we're
going to put some text for example
paragraph of text now let's save our
file by typing contrl s on Windows or
command s on
Mac and to update our website to the new
code we're going to go to our website
and click refresh or typ controlr on
Windows or command r on
Mac and now you can see that the
computer created a paragraph of text
just like we told it to do and that's
the basics of HTML the computer reads
our code and then follows our
instructions one by one first it creates
a button and then it creates a paragraph
of text
now let's review the syntax rules for
HTML each of these things that were
displaying on a web page these are
called HTML elements so a button is a
type of HTML element and a paragraph is
another type of HTML element to create
an element we start with a less than
symbol and then the element name like a
button and then the greater than symbol
so this whole thing is called an HTML
tag this tells a computer to create a
button
element every HTML tag needs a matching
tag the matching tag follows the same
syntax except it has a slash in front of
the element name so this is called the
opening tag and this is called the
closing tag you can think of the opening
tag as the start of the button and the
closing tag tag as the end of the button
and in between we have the contents
inside the button in this case it's the
text
hello in addition to text we can also
have elements inside an element for
example we can go to our paragraph
element and we can add a button inside
so less than button greater than and we
also need less than SL button greater
than and then inside the button we'll
also have the text
hello if we save this file and refresh
the
page now our paragraph element has a
button element
inside by the way this is called nesting
when we have an element inside another
element the last syntax rule we have to
review is that in HTML if we have
multiple spaces for example if we go
here and type multiple
spaces multiple spaces are combined into
one space on the web page so if we save
this code and
refresh you'll notice that all of the
spaces that we added only show up as one
space on the web page in addition in
HTML new lines also count as spaces so
if we go back to our
code and we type here and press enter to
create a new line and then save and
refresh notice that the new line doesn't
appear on the web page and that's
because this new line here is the same
as spaces in HTML so all of these get
combined into one space on the web
page at first this might seem a little
weird but this feature gives us a lot of
flexibility when organizing our h ml
code for example we can go into our code
and add a new line here to separate
these two elements and make our code
easier to read another thing we usually
do to make our code easier to read is to
put the contents of an element on its
own line for example we're going to type
here and press enter and here and press
enter
again to put the contents of the button
Buton on its own line now it's a lot
easier to see where this button starts
and where it ends we can do the same
thing with the paragraph We can type
here and press enter and type here as
well and press enter and then remove
some of the Extra
Spaces to put the content of the
paragraph on its own line and now if we
save our
file and refresh
you notice that none of the new lines
that we added appear on the web page by
the way a web page is a single page like
the homepage or the cart page together
we call this a
website so that's the basics of HTML and
HTML
syntax now let's review CSS CSS stands
for cascading style sheets and CSS
changes the appearance of our website
let's review some CSS code we're going
to write our CSS code inside our HTML
file first let's type here and create
some new lines at the top and then at
the top we're going to create a special
HTML element called the style element so
let's type less than style greater
than and we also need the closing tag
less than SL style greater than so the
style element is unique because it
doesn't appear visibly on the page
instead the purpose of the style element
is that it lets us write CSS code
inside so inside here let's press enter
to create a new line and we're going to
type
button open curly bracket close curly
bracket and then inside the curly
brackets we're also going to press enter
to create a new line so this is CSS code
and this code tells a computer to change
the appearance of all buttons on the
page and then inside these curly
brackets we can tell the computer how to
change the appearance for example we can
type
background- color colon red and
semicolon if we save
and
refresh you can see that this CSS code
changes the appearance of all buttons on
the page and changes their background
color to
Red let's do another example we're going
to go back to our CSS code going to type
here and press enter to create a new
line and we're going to add color colon
white and semicolon let's save
and
refresh and this CSS code changes the
text color of all buttons on the page to
White let's do one more example we're
going to type the
code order Colon none and
semicolon let's save this and
refresh and this CSS code removes the
border for all buttons on the page
and that's how CSS works we tell the
computer which elements we want to
change and then how to change the
appearance of these
elements now let's review the syntax
rules for
CSS this part of the CSS code is called
the CSS selector it tells a computer
which elements we want to change in
other words it selects which elements to
change inside the curly brackets we have
some CSS Styles this tells a computer
how to change the
appearance for each style the left side
is called the CSS property this tells a
computer what we're changing the right
side is called the CSS value this tells
a computer what we're changing the
property to for example this style
changes the background color to
Red we use a colon to separate the
property and the value and a semicolon
at the end to tell the computer that
this is the end of a style so that's the
basic syntax of CSS we tell the computer
which elements we want to change and
then how to change the appearance of
these
elements the next thing we're going to
review is HTML
attributes right now this CSS selector
changes the appearance of all but
buttons on the page however what if we
only want to change the appearance of
this one button and we want to style the
other button differently how do we do
that we're going to review a feature of
HTML called attributes attributes change
the behavior of an element for example
we're going to go to the opening tag of
the first button and then here we're
going to add an HTML attribute by typing
space
title equals double quotes and then in
between the double quotes we're going to
type tool
tip so this is an HTML attribute and
this attribute adds a tool tip to this
button if you're wondering what a tool
tip is if we hover over some code in our
code editor it'll show us this sort of
popup with more
information this is called a tool tip
when we hover over something and this
shows up so if we save our
file and refresh the web page and now we
hover over our button we can see that
the HTML attribute added a tool tip to
our button and then inside the double
quotes is the text inside the tool tip
for example we can actually change this
to good
job and if we save save and
refresh and hover over our button the
text between the double quotes is what
shows up in our tool tip so that's an
example of an HTML
attribute now let's review the syntax
rules for
attributes we always put attributes on
the opening tag and we add a space
between the element name and the
attribute to separate them on the left
side is the attribute name this tells
the computer what we're changing about
this element on the right side is the
attribute value this tells a computer
what we're changing this attribute to
for example here we're changing the tool
tip of this element to good job we
separate the name and value with an
equal sign and make sure there are no
spaces around the equal sign and we
surround the value with double quotes
now let's go back to the original
problem how do we style these buttons
differently we can do this using a very
important attribute called the class
attribute let's review that right now
we're going to go back to our button and
then here we're going to type space
class equals double quotes and then
inside the double quotes we're going to
type red Das
button so the class attribute sort of
adds a label to an element so here we
labeled this button as a red button and
now that we labeled this element we can
select it in
CSS to do that we're going to go to our
CSS code we're going to remove the
button
selector and replace it
witht
red-
button when we start the selector with a
DOT this means that now we're looking
for a class so here we're going to look
for all elements with the class red dash
button which is only this element if we
save and
refresh now only the elements with the
class red button gets these Styles we
can also add the same class to multiple
elements for example we can go to to our
other
button and add the class equals
red-
button if we save and
refresh now these Styles get applied to
both buttons again because they both
have the class red-b button if we want
to style this button differently we just
give it a different class for example we
can change this to Yellow yellow dash
button and then in our CSS we can add
another selector so we can type dot this
means we're going to select a class and
we're going to select the yellow Das
button class open curly bracket close
curly bracket and then inside here we
can add some styles for the yellow
button for
example background Das color colon
yellow and
semicolon now let's save and
refresh and that's how we use the class
attribute in HTML to modify specific
elements the final thing we need to
review is something called the HTML
structure let's go back to our website
we're going to find a blank area and
then
rightclick and then click inspect
so we already learned about the console
tab here we can write and run JavaScript
code now we're going to go to the
elements tab which is for HTML and CSS
so in the elements tab we can see all
the HTML on the page as well as all the
CSS on the page and we can play around
with the CSS if we
want now if we go back to to the
HTML you'll notice that our web page has
some elements that we didn't add before
the HTML element the head element and
the body
element so this is the structure that
we're supposed to follow when writing
HTML in our code we didn't follow the
structure so the browser actually adds
it for us
automatically however it's still best
practice to follow this structure in our
code because it gives us access to some
more features of
HTML let's review the HTML structure and
add it to our
code we're going to type up here and
we're going to create some new
lines and now every HTML file is going
to start with less than
exclamation dock type in capitals and
then space
HTML and greater
than this is not an HTML element it's a
special line of code that tells a
browser to use a modern version of
HTML if we don't have this the browser
might fall back to an older version of
HTML that has less
features next we're going to create an
HTML element so less than
HTML and greater
than the HTML element represents the
entire web page
so everything on the web page should go
inside this
element and then inside the HTML element
we're also going to split it up into two
sections the head
element and the body
element so the body element is supposed
to contain everything that is visible on
the page in our example that would be
the buttons and the parag graph so let's
actually select this
code and we're going to
rightclick and
cut and then inside the
body we're going to right click and
paste the head element contains
information about the page in general
everything that is not visible on the
page goes inside the
head in our examp example that would be
the style element so let's select this
as
well we're going to rightclick and
cut and then inside the
head we're going to right click and
paste and at the bottom let's just clean
up by removing all of the extra new
lines so this is a structure that we're
supposed to follow in all of our HTML
files as you can see this structure uses
a lot of nesting or elements inside
elements to organize our
code okay so what are the benefits of
following this structure one benefit is
that there are other elements that we
can use inside the head for example
let's type here press enter and we're
going to add the title element so the
title element sets the text in the
tabs inside we can type HTML CSS review
if we save and refresh the title will
show up in the
tab so this is an example of an element
that we can now add in the
head another benefit that we get from
this structure is the ability to
automatically refresh our web page when
we change our code
so far every time we change our code we
have to save and then manually refresh
the web page we can actually automate
this by following the structure and then
installing a VSS code
extension so let's click the extension
area and we're going to search for the
extension live
server and click install
once we have that installed we're going
to change a
setting let's open the settings by
clicking this icon in the bottom left
and then click
settings at the top we're going to
search for live
server and we're going to look for a
setting called live server custom
browser and we're going to change this
to
Chrome now now if Google Chrome is
already your default web browser you
don't need to do this step but it's nice
to
know now let's close the
settings and go back to our
code next instead of opening this file
directly in the browser like before
we're going to use live server to open
this file to do that we're going to
rightclick this file in our code editor
and then click open open with live
server if we open a file with live
server this web page will automatically
refresh when we change our
code for example we can go here and
change the background color to Green if
we save live server will automatically
refresh the web page so we don't have to
do that back and forth
anymore let's just change it back to Red
so that the class last name makes sense
and
save and we can also close the previous
tab so this is the HTML structure it
gives us access to more features of
HTML and this is all we need to review
about HTML and CSS for now if you want
to learn more you can check out my HTML
and CSS full course in the video
description by the way to find the links
mentioned in each lesson you can click
here in the
description and this page contains all
the links mentioned in each
lesson before we add JavaScript to our
website we're going to review some VSS
code
setup so you'll notice that many of
these lines have spaces at the front
these spaces are called in indents and
indents make our code easier to read for
example we can easily tell that this
code is inside the brackets because it
has an extra indent in the
front if we didn't have indents here's
what the code would look like it's a lot
harder to
read to add an indent we can type at the
beginning of the line and press
tab to remove an indent we can press
shift tab or just use
backspace now by default VSS code uses
four spaces per indet however in HTML
CSS and JavaScript we usually use two
spaces per indet so we're going to
update this setting let's go to our
settings by clicking this icon in the
bottom
left and then click
settings and at the top we're going to
search for tab
and we're going to change the tab size
from 4 to
2 now let's close the
settings and we're also going to change
the indents for this file we're going to
go down here and click select
indent and we're going to choose indent
using
spaces and then click
two and now if we type at the start of a
line and press tab it will only add two
spaces per
indent so let's reformat our code to use
two spaces per indent instead of four
first we're going to remove all the
indents in our code a shortcut for this
is to select all of these
lines and press shift tab to remove one
indent for each line so we're going to
keep pressing shift tab until we remove
all the
indents next next we're going to add the
indents back using a similar shortcut
we're going to select the head
element and press tab to add one indent
for each line and then select everything
inside the head and press tab to add
another indent and then select
everything inside style and press Tab
and then inside each of these brackets
we're going to select the lines press
Tab and then here press tab we'll do the
same thing for the body element we'll
select all these lines and press tab
we'll select everything inside the body
press Tab and then inside each of these
elements we're going to press Tab and
press
tab now if we save our website will look
the same because all we did was adjust
the
indents so there's one other setting in
vs code that we're going to set up which
is line wrapping if you look at this
line of code you can see that it's
really long and we need to scroll
horizontally to see the rest of the line
instead we're going to make this line
wrap around if it gets too long let's go
back into our settings by clicking here
and then click the
settings and then up here we're going to
search for
wrap and we're going to look for editor
word wrap and we're going to turn this
on now if we close our settings and go
back to our
code this line which is really long will
wrap around to the next line instead of
us having to horizontally
scroll so that's the vs code setup that
we need two spaces per indent and line
wrapping finally we're going to add
JavaScript to this website so we learned
that we can use the console to write and
run JavaScript well there's actually
another way to run JavaScript which is
inside an HTML file let's learn how to
do that so we learned that HTML has a
special element that runs CSS code
called the style element while HTML has
another special element that runs
JavaScript code and this element is
called the script
element so inside
body at the bottom of the body we're
going to add less than script greater
than and the closing tag less than SL
script greater than and inside the
script element we can put some
JavaScript code we're going to add the
code alert Open Bracket quote hello
quote close bracket and semicolon if we
save
live server will refresh the page and
now you notice that the computer now
runs our JavaScript code just like it
did in the console it creates a popup
with the text hello
inside and we usually put the script
element at the bottom of the body
because we want the web page to be
created first and then we use JavaScript
to make it
interactive for the rest of this course
we're going to run our JavaScript code
using using an HTML file the console
that we used in the previous lessons is
more of a way to try out JavaScript code
we wouldn't use a console for a real
website in addition to the script
element we have another way to run
JavaScript code inside HTML and that's
by using an attribute let's go back to
our first button and here we're going to
add another attribute so let's type
space and this time we're going to add
the
onclick attribute equals double
quotes So this attribute will run
JavaScript code whenever we click this
button that's what onclick means between
the double quotes we can write some
JavaScript for example let's press enter
enter and then here we're going to type
alert
Open Bracket
quote good job quote close bracket and
semicolon now if we
save live server will refresh the page
and run this line of JavaScript code
let's press okay and now if we click
this
button it will run this line of
JavaScript code and create a popup with
a text good job inside
so those are two places where we can run
JavaScript code the script element and
the onclick attribute the code in the
script element runs first when the page
is loaded the code in the onclick
attribute runs after when we click the
button on the
page and that's how we use HTML CSS and
JavaScript together on a website
notice that everything starts from
HTML HTML first creates the website and
then inside the HTML we can run CSS code
to change the appearance and we can run
JavaScript code to make the website
interactive now let's learn some new
features of JavaScript that we haven't
seen yet in this course the next feature
we're going to learn is called comments
comments are pieces of code that the
computer ignores so let's create our
first comment we're going to go down to
the script element
here and type forward slash forward
slash so this is a comment anything
after the double slash will be ignored
by the computer so we can type anything
we want like this is a
comment if we save it ignores this line
and creates the popup in the next
line now let's close this popup and
learn why we use
comments comments are useful for
providing more information for people
reading our code for example we can
create a comment above this code like
this code creates a
popup this comment helps others and
ourselves understand what this code does
so that's one way we use
comments another way we use comments is
if we don't want to run some code
anymore but we also don't want to delete
it for example this code creates a popup
every time we refresh the page and this
can be
annoying so I want to stop running this
code but I also don't want to delete it
because you might want to review this
code
later so what we can do here is to add a
double slash in front of this line to
turn this code into a
comment now if we save the computer will
ignore this line of code and not create
the
popup this is called commenting out the
code it's useful if we don't want to run
some code anymore but we also don't want
to delete it for informational purposes
so JavaScript has another Syntax for
writing comments and that syntax is
slash star and star
slash here anything between the stars is
a comment this is called a multi-line
comment because between the Stars we can
write a comment on multiple lines for
example we can type multi enter line
Line enter
comment on the other hand double slash
is known as a single line
comment now just like JavaScript HTML
and CSS also have comments but they use
a different
syntax if we scroll up to our
HTML here we can type less than
exclamation
d-h and we also need dh- greater than so
anything between these double dashes is
a comment for example this is a
comment in CSS to create a comment we
can type slash star star slash so it's
the same multi-line comment as
JavaScript between the Stars we can add
a comment so this
is a
comment if we save our
file nothing changes on our web page
because comments are ignored by the
computer the last feature of JavaScript
we're going to learn is called
console.log let's go back to our
code and at the bottom in the script
element we're going to type the code 2 +
2 so we learned that this code in Java
script does some math however if we save
this
file where is the result of this math so
we might think that the result will show
up in the console but if we
rightclick click
inspect and then click the
console you'll notice that the result
doesn't show up here either and that's
because before we were running 2 + 2
inside the console so the result shows
up in the console but now we're not
running this code in the console anymore
we're running this code on the web page
so how do we see this
result the solution is we're going to
redirect this result back to the console
to do that we're going to use this piece
of
code
console.log Open Bracket close bracket
and
semicolon console.log will display
whatever's between the brackets back in
the console so if we move this code
between the brackets so we select this
and then right click cut and then
between the brackets right click paste
and
save the result of this code is
displayed back in the console
and console.log works for any code that
we learned so far for example we can use
strings so let's create a new line and
type
console.log Open Bracket close bracket
semicolon and then between the brackets
let's type some
strings quote Su quote plus quote text
quote
and save this
file again it will display the result of
whatever's between the brackets back in
the
console so that's how we see the result
of JavaScript code that is running in a
file we use
console.log and that's the end of this
lesson in this lesson we reviewed the
basics of HTML and CSS we set up our
code editor vs code we learned how to
load JavaScript inside an HTML file
using the script element and the onclick
attribute we learned how to create
comments and we learned how to use
console.log thanks for watching this
course so far if you want to support
this channel you can check out the
premium version of my courses just like
this one where you can get a certificate
of completion and a learning platform if
you're interested in extra videos from
me more in-depth videos and behind thes
scenes content you can check out these
links here you can also support the
channel by liking the video subscribing
and sharing this video with others
thanks again and let's continue with the
course here are some exercises you can
try on your own to practice what we
learned in this lesson
in this lesson we're going to learn the
next feature of JavaScript called
variables and we're going to use
variables to build a simple version of
the cart quantity feature of the final
project
first let's create a new HTML file just
for learning variables we're going to go
to our code editor and click this icon
to show our files and then click this
icon to create a new
file and we're going to name this file
05-
variables.
HTML and press
enter so the 05 just means that this
file is for lesson
five let's also add the lesson number to
website.
HTML we'll select this file and then
rightclick
rename and then at the front We'll add
04- and press
enter next we're going to copy all the
code in website. HTML to variables.
HTML so let's click in this file and
we're going to select all of this code
by typing control a on Windows or
command a on
Mac and then we're going to
rightclick
copy and then inside variables.
HTML rightclick and
paste let's click this icon to hide our
files for now and we'll prepare this
file for this lesson so let's scroll up
to the top and first we're going to
change the title to
variables next we're going to delete all
the CSS because we're going to start
over and we're going to delete all the
HTML except for the script
element and let's delete all the
JavaScript from the previous
lesson and finally let's save
and we'll open this file in our browser
by right clicking and then open with
live
server and now we can close the previous
tab and the previous code for
now now we're ready to learn
variables first of all what is a
variable a variable is like a container
we can save a value like a number or a
string inside a variable and then then
use it later Let's do an example and
create our first
variable inside the script element we're
going to type the code let and space the
word let creates a new variable and now
we're going to choose a name for our new
variable let's name this variable
one so this creates a variable or a
container named variable one and now we
can save a value inside this variable to
do that we're going to type space equals
space and then a value like a number or
a string so let's save the number three
inside and we'll type a semicolon at the
end so here we use the let to create a
new variable we named this variable
variable one and we saved the value
three inside this
variable now that we saved this value we
can use it later for example let's type
a new line and type the code
console. log Open Bracket close bracket
and
semicolon remember from the previous
lesson that this code displays
whatever's inside the brackets in the
console so far we put a value inside
like the number
two if we save and then go to our
website and open the console so right
click
inspect and then click the
console we can see that the number two
was displayed in the
console so now let's try replacing this
value with the variable that we created
above so instead of two we're going to
console.log variable one
if we
save notice that it now displays three
so it's displaying whatever value is
saved inside the variable as you can see
we can save a value inside a variable
and then use that variable later
on let's do another example we're going
to create another variable so we're
going to create some new lines and we'll
type
let and this time let's name this
variable
calculation and we're going to type
space equals space to save a value
inside this new variable and this time
instead of just a number we're going to
save a
calculation 2 + 2 and semicolon so this
will calculate 2 + 2 and then save the
result which is four into the
variable if we call
console. log Open
Bracket
calculation and semicolon and
save it will show us that the value for
is saved inside
calculation now let's try this code
we're going to type a new line and then
console. log Open Bracket and
calculation again
and plus 2 and
semicolon so here we're using a variable
inside a
calculation what this does is that it
takes whatever value is saved inside the
variable right now it is four and then
substitutes that value into the
calculation so this will be 4 + 2 which
equals
six if we
save we can see that in the console it
display blade
six so we can use a variable wherever we
use a value and JavaScript will
substitute whatever is inside the
variable into the
code let's do another example we're
going to type some new lines and create
a new variable again using
let and we're going to name this
variable
result and we're going to make it equal
to calcul
ation plus 2 and
semicolon so this does the same thing as
a code before it will take whatever
value is inside calculation which is
four and substitute it into this code so
we get 4 + 2 =
6 but this time we have an extra step
we're going to save this result which is
six into another
variable so so if we
console.log
result and
save we can see that six was saved into
the result
variable again we can use a variable
wherever we use a value now in addition
to numbers we can save any type of value
in a variable including
strings for example let's create a new
variable using
let and let's name this
message and we're going to save inside
this variable a string this time so
quote hello quote and
semicolon again we're going to
console.log this variable so
console.log and
message and a semicolon at the end if we
save
it will show us that the string hello is
saved inside this
variable okay now that we learned how
variables work let's learn the syntax
rules for
variables the word let creates a new
variable and then we give the variable a
name so we can name variables almost
anything we want except for a few
restrictions number one we can't use
special words like let as a variable
name
that's because let already has a special
meaning in JavaScript it creates a
variable so let is a reserved word
however we can use let one or let two as
variable names we just can't use
let number two we can't start a variable
name with a number if we start with a
number JavaScript will think this is a
number instead of a variable name
however we can use numbers in the middle
or the
end lastly we can't use most special
characters like these or a space in a
variable name however there are two
special characters we can use dollar and
underscore so those are the rules for
naming
variables and then to save something
inside a variable we just use the equal
sign and then the value we want to save
and that's it after we create a variable
we can start using it in the rest of our
code now there's one last part of the
syntax that we haven't learned which is
the semicolon we've seen semicolons in
many places already in JavaScript a
semicolon means this is the end of an
instruction it's similar to a period in
English in English a period means this
is the end of a
sentence so here this semicolon tells
Java script that this is the end of an
instruction and now after this we can
add another instruction like
console. log Open Bracket and then the
string semicolon and a semicolon at the
end if we
save it will run these two instructions
one after another without any
problems so if we didn't have the
semicolon here and and we save it
wouldn't work because JavaScript thinks
that this entire line is one
instruction so we need semicolons to
separate different instructions in
JavaScript if we
save everything goes back to
normal so JavaScript is a little special
because it has a feature called
semicolon
insertion that means it will try to
insert the last semicolon in a line of
code automat automatically for example
if we removed the last
semicolon and
save this code will work without that
semicolon and that's because JavaScript
inserts the last semicolon
automatically however a lot of companies
still prefer to use semicolons in their
JavaScript code because semicolon
insertion can sometimes put the
semicolon in the wrong place for this
reason we're also going to use sem
colons in this course to help you get
used to JavaScript code with
semicolons next we're going to learn how
to change the value that is saved inside
a variable for example here we save the
number three inside variable one now
we're going to change the value saved
inside variable one to do that we're
going to go to the bottom and create
some new
lines and we're going to type the
variable name again so
variable one and now to change the value
saved inside we're just going to type
the equal sign and then a different
value like five and
semicolon and now if we console.log this
variable
console.log variable 1 and semicolon and
save it will show us that five is now
now saved inside variable
one notice also that if we scroll up to
the top the first console.log still
displays the value three and that's
because at this point in the code
variable one still contained three we
didn't update the variable yet so when
we first saved a value inside this
variable this is called assigning a
value to a
variable then when we change the value
inside this varable iable this is called
reassigning a value to a
variable now let's learn the syntax
rules for reassigning a value notice
that we don't use the word let when
reassigning that's because let creates a
new
variable so if we try to use let again
it would try to create a new variable
named variable one however variable one
already exists and we can't create two
VAR variables with the same name so this
would cause an error instead to reassign
a variable we just type out the variable
name and make it equal to something else
so that's the Syntax for reassigning a
variable now we're going to do one last
example before working on the project
let's go to the end of our code we're
going to type some new
lines and this time we're going to re
reassign variable one again so we can
reassign a variable as many times as we
want so let's type variable 1 and then
equals and we're going to type variable
1 + 1 and
semicolon so we learned earlier that we
can use a variable inside a calculation
and it will substitute whatever value is
inside the variable
here we're also using a variable inside
the calculation but we're using this
variable
itself so it's essentially taking this
variable increasing it by one and then
saving it
back if we
console.log this variable variable
one and
save variable one now contains six so it
took the previous value in variable one
which was five added one and then saved
it
back so this is how we increase the
value of a variable by a certain
number okay now that we know how to
create and reassign variables we're
ready to work on a project so I actually
prepared a project that we can do for
this lesson and we can see this project
by going to our browser clicking at the
top and and typing
super simple
dodev SL projects SLV
variables and press
enter so we're going to work on the cart
quantity feature of the final project so
in the final project we have a number in
the top right corner that shows how many
products are in our cart when we click
the add to cart button this quantity
will increase
so what you see here is a simple version
of the cart quantity feature that we can
create right now let's go over how it
works first make sure you have the
console open on this page now when we
click the show quantity button it will
show us that there are zero products in
our cart if we click the add to cart
button it will increase the quantity by
one and display it in the console
if we click add to cart again it will
increase the quantity by one again now
in the final project we can also add
more than one product at a time using
this
drop-down for now we're going to build a
simpler version of that we're going to
use the plus two and plus three buttons
to add multiple products so when we
click the plus two button it will
increase the quantity by two and display
it in the console
and when we click the plus three button
it will increase the quantity by
three and finally when we click the
reset cart button it will reset the
quantity back to zero and display this
message in the
console so now that we understand how
this project Works let's build this step
by step first let's create a new HTML
file just for this project we're going
to go to our code editor and click this
icon to show our files and then click
this icon to create a new
file let's name this file 05
dcart D
quantity.
HTML and press
enter next let's open variables. HTML
and we're going to copy all the code
here into our new
file let's type control a on Windows or
command a on Mac to select all this code
and then
rightclick
copy and then in our new
file right click and
paste let's close this for
now and in the new file we're going to
change the title to cart quantity
and let's remove all of our JavaScript
code but keep the script element because
we're going to write new JavaScript
code now we're ready to begin let's
start by creating these
buttons let's go to the body element
going to create a new
line and here as we learned in the
previous lesson we can create a button
using this HTML code less than button
greater than and the closing tag less
than SLB button greater
than inside this button we're going to
have the text show
quantity and let's
save now let's open this file in live
server by right clicking and then open
with live
server and we can see that we created
the first button now let's create the
other buttons here feel free to pause
the video if you want to try it
yourself we're going to go back to our
HTML and create another
button inside this one we're going to
have the text add to
cart let's create another
button this one is going to have the
text plus
two and we'll create another
button this one is going to be + 3 and
finally we'll create the last
button and this one is
reset
cart and now let's
save and if we go back to our
tab we've created all the
buttons now let's make this web page
interactive with
JavaScript first of all we need
somewhere to save the cart quantity so
as we learned in this lesson variables
are the perfect solution for this
variables let us save a value so let's
go into the script element and we're
going to create a variable by typing
let and this variable is going to save
the cart quantity so let's just name it
cart capital Q
quantity so the card quantity will start
out at zero so we're going to type equal
Z and
semicolon next when we click the show
quantity button we want to display the
quantity in the console to do this we
learned a special HTML attribute in the
previous lesson called the onclick
attribute so we're going to type in this
opening tag here space
onclick equals and double quotes So the
onclick attribute run some JavaScript
when we click this
button and between the double quotes we
can write JavaScript code so let's press
enter
enter And now when we click this button
we want to display the card quantity in
the console so let's type
console.log Open Bracket close bracket
semicolon and then between the brackets
we're going to display a message
now if we go back to Super
simple. and we click show
quantity we want to display this message
in the
console so in our code between the
brackets we're going to type the string
quote cart
quantity colon
0 now let's save and go back to our tab
to try it
out so we're going to open the console
first by right clicking and then click
inspect and then click the
console and now when we press the show
quantity button it should display that
message in the
console okay so we just made our project
interactive however we obviously don't
want to display zero every time we want
to display the value inside cart
quantity so we need to insert this value
in inside this
string remember from the strings lesson
when we want to insert a value into a
string we're going to use a template
string so let's switch the single quotes
to back
ticks to create a template
string and now instead of zero we're
going to insert a value using Dollar
open curly bracket and close curly
bracket and in between these brackets
we're going to insert this
variable
cart capital Q
quantity remember that JavaScript is
case sensitive so make sure you type the
variable name exactly the
same now let's
save and click show quantity
again and now it displays the value
inside card quantity in the console so
notice that variables also work with
string
interpolation again we can use a
variable wherever we use a value and it
will just substitute whatever value is
saved inside this variable into the
code now let's make the rest of the
buttons
interactive so when we click the add to
cart button we're going to add one to
this cart quantity and display it in the
console so again we're going to type
here and type space
on click equals double quotes and
between the double quotes we're going to
add
JavaScript let's also add some new lines
here to make our code easier to
read okay so in the onclick attribute
we're going to do two things the first
one is increase the card quantity by
one we can do that by reassigning the
card quantity variable
so we're going to type just the variable
name cart
quantity and we're going to make it
equal to
itself plus one and
semicolon next we're going to display
the updated quantity in the console so
let's press
enter and we're going to display this
message again so we can actually just
copy this code so we'll select it and
then right click and
copy and then
here right click and
paste now if we
save and click the add to card
button we'll see that it increased the
quantity by one and displayed the
updated quantity in the console let's
press it again to make sure it
works so it increases it by one again
and then displays it in the console
so that's basically how the cart
quantity feature works in the final
project first we need a variable to save
the quantity and then when we click a
button we're going to update the
quantity so now let's make the rest of
these buttons interactive feel free to
pause the video if you want to try it
yourself for the plus two button we're
going to add the onclick attribute again
onclick equals double quote
and inside we're going to increase the
cart quantity by two so cart quantity
and then we'll just make it equal to
itself plus two and
semicolon and again we're going to
display the updated quantity in the
console so we can create a new line and
just copy this code so select it right
click
copy and here right click and
paste let's save and click plus two a
few times and we can see that it adds
two to the card quantity and displays it
in the
console for the plus three button we'll
do the
same let's type an onclick
attribute click equals double
quotes and here we're going to increase
the card quantity by three three so cart
quantity equals
itself plus 3 and
semicolon and we're going to display
this in the console again so we'll
select this right click copy and here
rightclick and paste let's save again
and try it out to make sure it works so+
three +
three and finally let's do the reset
card
button so we'll add the onclick
attribute again on click equals double
quotes and inside the double quotes
we're going to do something a little
different this time instead of
increasing the cart quantity we'll set
it back to
zero to do this we can just reassign the
cart quantity variable so cart
quantity and just make it equal to Z and
semicolon now if we go back to
superimple
dodev and try out this reset cart
button you'll notice that it displays
two messages the first message is cart
was reset so we're going to display that
message in our code
first
console.log and the string cart was
reset
and the second message is the same
message as the other buttons so we can
just select
this and then right click
copy and then here right click and
paste and now let's save and go back to
our Tab and give this a
try so the cart quantity starts at zero
when we press add to cart increase in es
by one this increases by two this
increases by three and when we click
reset cart it'll display cart was reset
and reset the cart quantity back to
zero and that's it we just created a
simple version of the cart quantity
feature of our final project using
everything that we learned in this
course so
far now we're going to learn some
shortcuts for reassigning
variables so if we look at this line of
code here we're increasing the value of
this variable by two and then saving it
back well there's actually a shortcut
for this and that shortcut is cart
quantity plus equal 2 and
semicolon so this does the same thing as
the line above but it's just shorter the
plus means we're going to add two to
cart quantity
and equals means we're going to save
that result back to card quantity so we
can actually delete this
line and the code will work the same way
if we
save and try it
out it will still add a two and then
save it back in card
quantity let's scroll up and practice by
using this shortcut for card quantity +
one so instead of this line we can type
cart
quantity plus equal 1 and
semicolon so it turns out that in
programming plus equals 1 is so common
that we have an even shorter shortcut
for plus equals 1 and that shortcut is
cart
quantity plus plus and
semicolon so this is the same thing as
plus equal 1
and all three lines do the same
thing so we can remove these
lines and the code will work the same
because it's just a
shortcut if we
save so if we click add to
cart it will add one every
time so those are some shortcuts for
reassigning
variables we also have these shortcuts
for the other operators like minus
equals multiply equals divide equals and
minus minus I'll leave some exercises
for these other shortcuts at the end of
this
lesson next we're going to learn some
best practices for naming variables so
if we scroll
down notice that our variable cart
quantity has two words in it cart and
quantity we learned earlier that we
can't have spaces in a variable name so
if we want to have multiple words we
have to combine them together like this
now you might be wondering why we wrote
it this way with a lowercase c and a
capital
Q This is actually a naming convention
called cam case in cam case we combine
the words together and capitalize every
word except the first
word so for cart quantity we capitalize
quantity but we keep cart lowercase
because it's the first
word cam case is actually the standard
naming convention for JavaScript all of
our variable names should use cam
case now in programming there are other
naming conventions that exist another
one is called Pascal case Pascal case is
the same as camel case except we
capitalize the first word so for cart
quantity Pascal case would be Capital
cart and capital quantity in JavaScript
there is one feature where we use Pascal
case which we'll learn later in this
course for everything else we use camel
case another naming convention is Kebab
case here we keep the words lowercase
and combine them with a dash like cart
Dash
quantity Kebab case doesn't work in
JavaScript because the dash is already a
minus symbol however we use Kebab case
in HTML and CSS and also in our file
names as you can see
here and finally we have snake case
where we keep the words lowercase and
combine them with underscores snake case
is used in other languages but it's not
really used in
JavaScript so those are the common
naming conventions that we use in
programming now one more thing I want to
note is that when we name our variables
try to pick a name that is not too short
or too long for example instead of cart
quantity we could have named this
variable
C but this name is too short it's hard
to understand what c means we could also
use a name like this quantity of
products in the cart but this name is
too long it's hard to read this in the
code so try to have a balance between a
name that is understandable but not too
long like cart
quantity the last thing we're going to
learn in this lesson is there are three
ways to create variables in JavaScript
let's go back to our variables. HTML
file and we're going to learn those
three
ways so the first way is to use let
which we already learned the second way
to create a variable is to use the word
const so at the bottom we can type const
space and then a variable name like
variable 2 and make it equal to
three so const creates a variable just
like let except we can't change its
value later this value stays constant
that's why it's called const if we try
to change its value like variable 2 = 5
and then and we save this and we open
this file in the browser by right
clicking and then open with live
server and then open the console so
rightclick
inspect and then click the
console it will give us an error when we
try to change this variable so this
doesn't work let's remove this line and
Save
so why would we ever use const instead
of let well const makes our code safer
and easier to understand when we create
a variable with const we know for sure
that this variable will always contain
three for let however if we create a
variable it's hard to know what value is
inside this variable because later on we
can change this value in our
code so in order to keep our code safer
it's actually a best practice to use
const by default and only use let when
we know that we need to change the
variable so here it's actually best
practice to use const to create this
calculation variable because we're not
changing it later same thing for the
result
variable and the message
variable now for variable one we have to
use let because we're changing it later
in this code
so that's const it creates a variable
that can't be changed
later finally the Third Way of creating
a variable is to use another word VAR so
at the bottom we can type VAR space and
then a variable name like variable 3 and
make it equal to
three so VAR creates a variable just
like let and this variable can be
changed
later VAR is actually the original way
to create variables in JavaScript VAR
means
variable however VAR has some issues
that we'll learn later in this course
and because of these issues we don't use
VAR in new JavaScript code you might see
VAR in older JavaScript code so it's
still useful to know so those are three
ways to create variables in JavaScript
let constant and VAR we use const by
default and if we have to change a
variable then use
let so one more thing we're going to
learn is that we can use type of with
variables so remember that type of tells
us what type a value is for example if
we
wrote
console.
log type of
three and
save type of will tell us that three is
a
number well we can actually use type of
with a
variable so if we change this to
variable 2 and
save type of will tell us the type of
value inside the variable which is a
number and that's what we see in the
console
now let's check the type of this
variable message so message contains a
string and if we do
console.log type of
message and
save this will tell us that the value
inside the message variable is a string
so we can use type of to check the type
of value that is saved inside a variable
and that's the end of this lesson in
this lesson we learned about variables
which are a way to save values and use
them later we learned how to reassign a
variable we created the cart quantity
feature of the final project we learned
some shortcuts for reassigning a
variable we learned some naming
conventions and best practices for
variable names and we learned learned
three ways to create a variable let
const and
VAR here are some exercises to help you
practice using variables
in this lesson we're going to learn two
more features of JavaScript called
booleans and if statements and we're
going to use these features to build
this rock paper scissors
project let's start by creating a new
HTML file for this lesson we're going to
go to our code editor and click this
icon to show our files and then click
this icon to create a new file we're
going to name this file
06-
booleans
HTML and press
enter let's open variables.
HTML and we're going to copy all this
code into our new file let's select the
code using control a on Windows or
command a on Mac and then
rightclick
copy and in
here rightclick and
paste let's close this for now and
prepare this file for this lesson so
we'll scroll to the top and change this
to
booleans and then remove all the
JavaScript code but keep the script
element
now let's
save and open this file in live server
by right clicking and then open with
live
server and we can close the previous
tabs as well as the previous code for
now we'll start by learning what are
booleans so far in this course we learn
two types of values in JavaScript
numbers and strings booleans are another
type of value in JavaScript but booleans
are special because there are only two
Boolean values true and
false let's click in the script element
and type true press enter and type
false so these are the only two Boolean
values that exist true and false so
what's the purpose of Boolean values a
Boolean value represents whether
something is true or
false for example in JavaScript we can
compare two numbers let's create some
new lines and type the code 3 less than
5 so this code checks whether the number
three is less than five and of course
this is true so if we console.log this
code console.log
and
save and then go to our website and open
the console rightclick
inspect and
console it will show us that the result
of this code is the Boolean value
true let's try another
example let's delete this less than
symbol and replace it with a greater
than symbol so now this code checks
whether three is greater than five
and we know that three is not greater
than five so if we
save the computer will tell us that the
result of this comparison is the Boolean
value false so as you can see a Boolean
value represents whether something is
true or
false now let's learn the syntax rules
for booleans to create a Boolean we just
type true or false note that we don't
surround these with quotes like this if
we surround them with quotes this is now
a string not a
Boolean we can use type of to check this
so at the front we can type
console.log type of
true if we
save this will tell us that this is a
string now if we remove the
quotes and Save
this will tell us that this is now a
Boolean so when creating a Boolean don't
put quotes around true or
false let's
save now one way to create a Boolean is
to compare two numbers for example 3
greater than 5 so this greater than
symbol is called a comparison operator
and there are many other comparison
operators we can use
we saw less than earlier and we also
have greater than or equal to less than
or equal to Triple equals which checks
if two values are equal to each other
and exclamation double equals which
checks if two values are not equal to
each other now JavaScript is a little
special because it has two ways to check
if two values are equal triple equals
and double equals the difference is that
double equals tries to convert both
values into the same type for example in
our code let's create some new lines and
console.
log and let's check if the number five
is equal to the string
5. if we
save it will tell us that these two
values are equal to each other even
though one of of them is a number and
the other is a string and that's because
the double equals converts both values
into the same type so converts both of
these into the number five and then
Compares them so that's why they are
equal however this is not a good idea
because this value is a number and this
value is a string it's a piece of text
so they shouldn't really be equal to
each other that's why in JavaScript we
always use the triple equals to check if
two values are the same so that we avoid
the conversion behavior of double equals
so if we
save now it will tell us that these two
values are not equal to each other
because one value is a number and the
other value is a
string so this rule also applies to not
equal to in JavaScript we always use
exclamation double equals instead of
exclamation equals to avoid the
conversion
Behavior All right so those are
comparison operators in the order of
operations comparison operators have a
lower priority than math so if we did
something like 5 and then minus
5 this would calculate 5 - 5 first which
is zero and then compare the two numbers
so three is now greater than zero so if
we
save the first comparison will now be
true so comparison operators have a
lower priority than math
operators now that we know what Boolean
values are we're going to combine them
with a really useful feature called if
statements an if statement lets us write
multiple groups of code and then decide
which code to run Let's do an example
and create our first if statement we're
going to go to the the
bottom and create some new
lines and type if and Open Bracket Clos
bracket and open curly bracket closed
curly
bracket between these round brackets
we're going to put a Boolean value like
true and in between the curly brackets
we're going to put some code to run for
example console.log
hello so the way that an if statement
works is that if this Boolean value is
true then we're going to run the code in
the curly brackets if this Boolean value
is false then we're not going to run the
code if we
save the value between the brackets is
true so we're going to run this code and
display
hello now if we change this to false and
save it will not run this
code so an if statement lets us decide
whether or not to run some code based on
this Boolean
value now if statements have another
useful feature called
else let's go to the end of this if
statement and
type
else open curly bracket close curly
bracket and then inside these curly
brackets we're going to put some
different code like
console.log
else the way else works is if this
Boolean value is true the computer will
run this code otherwise we will run the
code inside
else let's give it a try we'll change
this Boolean value to true and
save and because it is true it will run
this code
and display
hello now if this Boolean value is false
and
save because it is false it will not run
this code and it will run the code
inside else and display
else so using IF and else we can write
two groups of code and then decide which
code to
run now let's do a practical example
we're going to write some code to check
if someone is old enough to
drive let's go to the bottom and create
some new
lines and we're going to type if
brackets and curly
brackets and inside here we're going to
compare two numbers the first number is
a person's age let's pretend we have a
person who is 30 years old so we're
going to type
30 then we're going to check if this age
is greater than or equal to the legal
driving age Let's Pretend the legal
driving age is
16 notice that between the brackets we
don't have to just put a Boolean value
we can put any code that results in a
Boolean
value so this comparison results in the
Boolean value true that means the
computer will run the code between the
curly brackets so in here let's type
console
.
log you can
drive now if this is not true let's run
some different code at the bottom we'll
type
else and curly brackets and then inside
these brackets we'll type
console.log you canot drive
now let's
save and it will tell me that this
person who is 30 years old can
drive if we go back and change this to a
person that is 15 years old and
save this comparison will result in
false so it will display you cannot
drive so that's how we use if statements
we can write multiple groups of code for
different situations and then decide
which Cod code to
run now let's learn the syntax rules for
if statements to create an if statement
we type if and then round brackets with
a Boolean value inside this is called
the condition if this condition is true
we will run the code inside the curly
brackets we can also add an else
statement this code will run if the
condition is false the else statement is
optional we don't have to have
one so these curly brackets and the code
inside these are called branches because
it's like a tree branch the code is
splitting off into two directions and we
either run this code or we run this
code one more thing to know is in a
branch if we only have one line of code
the curly brackets are actually optional
so we can delete these and the code will
still work
however if we have more than one line of
code in this Branch for example if we
add another line
console.log
congrats now this branch has two lines
of code so the curly brackets are
mandatory so we have to add them
back now we're going to learn another
feature of if statements which is we can
have more than one condition for example
we're going to go to the end of this if
branch and type else if and then
brackets and curly
brackets else if lets us add another
Branch to our if
statement between these round brackets
we can add another condition for example
if a person is almost old enough to
drive let's display a different message
so inside this condition
let's check if this person's age which
is 15 is greater than or equal to 14 so
we're checking if they are almost old
enough to drive and now inside the curly
brackets we're going to display a
different
message
console.log almost
there so the way this works is that the
if statement checks the condition one by
one first it checks if this is true if
it is it will run this Branch then it
checks if this is true if it is it will
run this branch and if none of the
conditions are true it will run the else
Branch so here this condition is false
so we're not going to run this code but
now the second condition is true so
we're going to run this code if we
save we display almost there
in the
console so using else if branches we can
add as many conditions as we want to an
if
statement the next thing we're going to
learn is that we can combine if
statements with variables from the
previous
lesson for example here we wrote the
person's age two times so we can
actually save this age in a variable and
then reuse that
value so above the if statement
let's create a variable using const and
let's name this variable H and we'll
make it equal to
15 remember the best practice for
creating a variable is to use const by
default and only use let if we're going
to change this value
later and now that we saved this number
in a variable we can use the variable
inside the if statement so we'll replace
15 with age and here as well with
age so this will take whatever value is
inside the variable and substitute it
into the
code if we
save the if statement works the same way
as before and we run this
line okay now we're ready to use
booleans and if statements to do a
project we're going to build a rock
paper scissors gate G first let's take a
look at the project we're going to go to
our browser and at the top create a new
tab and we're going to type here
superimple dodev SL
projects SL
booleans and press
enter here we can see a simple version
of a rock paper scissors game and if we
click this link it will take us to the
final version of this game so in this
game we can pick a
move and then the computer will pick a
random move and it will show us the
result and we also have a score of how
many times we won lost and tied so we're
going to build this as we go through the
course but for now let's go
back and we're going to start by
building this simple version of the game
so how this simple version works is we
click one of these buttons to pick a
move so let's pick
Rock then the computer will randomly
pick a move in this case it's paper but
for you it might be different and it
will compare the two moves and display
the results in this
popup so the rules of rock paper
scissors are rock beats scissors paper
beats Rock and scissors beats
paper let's press okay and we'll get
started on this
project first we'll create a new HTML
file just for this project let's go to
our code editor and click here and
create a new file and we're going to
name this file
06-
rock-paper-scissors HTML and press
enter next let's copy all the code from
booleans HTML into this new file so
we'll open this again and then control a
or command a to select all the code and
then right click
copy and in here right click and
paste let's close this and prepare this
file so we'll change this to rock
paper
scissors and remove all of the
JavaScript code that we had
before finally let's save and open this
file in the browser by right clicking
and then open with live
server let's take a look at the project
again so we're going to start by
creating the text first because this
text is in the final version of the
project so in our
HTML we're going to create a paragraph
element for this text so less than P
greater than and the closing tag less
than /p greater than inside our
paragraph we're going to have the text
rock paper
scissors next let's create the
buttons so we'll go to our
HTML and create a
button and inside this first button
we'll have the text
Rock Let's create another
button this one will be
paper and we'll create the last
button this one will be
scissors now let's save and check our
new
tab and now we created all the elements
that we
need next let's make these elements
interactive with Javas JavaScript so
when writing JavaScript a good strategy
is to think about what steps we need to
do and then convert those steps into
code so here when we click a button the
first step is the computer will randomly
select a move and then we're going to
compare the moves to get the result and
finally we'll display the result in a
popup by the way this is called an
algorithm an algorithm is a set of steps
to complete delete a task or to solve a
problem now that we know what steps we
need to do we're going to convert these
steps or this algorithm into
code first we're going to run some
JavaScript when we click these buttons
so let's use the onclick attribute again
we'll go to the opening tag of the
button and type
onclick equals double
quotes and then inside these double
quotes we can add our JavaScript
so now we have to figure out how to
randomly select a move for the computer
to do this we need to learn a new piece
of JavaScript
code so here we're going to type capital
m
math.random Open Bracket close bracket
math.random generates a random number
between 0o and 1 so if we console.log
this console
log and
save and click this
button and then check in our console by
right-clicking
inspect and the
console it will display a random number
between Z and 1 if we click this button
again it will generate a different
random number so every time we run MTH
random it generates a different random
number between 0 and one now to be more
precise it actually generates a number
greater than equal to zero and less than
one now let's save this random number in
a variable so we can use it later so
we'll replace the
console.log with
const and then a variable name let's
just name it random capital N number
and then
equals so we saved this random number
inside this
variable next we need a way to convert
this random number into a move like rock
paper or scissors to do this let's
imagine the space between 0 and 1 and
then divide the space into three equal
parts each part represents a move if we
generate a random number and it's
between 0 and 1/3 the move will be Rock
if it's between 1/3 and 2/3 the move
will be paper and if it's between 2/3
and one the move will be scissors this
is how we can convert the random number
into a move and this will give the
computer an equal chance of picking rock
paper or
scissors now let's convert these steps
into code and an if statement is the
perfect solution for this this already
looks like an if statement so in our
onclick attribute let's add some new
lines and type if brackets and curly
brackets for this first condition we're
going to check if the random number is
between 0 and 1/3 so let's check if
random number is greater than or equal
to
zero but in this case we also need to
check that random number is less than
1/3 because we're checking if the number
is between 0 and 1/3 but how do we do
this how do we check that two
comparisons are both true to do this
we're going to learn another type of
operator in JavaScript called logical
operators logical operators let us
combine Boolean values which is what we
need to do here let's go back into
booleans
HTML and we're going to learn logical
operators so first let's open the tab
for this
file and we're going to comment out all
the previous code so our console doesn't
get too messy
slashstar and then at the
bottom star
slash now let's create some new
lines and the first logical operator
we're going to learn is called the and
operator
let's type
console. log a Boolean value
true and another Boolean value
true so this is the and operator and it
checks if two Boolean values are both
true so it checks if the left side is
true and the right side is true that's
why it's called the and operator so here
the left side is true and the right side
is also true so the and operator will
result in true if we
save this displays true now if one of
these sides is false for example if we
change this to
false now let's check is the left side
and the right side both true in this
case no so and will now result in false
if we save it now displays false
so that's the logical and operator it
checks if the left side is true and the
right side is also true so this is
exactly what we need for our project for
example let's create a new line and type
console.log and let's say that we
generated a random number like
0.2 and we want to check if it's between
0 and 1/3 so we can do
0.2 is greater than or equal to 0 and
we're also going to check if
0.2 is less than
1/3 so we're using the logical and
operator to check if the left side is
true and the right side is also true so
in this example both sides are true 0.2
is between 0 and 1/3 so if we save
this whole thing will display true now
in the order of operations logical
operators like and have a lower priority
than math and comparisons so in this
example it will calculate the math first
and then it will calculate the
comparison on the left and then the
comparison on the right and then at the
end the and operator checks if both
sides result in
true now let's use the and operator in
our project let's go back to the file
for our
project and then inside this first
condition we're going to check if the
random number is greater than or equal
to zero and at the same time is the
random number less than 1/3 so this is
how we check if a number is between 0
and
1/3 in this case the computer will pick
Rock so between the curly brackets let's
just type con
cons. log
Rock let's get some practice and create
the other two branches for picking paper
and scissors feel free to pause this
video if you want to try it yourself
first so here we're going to type else
if to add another branch and then
brackets and curly brackets and in this
condition we're going to check if random
number is greater than or equal to
1/3
and
random number is less than
2/3 so if this random number is between
1/3 and 2/3 inside here we're going to
console do log
paper and finally let's create another
Branch using else
if random
number greater than or equal to
2/3 and random number less than
1 and
console.log
scissors if we
save and then go back to our rock paper
scissors tab
and then click the rock button a few
times it will pick some random moves for
the
computer so that's how we generate the
computer's move one thing I want to
point out is that I use the less than
comparison instead of less than or equal
to I just did this so that the
comparisons don't
overlap before we continue in the
project we're going to learn two other
logical operators we can use let's go
back to booleans
HTML and let's also open the tab for
this
file the next logical operator is called
the or operator for example let's type
some new lines and type
console.log true or
false so this is the logical or operator
it checks if at least one side is true
so it checks if the left side is true or
the right side is true that's why it's
called the or
operator so here one of these sides is
true so the or operator will result in
true if we
save this displays
true if both sides are true it will also
result in true because at least one side
is
true the last logical operator we're
going to learn is called the not
operator for example let's create a new
line and type
console. log exclamation
true so the exclamation is called the
not operator the not operator only uses
one Boolean value and it flips it into
the opposite value so if this value is
true the not operator will flip it into
false so if we
save this will result in false now if
you think about it if we say that
something is not true that's the same
thing as saying that it is false so
that's why this is called the not
operator now if we change the value to
false again the not operator will flip
this into true so if we
save this will now result in true
so those are the logical or and not
operators we don't need to use these in
our project right now but I'll leave
some exercises for these at the end of
this lesson now let's go back and
continue the project let's open the code
and open the
tab the next step is to compare the
computer's move to our move which is
Rock so first let's save the computer's
move in a variable so we can compare it
later so instead of
console.log we're going to create a
variable with
const
computer capital M move and make it
equal to the string
Rock and we'll do the same thing
here const computer move equals
paper and
here const comp futter move equals
scissors and now at the bottom let's
console.log the computer move variable
to make sure that it
worked if we save and then click our
Rock
button unfortunately it gives us an
error telling us that computer move is
not defined even though we created it
right here so what is happening here if
statements have a special feature they
create something called a scope a scope
limits where a variable exists basically
whenever we have these curly brackets
like this any variable we create inside
the curly brackets will only exist
inside the curly brackets and we can't
use these variables outside the curly
brackets so this is called a scope
Scopes are a feature of many programming
languages and they help us avoid naming
conflicts for example if I create a
variable here called random number
equals
0.5 and this didn't create a scope so if
I delete these curly
brackets this variable name will now
conflict with the variable name up here
because we can't have two variables with
the same name so you can imagine that if
we didn't have scope and we had hundreds
or even thousands of lines of code we
would quickly start to run out of
variable names so by creating a new
scope here all the variable names inside
the scope only exist between the curly
brackets and it won't affect anything
outside in the code so Scopes help us
avoid naming
conflicts okay so I'll delete this
example and we'll learn how to access
this variable
outside of this scope so to access this
variable outside of the if statement we
have to create this variable outside of
the if statement so above
here we can create this
variable
const
computer move and let's just make it
equal to the empty string for
now so this variable was not created
inside any curly brackets so it's
accessible from all of this code inside
the onclick attribute including inside
the if
statement and then inside the if
statement instead of creating a new
variable we're just going to save the
move inside this variable up here
because we can access this variable
anywhere else in the
code so instead of using const we're
just going to reassign computer move and
we're going to move it here as well and
here as
well and remember when we reassign a
variable we have to switch from const to
let and now if we
save and then click the rock
button we're able to console.log
computer move because computer move is
no longer inside this scope it's up here
so we can access it in this line of code
so that's how scope Works any variable
that we create inside the curly brackets
will only exist inside the curly
brackets so remember in the previous
lesson we learned a third way of
creating variables called VAR the issue
with VAR is that it doesn't really
follow the rules of scope for example
here if we create a variable with VAR
like VAR and
random number
equals
0.5 this variable will conflict with the
variable up here with the same name even
though it's inside a scope so that's why
we don't use VAR anymore and we just use
const and let because of VAR doesn't
really follow the rules of scope so we
can remove this for now and move on to
the next
step so we generated a random move for
the computer
now we have to compare our move which is
Rock to the computer's move to get the
result and see who wins to do that we'll
use another if statement so at the
bottom here let's type if and then
brackets and curly
brackets and then inside this condition
let's check if the
computer move is equal to rock
so remember in JavaScript we always use
triple equals instead of double equals
to avoid the conversion
behavior and now if the computer's move
is rock and our move is Rock then inside
the curly brackets the result is going
to be a
tie and let's save the string in a
variable so we can use it later again we
have the same situation as before we
don't want to create the variable inside
here because then it only exists in this
scope between the curly brackets instead
we're going to create the variable above
outside the if statement so we'll use
let to create this variable because
we're going to reassign it in the if
statement let's name this variable
result and just make it equal to the
empty string at the top and then in the
if statement we'll save the result into
this variable
so
result equals
tie now let's create the other branches
of this if statement so here we'll add
else if brackets and curly
brackets and we'll check if the
computer move is equal to paper this
time if the computer move is paper and
we picked Rock
then we lose so the result is equal to
you
lose and finally we'll add another else
if brackets and curly brackets and we'll
check if the
computer move is equal to
scissors and if the computer picked
scissors and we pick Rock the result is
is that you
win so that's how we compare our move to
the computer's random move using an if
statement the last step is to display
this result in the
popup so at the bottom let's create a
popup using alert Open Bracket close
bracket and let's go back to super
simple Dev to see the message in the
popup so we'll click this and in the
popup it shows our move the computer's
move and then the result so we can
actually just copy
this rightclick
copy and then in here right click and
paste so obviously the computer is not
going to pick this move every time and
this is not going to be the same result
every time instead we want to insert
computer move into here and we want to
insert result into here so because we
want to insert values we're going to
turn this into a template string using
back
ticks and now instead of paper we're
going to insert a value using dollar and
curly brackets and we're going to insert
the variable
computer
move and instead of this text every time
we're going to
insert the variable
result and now if we
save and we can click okay to close this
and go back to our Tab and click the
rock
button we're going to pick Rock the
computer will pick a random move and it
will show us the result in a
popup so that's how we create this
simple version of rock paper scissors in
our code we did things step by step
first we generated a random number we
converted it into a move for the
computer and then we compared our move
to the computer move and we displayed
the result in a
popup so as you can see when we're
writing JavaScript we first figure out
what steps we need to do this is called
an algorithm and then we convert these
steps or this algorithm into
code so now now we can actually remove
this console.log because we don't need
it
anymore and the last step is to make the
other buttons here interactive so feel
free to pause this video if you want to
try it yourself
first for the paper button let's add
some new lines to make it a little
easier to read and again we'll add the
onclick
attribute and then inside here we can
actually make a copy of all the
JavaScript we wrote so we can select all
of
this and then write click
copy and then in here right click and
paste if the formatting doesn't look
right we can select all of these
lines and press tab to add indents until
the formatting looks good
the one thing we have to change here is
that now we picked paper so the result
is going to be different if the computer
picks Rock and we pick paper that means
you
win if the computer picks paper now it
means that we tie and if the computer
picks scissors that means you
lose and here what will also change up
pick Rock to
paper and that's
it the last step is to make the scissors
button interactive so again
onclick equals double
quotes and then we'll make a copy of the
code so I already have it so just write
click and
paste and then again select the code
that we need to fix the formatting for
and press
Tab and here we pick scissors so if the
computer picks Rock then the result is
you lose if the computer picks paper the
result is you win and if the computer
also picks scissors the result is a
tie and we'll change you pick Rock to
scissors
now if we save and try out our game if
we click Rock we're going to pick Rock
computer picks a random move and it will
show us the result here let's press okay
and try
paper this also works correctly let's
press
okay and click
scissors and this also works
correctly and that's it we just finished
creating a simple version of this rock
rock paper scissors
game in the rest of this lesson we're
going to learn more details about
booleans and if
statements let's go back to booleans
HTML and open the tab for this
file and let's comment out the previous
code using
slashstar and star slash and create some
new
lines the next thing we're going to
learn is called truthy and and falsy
values so if statements don't just work
with Boolean values like true and false
they actually work with any type of
value including numbers and strings for
example let's type if brackets and curly
brackets and inside this condition
instead of putting a Boolean value we're
going to put a number like five and then
in inside the curly brackets let's
console.log the string
truthy if we
save the number five behaves just like
true it causes the if statement to run
this code so we call this value a truthy
value because it behaves just like true
now let's change this value to a
different number zero if we say
the number zero behaves just like false
it causes the if statement to not run
this code we call this value zero a
falsy value because it behaves just like
false so how do we know if a value is
truthy or falsy in JavaScript the list
of falsy values are false the number
zero the empty string Nan undefined and
null
any value that is not on this list is a
truthy
value so why do we use truthy and falsy
values one way we use them is like a
shortcut in our code for example let's
create a variable at the bottom using
const and let's call it cart
quantity and make it equal to
five next let's create an if statement
if brackets and curly brackets and
inside the curly brackets let's type
console.log the string cart has
products now let's say that we only want
to display this message if our cart has
products usually inside this condition
we would check if cart quantity
is greater than zero but now instead of
doing this comparison we can actually
just type cart quantity and it will
behave the same way if the card quantity
is not zero they will both behave like
true if the card quantity is zero they
will both behave like false so here the
card quantity is five which is a truthy
value if we
save this caus the if statement to run
this code as you can see instead of
doing comparisons we can use truthy and
falsey values as
shortcuts truthy and falsy values also
work with logical operators for example
if we
console.log the not operator and the
number
zero zero is a falsy value it behaves
just like false so the not operator will
flip it into true if we
save this will display
true now that we understand truthy and
falsy values let's go over the list of
falsy values because there are some that
we haven't learned yet we already
learned false zero and the empty string
the next falsy value is Nan which means
not a
number we get Nan if we do some invalid
math for example at the bottom let's
type
console.log the string
text divided by the number
five so obviously this is not valid math
if we save JavaScript will tell us that
the result of this calculation is not a
number or
Nan the next falsy value is undefined
undefined represents that something
doesn't have a value for example at the
bottom if we create a variable with
let variable one and we don't give it a
value and then we
console. log this
variable and we
save it will show us that variable one
contains the value undefined so
undefined represents that this variable
doesn't have a
value one thing to note with undefined
is that we can only use this syntax with
let we can't use it with
const if we really want to use this with
const we have to type out equals
undefined
directly the last faly value is null
we'll need some extra knowledge to
understand null so we'll learn about
null later in in this
course the last thing we're going to
learn in this lesson are some shortcuts
for if statements called the Turner
operator the guard operator and the
default
operator first let's comment out this
code so our console doesn't get too
messy SL star and then at the bottom
star
slash and let's scroll down and we'll
start by learning the Turner operator
we're going to type a Boolean value like
true and question mark another value for
example the string
truthy and then colon and another value
like the string
falsy so this is the Turner operator
this is similar to an if else statement
the first value is like the condition if
it's truthy the result of this code is a
value after the question mark if the
first value is falsy the result of this
code is the value after the colon so you
can think of the question mark as the if
branch and the colon as the else Branch
this is sort of like a shortcut for an
if statement like
this now an advantage of the Turner
operator over an if statement is that we
can save a tary operator in a variable
so at the front
we can do
const result
equals and now if we
console.log the
result and
save the first value is true so the
value after the question mark gets saved
in the
variable as always we can use truthy and
falsy values instead of just true and
false so here if we change the first
value to a falsy value like zero this
will cause the value after the colon to
get saved inside the variable if we
save that's exactly what happens so this
is the turnery operator it's sort of a
shortcut for an if else statement like
this the next shortcut is called the
guard operator earlier in this lesson we
learned the and operator which checks if
two sides are both
truthy the and operator has a special
feature let's say we have an and
operator and the left side is
false in this situation we already know
it's impossible for both sides to be
truthy so we don't even need to check
the right side so the and operator
actually stops early and doesn't even
run the code on the right this is called
a shortcircuit
evaluation for example let's go into our
code and create some new lines and we'll
type
false
and
console.
log
hello if we
save the left side is falsy so the and
operator stops early or short circuits
and it doesn't even run the code on the
right so as you can see we can use the
value on the left to block or guard the
code on the right so when we use the and
operator like this we call it the guard
operator this is sort of like a shortcut
for an if statement like
this and just like the Turner operator
we can save the guard operator in a
variable for example let's create a
variable const
message and make it equal to
false and the string
hello if the first value is falsy the
guard operator will stop early and the
result will be the first value if we
console. log this
message and
save the value f false will be saved
inside this
variable now let's change this value to
a truthy value like the number five now
it will not stop early and it will give
us the second value as the result if we
save the string hello is now saved
inside this
variable this is sort of like a shortcut
for an if statement like this so don't
worry if it's a bit confusing all of
these are just shortcuts for an if
statement they're sort of like an if
statement that we can write on a single
line the last shortcut is called the
default operator which is similar to the
guard operator but uses
or earlier in this lesson we learned the
or operator which checks if at least one
side is truthy let's imagine we have an
or operator and the left side is
true in this situation we already know
the result of the or operator because
the left side is already truthy we don't
even need to check the right side so the
or operator also stops early or short
circuits if the first value is truthy
for example let's create some new lines
and let's say that in our final Amazon
Project we can choose a currency to pay
for our order let's create a variable
with
const currency and make it equal to the
string e or
Euros now let's say that choosing a
currency is optional if we don't choose
a currency we'll use a default value of
USD or United States dollars to create a
default value we can go to the end and
type or the string
USD so here
the left side is truthy so the or
operator will stop early and it will
result in the value on the
left if we
console. log the
currency and
save it will display
Euros now let's say that we didn't
choose a currency because it's optional
so let's go here and we're going to
change this currency to
undefined now the left side is falsy so
the or operator does not short circuit
it will continue and the result will be
the value on the right if we
save now the string USD is saved inside
currency as you can see we can use the
or operator to set a default value so
when we use the or operator like this we
call it the default operator
the default operator is sort of a
shortcut for an if statement like
this so don't worry remember that
everything that we learned in this last
section are basically some shortcuts for
if statements we don't have to use them
but they can save us some
typing and that's the end of this lesson
in this lesson we learned about booleans
and if statements Boolean values
represent whether something is true or
false we learned how to use if
statements to make decisions in our code
we learn how to use comparison and
logical operators we learned about
algorithms and created a simple version
of rock paper scissors we learned about
truthy and falsey values and we learned
some shortcuts for if statements the
turnery operator the guard operator and
the default operator here are some
exercises to help you practice booleans
and if
statements in this lesson we're going to
learn the next feature of JavaScript
called functions and we're going to use
functions to improve our rock paper
scissors project first let's create a
new file for this lesson we'll go to our
code
editor and create a new
file and let's name this file
07-
functions.
HTML and press enter
next let's copy booleans HTML to
functions. HTML so we'll click this file
and then select all this code using
control a or command
a and then right click
copy and in
here rightclick and
paste and we'll hide our files and
prepare this file for this lesson
so at the top we'll change the title to
functions and we'll remove all the code
in the script
element and let's
save and we'll open this file in live
server by
right-clicking open with live
server and we're going to open the
console as well so right
click inspect
and then click the
console and finally we can close the
previous
tabs as well as the previous
code okay now we're ready to learn
functions first of all what is a
function a function lets us reuse code
let's create our first function we're
going to go to the script element
and type the word
function and
space so this creates a new function and
then we're going to give a name to our
function we can name it almost anything
we want but for now let's just name it
function one and then we're going to
type round brackets and curly
brackets then inside these curly
brackets we're going to create a new
line
and we're going to type some code so
console.log the string
hello and we'll also type
console.log 2 +
2 and
save so this creates a function now
let's learn how to use this function
we're going to type at the bottom
the function name so
function one and then Open Bracket close
bracket and
semicolon when we type the function name
with brackets this will run the code
inside the function if we
save notice that it runs the code inside
the function and displays the two lines
in the
console so why do we use functions a
function lets us reuse code so if we
wanted to run both these lines of code
again all we have to do is type the
function name again with brackets so
function one and brackets again if we
save this will run the code inside the
function two times and we can reuse this
code as many times as we want by typing
the function name with brackets so
that's what a function is it lets us
reuse code now let's learn the syntax
rules for functions the word function
creates a new
function and then we choose a name for
our function the rules for function
names are the same as variable names we
can't use special words like function we
can't start with a number and we can't
use special characters although dollar
sign and underscore are allowed and just
like variable names the best practice is
to use camo case for function
names and inside these curly brackets we
put the code that we want to run when we
use the function this is called the
function body now one very important
thing to remember is that this code only
creates a function it doesn't run the
code in the function or do anything else
in order to actually run the code we
have to use the function like below by
typing the function name with
brackets this is known as calling the
function it's also known as running the
function or executing the
function now that we learned the syntax
rules for functions let's do a practical
example we're going to use functions to
improve the code of our rock paper
scissors project first let's click here
to show our files and we're actually
going to make a copy of the project just
for this lesson so we're going to
rightclick this
file
copy and then at the bottom right click
and
paste and we're going to rename this
file so rightclick
rename remove copy at the end and then
at the beginning we'll change this to
07 and press enter
next we're going to open this file in
live server by right clicking and then
open with live
server and let's also open the console
on this page we'll right click
inspect and then click the
console all right now if we look at the
code for generating a computer move
you'll notice that this code is the same
for all three
buttons so this is a perfect situation
to use a function because a function
lets us reuse code so let's scroll down
to the script element and we're going to
make a function here so let's type
function and then a function name let's
name this function
pick
computer move and then brackets and
curly brackets so one recommendation for
function names is to use a verb or an
action in the name such as
pick so next we're going to move all the
code for picking a computer move into
our new function so let's create a new
line here and we'll scroll up to the
scissors button because it's the closest
one and we'll select all of this code
for picking a computer move and then
rightclick
cut and inside the
function right click and
paste if we need to fix the formatting
we can select these lines and press tab
to add
indents so the reason we created this
function in the script element is
because remember that the script element
runs when the page is loaded so we want
to make sure that we create the function
first and then we use it in the buttons
after now remember this code just
creates a function it doesn't actually
run the code inside to run the code
inside we're going to call this function
so let's scroll up to the scissors
button and we're going to call this
function by typing the function name
pick computer move Open Bracket close
bracket ET and
semicolon if we
save and then click the scissors
button unfortunately it now gives us an
error saying computer move is not
defined now this might seem weird
because down here we actually create the
computer move so what's going on the
reason this happens is because functions
create a scope in the previous lesson we
learned about Scopes which limit weight
where a variable exists we learned about
if statements and that if statements
create a scope between the curly
brackets this means that any variable
created between the curly brackets only
exist between the curly
brackets functions also create a scope
any variable that is created between
these curly brackets only exists inside
the curly brackets and we can't use it
outside the curly Brack ETS like we do
here so that's why we're getting this
error so how do we solve this problem
remember that with if statements we
solve this by creating the variable
outside of the if statement like this we
can use a similar solution with
functions to make this variable exist
outside the function we just have to
create it outside the function so let's
select this code we're going to
rightclick
and
cut and remove these lines and then
outside the function we're going to
rightclick and
paste so now this variable is no longer
inside the function's scope and it can
be used anywhere else in the code so
variables like this that can be accessed
anywhere are called Global
variables if we save
and now click the scissors
button everything is working again
because this code above can now access
this
variable now let's press
okay and let's use this function to
reuse this code so we'll scroll up to
the paper
button and now instead of all this code
again we're just going to remove it and
call the function pick
computer move Open Bracket close bracket
semicolon and also with the rock button
we'll select all this
code and remove it and just call the
function
pick
computer move brackets and
semicolon now if we
save and click the rock
button it works just like before
we'll press okay and click the paper
button it also works just like before so
as you can see functions let us reuse
code and they make our code a lot
cleaner by removing all the duplication
that we had another benefit of removing
duplication is that before if we ever
wanted to update the code for picking a
computer move we had to update it in
three places in each of the buttons but
now if we scroll
down we only have to update it in one
place inside this function so functions
also make our code easier to update in
the
future next we're going to learn a
feature of functions called a return
statement a return statement lets us get
a value out of a function so at the end
of this function let's type some new
lines and we're going to type type
return and then a value like the number
five and
semicolon now whenever we call this
function it will result in a value the
number five so up
here when we call this function this
will result in the number five so we can
actually console.log this console.log
and then
save and click the scissors
button and it will show us that calling
the function now results in the number
five and we display it in the
console so that's how a return statement
works it lets us get a value out of this
function let's press okay and do another
example we'll scroll
down and this time let's change CH this
value to the string
Rock now whenever we call this function
it will result in the string Rock if we
save and then click
scissors and scroll up
here calling this function now results
in the string Rock and then we display
it in the
console so now let's press okay and
we'll learn the syntax rules for a
return
statement so we just have to type the
word return and then a value and it will
get this value out of the function now
instead of just a value we can also
return a calculation or a variable or
anything that results in a
value so this is known as returning a
value from a function and this value is
known as the return value we also Al
don't have to return anything from a
function if a function doesn't have a
return statement or we return without a
value like this this will return the
value
undefined so if we
save and then click scissors
again the function will return
undefined and lastly when we use a
return statement it ends the function
immediately so after the the return
statement if we type
console.log the string
after and press okay here and save this
file and then click the scissors
button notice that it doesn't run this
code and that's because once we return
the code returns back to where we called
the function that's why it's called a
return statement so it's not going to
run anything after the return so we can
remove this
code and press
okay so now that we understand return
statements we're going to learn a better
way of getting the computer move out of
this function so first let's actually
move this variable back into the
function so we right click and
cut and then in
here right right click and
paste and delete these
lines so now we're back to the original
problem how do we access computer move
outside of the function so another
solution is to return this variable
because remember a return statement lets
us get a value out of the function so
down
here we're going to return the
computer
move so this will take whatever value is
saved inside computer move which is one
of these values and return it out of the
function if we
save and then click these scissors
button we were able to get the move
scissors outside of this function so
what happened here is that we return
this move and then up
here we took the move and displayed it
in the console to get
scissors so that's another way of
getting the computer move out of a
function using the return
statement however now we're back to this
problem with computer move not being
defined because we moved it back into
the function's scope so let's scroll up
and remember that this return value is
just a value we can use it like any
other value for example we can
console.log it or we can also save this
in a variable so let's do that right now
we're going to remove
this and create a new variable with
const and let's just name this variable
computer move to match what we use down
here and we use equals to save the
return value inside inside this
variable so note that even though we use
computer move here as well as here
there're different variables this one is
inside the function's scope so it
prevents it from conflicting with
variables outside the function's scope
that's one of the main benefits of
Scopes so now that we saved the return
value into this variable and we're using
this variable down here the code should
now work work if we
save and click
scissors everything is back to
normal and let's press okay so don't
worry functions can be a little
confusing at first because the code is
no longer simply going from top to
bottom it sort of jumps around a little
bit so let's go through this step by
step when we click this button we're
going to run this function so the code
is going going to jump down here and
then it's going to run all of this code
from top to
bottom at the end we're going to return
whatever is inside computer move back to
where we called this function so we're
going to return all the way back here
and then we're going to save that return
value into a new variable computer move
and then use computer move down
here so following the code line by line
like this is called tracing the code
it's a useful technique to understand
exactly what the code is
doing now let's compare the two
solutions that we used a global variable
and returning a
variable so returning a variable like
this is actually preferred over using a
global variable and that's because a
scope can help us prevent naming
conflicts so all the variables inside
here will not conflict with anything
outside the scope so generally it's a
best practice to keep things inside a
scope if we
can now let's move on and use this
function in the other buttons feel free
to pause the video if you want to try it
yourself
first so we'll scroll up to the paper
button and then here we're going to save
The Returned computer move into a
variable so
const
computer move so that it matches the
code down here make it equal to whatever
is returned and then same thing for the
rock button we're going to save the
return value in a variable const
computer move
equals if we
save and click the rock button
it
works let's press okay and click the
paper button and this also works and
let's press okay so that's how we use a
return statement to take advantage of
the benefits of
scope next if we look at the rest of
this code where we compare our move and
display the result you'll notice that
this code is very similar for each of
the buttons you the only thing that's
different is the result and the message
that we display so we can actually use
functions here as well to reuse code
that has small differences to do this
we're going to need another feature of
functions called
parameters so let's go back into
functions.
HTML and let's open the tab for this
file and let's also comment out the
previous code by typing
slash star and at the bottom star
slash and create some new
lines and now we're ready to learn
parameters so parameters are sort of the
opposite of a return statement a return
statement gets a value out of a function
a parameter puts a value into a function
so let's do an example let's say that
we're working on the final Amazon
Project
and we need to calculate the tax for our
order let's create a function to
calculate the tax so
function let's name it
calculate tax brackets and curly
brackets and then inside the curly
brackets let's say that the cost of our
products is
1,000 or $10 and the tax is
10% to calc calculate the tax we can do
1,000 *
0.1 which is
10% let's also display this number in
the console so at the front we'll type
console.log and
brackets now let's save and remember
this code only creates a function it
doesn't run the code inside to run this
code we're going to call this function
so down here we're going to type the
function name calculate tax and then
brackets if we
save it runs this code and then it
displays the tax which is 100 cents or
$1 however right now this function only
calculates the tax for
1,000 what if we want to calculate the
tax for a different amount how would we
modify this function to work with any
number to do this we're going to learn a
feature of functions called parameters a
parameter lets us put a value into a
function so let's finally create our
first parameter so inside these round
brackets we're going to choose a name
for our parameter so let's just name
this
parameter
1 a parameter one works the same way as
a variable we can save a value inside
this parameter and then use it just like
a
variable so first let's save a value
inside the parameter to do that we're
going to go to where we call the
function and then inside these brackets
we're going to put a value for example
2,000 this will save this value into
this parameter
and now we can use it just like a
variable so instead of
1,000 we're going to type
parameter 1 and it will take whatever
value is inside parameter 1 in this case
2,000 and substitute it into the code if
we
save it now calculates 2,000 *
0.1 to give us 200 cents as the tax
now every time we call the function we
can save a different value into the
parameter for example let's create a new
line and call the function
calculate
tax and this time we're going to save
the value
5,000 into parameter 1 if we
save this line of code will calculate
the tax for 5,000
and result in 500 cents so as you can
see a parameter lets us put values into
a function and this allows our function
to work with any
value now let's learn the syntax rules
for parameters to create a parameter we
just type the parameter name between the
brackets parameter names follow the same
rules as variable names we can't use
special words we can't start with a
number and we can't use special
characters other than dollar sign and
underscore and the best practice is to
use cam
case let's actually change this
parameter name to cost so the code makes
more
sense and
save next when a function has a
parameter we usually say this function
takes a parameter if this parameter
should be a number we say this function
takes a
number when we put a value into the
function like this we call this passing
a value into the function another name
for this value is called the
argument and believe it or not we've
actually used functions and parameters
this whole time the first code that we
learned in this course was alert alert
is actually a function you can tell it's
a function because of the round brackets
and between the brackets we put a string
so this is an example of a
parameter and lastly a parameter only
exists inside the function's scope so we
can only use this parameter between the
curly brackets we can't use it outside
the
function next a function can actually
have more than one parameter for example
right now our calculate TX function can
only calculate a 10% tax but what if
we're in a different country and we want
to calculate a different tax percent to
solve this we can add a second parameter
by typing after the first parameter a
comma and then another parameter name
let's name this tax
percent and now to save a value into the
second parameter we'll go go to where we
call this function and also type a comma
and a second value like
0.2 or a 20% tax so the first value gets
saved in the first parameter and the
second value gets saved in the second
parameter and now we can use our second
parameter just like a variable so
instead of 0.1 every time we're going to
calculate it with tax
percent and it will substitute whatever
value is inside tax percent into the
code if we
save this first line will multiply 2,000
by
0.2 and give us 400 cents as the
result so we can have as many parameters
as we want in a function we just have to
separate them with a
comma Now notice that the second time we
call this function we didn't give a
value for the second parameter if we
don't save a value into the parameter
the parameter will get the value
undefined so here if we
console. log the second parameter tax
percent and
save it will show us that the second
time tax percent is
undefined and then multiplying the cost
time undefined is not valid math so we
get the result Nan or not a number so
now let's remove the
console.log and we'll learn how to fix
this so to fix this we can either pass a
second value into the function like this
line or we can also set a default value
for the parameter to set a default value
we can just type after the parameter
and then add equal sign and a default
value like
0.1 if we
save the second function call Will
multiply 5,000 by the default value
0.1 and give us
500 so that's how we add a default value
for a
parameter all right now that we learned
parameters we're going to go back to the
rock paper scissors project and reuse
even more code so let's go back to the
file for the project and also the tab
for this
project and now if we look at the code
inside each of the buttons you'll notice
that the code is basically the same for
all three buttons the only small
difference is the move that we picked so
this is a perfect situation to use a
parameter so so inside the script
element let's create a new function to
reuse all of this code we'll type
function and let's name this function
play game brackets and curly
brackets next let's move all of this
code inside the function so we can reuse
it we'll select this
code and then
rightclick
cut and inside the
function right click and
paste and if we need to reformat we can
select these lines and press
tab so the value that is different for
each button is the move that we picked
so we're going to turn this move into a
parameter so at the top between the
brackets we're going to create a new
parameter let's name it Player
move and now let's save a value into
this parameter so inside our scissors
button we're going to call this function
and run all this code so let's type play
game and call this function and for the
scissors button let's save the string
scissors into Player move to do that
we'll type between the brackets here and
type the string
scissors so as we learned this will save
scissors into Player move and now we can
use Player move just like a variable in
the
function now let's modify the code based
on the parameter so here this code
calculates the result however this only
works if the player move is scissors so
we're going to put this in an if
statement so we'll type
if
Player move equals
scissors and curly brackets inside this
if statement we're going to put this if
statement so let's select this and then
right click
cut and then inside
here right click click and
paste and select these lines and press
tab so notice that we can put an if
statement inside another if statement
and we did this because this code only
makes sense if the player move is
scissors and finally let's modify the
code that displays the message so here
instead of displaying scissors every
time we're going to display whatever is
saved inside Player
move so we'll replace it with Dollar
open curly bracket close curly bracket
and in between we'll insert Player
move and that's it we modify this
function to use a parameter instead of
always using
scissors now let's save and click the
scissors
button and you'll notice that it works
we displayed the move scissors and we
calculated the result
correctly let's press okay and we're
going to use this function to reuse the
code for the other buttons so we'll
scroll up and for the paper button we're
going to use a different if statement to
calculate the result so let's actually
copy this into the function we're going
to
rightclick click copy
and then inside the
function we're going to create another
Branch if the player move is paper so
here let's type else if brackets and
curly
brackets inside this condition we're
going to check if the
player move is equal to paper this time
and then inside these curly brackets
we're going going to paste the if
statement we copied earlier so right
click and
paste and we can select these lines and
press tab to
reformat so now we have the code that
determines the result for paper down
here we don't need to modify this code
because we're always displaying whatever
is inside Player
move finally we can scroll up to the
paper button
and remove all this duplicated code and
just use our function play
game and we're going to pass paper
inside so now paper will get saved
inside Player move and it's going to run
this if statement
instead if we
save and click the paper
button in this example I pick paper
computer pick Rock and it calculated the
result
correctly let's press okay and use this
function for the rock button feel free
to pause the video if you want to try it
yourself
first so let's scroll up to the Rock
button and first we need to copy this if
statement into the function so let's
rightclick
copy and then inside the function
let's create a branch for rock else if
Player move is equal to
rock and then curly brackets and inside
here we're going to rightclick and paste
the if statement we copied
earlier and now let's select these lines
and press tab a few times to
reformat and again this doesn't need
need to
change the last step is to scroll up to
our Rock button and instead of
duplicating all of this code we're going
to remove it and just call our function
instead play game brackets and then
inside we'll have the string
Rock now let's
save and click the rock
button so I picked Rock the computer
picked paper and we calculated the
result
correctly let's press okay so by using a
function with a parameter we were able
to reuse all of the code in our buttons
and you can see that it made our code a
lot cleaner so lastly notice that inside
a function we can call other functions
let's go through the code step by step
so that we understand how how it works
so here when we call the play game
function we go inside here and then we
call the pick computer move function so
now we're going to go inside this
function and run all the code and then
when this function returns we're going
to return back to where we called it and
then keep going and run the rest of the
code and then when the play game
function finishes it's going to return
back to
here so inside a function we can call
other
functions now one last thing we're going
to do for this code is we'll scroll
down and we're just going to add some
new lines to this if statement to
separate the branches and make the code
a little easier to
read and
save and let's scroll
up and that's the end of this
lesson in this lesson we learned about
functions which let us reuse code we
learned how to get a value out of a
function using return we learn how to
put values into a function using
parameters and we improve the code for
our rock paper scissors project by
reusing the code and removing
duplication
thanks for watching this course so far
if you want to support this channel you
can check out the premium version of my
courses just like this one where you can
get a certificate of completion and a
Better Learning platform if you're
interested in extra videos from me more
in-depth videos and behind the scenes
content you can check out these links
here you can also support the channel by
liking the video subscribing and sharing
this video with others thanks again and
let's go continue with the
course here are some exercises you can
do on your own to practice using
functions
in this lesson we're going to learn
another type of value in JavaScript
called objects and we're going to use
objects to create a score in our rock
paper scissors project first let's
create a new file for this lesson we'll
go to our code editor and click this
icon and then click this icon to create
a new file and we'll name this file
08-
objects.
HTML and press
enter next we'll copy all the code in
functions. HTML to objects. HTML so
we'll type here and press contrl a or
command a to select the code and then
right click
copy and in
here right click
and
paste now let's hide the files for now
and we'll prepare this file for this
lesson so we can change this to objects
and remove all the code in the script
element finally let's save and open this
in live server by right clicking open
with live
server and let's also open the console
on on this page so we'll right click
click
inspect and click the
console let's close our previous
tabs and also the previous
code and now we're ready to learn
objects so what is an object an object
groups multiple values together let's do
an example and create our first object
we'll go to the script element and we'll
create a variable using const and we'll
name this variable product and make it
equal to open curly bracket close curly
bracket and semic it so this is an
object inside this object we can add
some values so we'll type enter and then
Name colon and then a value like the
string
socks and at the end we'll type a
comma and then price colon and another
value like the number
1,90 so inside our object we just added
two values so at the bottom here let's
try console. logging this object
console.log
product and
save and it will display both values
into the
console so as you can see an object lets
us group multiple values together so for
each of these values we have some code
on the left this code is called the
property and using the property we can
access specific values in the object for
example let's type and enter and
console.log we're going to type the
object product and then a DOT and then a
property like
name so dot name Will access the value
that is associated with the name
property which is the string socks so if
we
save it will display the string socks in
the console
let's do another example and we'll
access this second value using the
property price so we'll type enter
console. log the object product and then
a DOT and then a property
price so this will access the value
associated with price which is
1,090 if we save
that's what gets displayed in the
console now we can also use the property
to change a value inside an object to do
that we're going to type the object's
name product and then Dot and a property
like name and just make it equal to
something else like the string cotton
socks so this code will change change
the value associated with the name
property to cotton socks so at the
bottom if we type
console.log the product
again and
save you'll notice the value associated
with the name property was changed to
cotton
socks so that's how an object works we
group multiple values together and then
we can access or change these values
using the properties on the left now
let's learn the syntax rules for objects
to create an object we start with an
open curly bracket and end with a closed
curly bracket inside the object we can
put multiple
values for each value the code on the
left is called the property this is how
we access the value inside the object we
separate the property and value with a
colon and this is called a property
value pair we can have many property
value pairs in an object and we separate
them with a
comma to access a value inside the
object we type the object's name and
then Dot and then the property we want
to access like name this will give us
the value associated with the name
property this syntax is called do
notation if we access a property that
doesn't exist the value will be
undefined to change a value in an object
we can use the dot notation again so
product. name and just make it equal to
something else now using the syntax we
can also add a value to an object we can
type a property that doesn't exist for
example here we can type
product do new
property and make this equal to
something like the Boolean value
true if we
console.log the product
again and
save it will add this value to the
object along with the new
property we can also remove a value from
an object by typing
delete and then the object
product Dot and then the property we
want to delete like new
property if we
console.log the product
again and
save this code will delete new property
from the
object and lastly notice that then an
object is just another type of value we
can save an object inside a variable and
we can also console.log objects if we
check the type of this value so type of
product and
save and scroll up in the
console it will tell us that product is
an object so let's remove
this and Save
and now we'll learn why we use objects
so objects make our code more
organized instead of creating a bunch of
variables for the products values like
the name and the price and other details
we can just group all these related
values together into one object objects
also allow us to use multiple values
together instead of console. logging
each of these values individually we can
just console log the whole object and
display all the values at
once so objects let us group multiple
values together and let us use multiple
values
together next let's do a practical
example with objects we're going to add
a score to our rock paper scissors game
so I've actually prepared a project we
can use for this lesson to see this
project we're going to go to our website
and then create a new
tab and then up here we're going to type
super simple dodev SL projects
slobs and press
enter so this is our simplified rock
paper scissors game again except in this
project when we play the
game it's also going to keep track of a
score so how many times we win lose and
tie and also if we click
okay we have a reset score button so if
we play the game a few
times and add to our
score and then click the reset score
button this will reset the score back to
zero so if we play the game again the
score starts from zero
again so we're going to learn how to use
objects to create create this feature
let's press
okay and first let's create a copy of
our project just for this lesson we'll
go to our code editor and click this
icon to show our files and we'll make a
copy of the rock paper scissors project
from the previous lesson so we'll
rightclick and
copy and down here right click and
paste and we we right click and rename
this
file we'll remove the copy at the end
and at the front we'll change this to 08
and press
enter now let's hide these files and we
can close the 07 file for now and let's
open this in live server by right
clicking and open with live
server let's also open the console on
this page so
rightclick
inspect and the
console all right now let's go into our
code and add a score to our game so
remember when writing JavaScript a good
strategy is to think about what steps we
need to do this is called an algorithm
and then convert those steps into code
so we already had an algorithm for the
rock paper scissors game
let's update this algorithm to include
the score so first the computer randomly
selects a move this step will stay the
same number two we're going to compare
the moves to get the result this step
will also be the same but now we're
going to add an extra step after getting
the result we're going to update a score
and finally we'll display the result and
the score in a popup now let's convert
these updated steps or this algorithm
into code the first thing we need to
change is we added a third step we're
going to save and update a score so
first we need somewhere to save our
score so one place we can save it is
inside a variable let's go to our script
element and at the top we're going to
create a variable for our score using
const
score and make it equal to an
object and inside this object we're
going to have the property
wins so this will keep track of how many
wins that we have we'll type colon and
the number zero because the score starts
at zero and then a comma and then
another property
losses this will be how many losses we
have and then colon and zero and then
another comma and ties colon and zero so
we use an object here because these
values are related to each other you
could use separate variables but we're
using an object for
convenience another thing you'll notice
is that we're creating this variable
outside of a function and outside of a
scope and that's because every time we
make a move we need to update the score
from last time so in order to save the
score from last time we need to keep it
outside the function if the score was
inside the function the function would
create a new score every time which is
not what we want so in this situation in
order to save a score from last time
we're going to keep this variable
outside now every time we play the game
after we calc calate the result we're
going to update the score so let's
scroll down to where we calculate the
result which is here and then below it
we're going to type some new
lines and type the code for updating the
score so we can do that with an if
statement so we'll type if brackets and
curly brackets and inside the condition
we're going to check if the result is a
win if it is a win
we're going to update the winds property
and increase it by one so down
here if the
result is equal to the string you
win and make sure that this string
matches the string up here inside the
curly brackets we're going to update
score. wins and we'll make it equal to
itself plus
one so this is how we increase the winds
property in the score object by one now
remember from the variables lesson that
we have a shortcut for increasing
something by one and that shortcut
is plus =
1 next let's add another Branch to this
if statement for the other two results
so else if brackets and curly brackets
and in the second condition we're going
to check if result is equal to the
string you
lose and make sure this string matches
the string up here so if the result is
you lose we're going to update score do
losses property and increase it by 1 so
plus equal
1 and finally we'll check if the result
is a tie else if brackets and curly
brackets
result equals to the string
tie and here we'll update
score. ties plus equal
1 so we converted this step in the
algorithm to code the score starts at
zero and every time we play the game
after we calculate the result we're
going to update the score using this
code now let's convert the last step
into code we're going to display the
result and the score in the popup at the
end so let's actually go back to the
super simple dodev
project and we'll see what the popup
looks like we'll click one of these
buttons and in this popup on the second
line we display the score so in our
code this is the code that displays that
popup so how do we add a second line to
the popup remember that template strings
have another special feature called
multi-line strings so we can type at the
end of this template string and press
enter to add another line to this Str
so here we can type winds colon and
we're going to insert a value using
Dollar open curly bracket Clos curly
bracket and here we're going to insert
the number of wins that we have which is
score. wins so we'll type score
dowins next we're going to show the
number of losses that we have so after
this
let's type a comma and losses colon and
insert another
value here we'll insert
score.
losses and finally we'll type a comma
and we'll display ties colon and
inserted value score dot
ties and this will display our score in
the popup so let's save this and give it
a try we'll click okay and then go back
to our Tab and play the
game so now on the second line we will
display the score one small issue here
is that we have a lot of spaces on the
second line so these spaces correspond
to the spaces here when we use
multi-line strings these Extra Spaces
will show up in the popup so to remove
these SP cases we can just remove them
in the code like this now if we
save press
okay and play the game it will show our
score on the second line without those
Extra Spaces at the front let's press
okay we're going to add one more feature
to this project if we go back to Super
simple. Dev we have a reset score button
which will reset the score back to zero
when we click it let's add this button
in our project so we'll scroll
up and inside the
HTML We'll add a button with the code
less than button greater than and inside
the button we'll have the text reset
score and now when we click this button
we'll run some code using the onclick
attribute equals double quotes and then
in here we're going to write some code
to reset this score back to
zero so one way we can do it is because
this score is an object we can use dot
notation to change everything back to
zero so we can type
score. wins and make it equal to zero
we'll also type
score. losses and make it equal to Z and
finally
score. ties and make it equal to
zero now let's
save and go back to our
Tab and play the game a few times to get
a
score let's press okay and press reset
score and then play the game again and
you'll notice that the score started
from zero again so that's how we create
the reset score button we just set all
of these properties back to
zero and that's it that's how we add a
score feature to our rock paper scissors
project using an object to save the
score let's press
okay and we're going to learn more
details about objects let's go back to
objects.
HTML and what open the tab for this
file and let's also comment out the
previous code using
slashstar and at the
bottom star
slash and
save now let's scroll to the bottom and
we'll do some
setup so first let's create a variable
with const we'll name it Product 2 and
make it equal to another object
inside this object we have the property
Name colon and the string
shirt and we're going to console.log
this object so
console.log Product 2 and
save so the next detail we're going to
learn about objects is another way to
access the values
inside we previously learned the
notation to do this for example
console.log product
to.
name this will access the value
associated with the name
property in JavaScript we have another
way of accessing values inside objects
which is using square brackets so we'll
create a new line and type console
do
log product 2 and this time we'll type
square
brackets and then inside the square
brackets we'll have a string with
name so this is called bracket notation
and this does the same thing as dot
notation up here it gets the value
associated with the name property if we
save these two lines of code both access
the string shirt which we see here so
when do we use the bracket notation
instead of the dot notation bracket
notation lets us use properties that
normally don't work with do notation for
example at the bottom we can type
console.log Product 2 and then use a DOT
and try to access a property called
delivery-time if we
save this property will give us an error
and that's because JavaScript thinks
that this Dash is a minus sign and it's
trying to do math so in order to use a
property like this we have to use
bracket notation so we're going to
replace the dot with square
brackets and and turn this into a
string now if we
save it no longer gives us an error and
because delivery time does not exist in
the object we get the value
undefined so using bracket notation we
can also add values to the object when
we create it so here we can add a
comma and we'll add another property
using bracket notation and a string
delivery-time and a colon and then a
value like the string one
day if we
save this lets us add a delivery-time
property to this object so as you can
see bracket notation lets us use
properties that normally don't work with
DOT
notation another feature of bracket
notation is that between the brackets we
don't just have to use a string we can
use a variable a calculation or anything
that results in a
value so you might be wondering which
one should we use do notation or bracket
notation we usually use do notation by
default because it's shorter and easier
to read but if we need to use properties
that don't work with do notation then we
use bracket not
notation now a shortcut here is when we
create the object if we only have a
string between the brackets the brackets
are actually optional so we can just
type this if we save the code will still
work okay the next detail we're going to
learn is that inside an object we can
save any type of value so this includes
numbers strings booleans
as well as other objects because
remember objects themselves are also
values for example we can type a comma
and add a property called
rating colon and then an object open
curly bracket close curly bracket and
inside this inner object we can add more
properties like stars colon 4.5
this is how many stars a product has and
then a comma and a property called count
colon
87 this is how many ratings a product
has so this is called a nested object or
an object inside an object we can use
nested objects to make our values more
organized so inside the product the
number of stars that has and the number
of ratings that it has are both related
to a rating so it makes sense to group
them together further inside the
product now to access values inside the
inner object we just use the dot
notation or bracket notation multiple
times for example at the bottom we can
type
console.log product
2 dot
rating this will get the value
associated with rating and this is an
object so we can use the dot notation
again
count so this will get the count inside
the rating object which is this value
right here so if we save it will display
87 and finally another type Ty of value
we can put in an object is a function so
in this object let's type comma and
another property
fun colon and we're going to create a
function here so let's type
function and we'll name the function
Function One brackets and curly brackets
and then inside the function we're going
to have some JavaScript code like usual
so
console. log the string
function inside
object this saves a function inside the
object and this works because a function
is actually just another type of value
in JavaScript but we'll learn more about
this feature of functions later in this
course for now just know that functions
are also values and we can save them in
an object to access this function we can
use the dot or bracket notation as usual
so at the
bottom we can type the object Product 2
and then a DOT and then the property
fun so this will access the value
associated with the fun property which
is a function and because this is a fun
function we can call it as usual using
brackets if we
save this will run the function here and
it will display function inside object
into the
console so when we save functions inside
an object this is called a method and
we've actually been using methods this
whole time
console.log is actually a method
console is an object provided by
JavaScript and log is a function that is
saved inside the console
object if we go to the bottom and type
console.log type of
console and
save this will confirm that console is
just an object and if we change this to
console.log and
save this will show us that console.log
is a function so log is a function that
is saved inside the console object so we
call this a method another example of a
method is math.random which we used in
the rock paper scissors project math is
also an object provided by JavaScript
and random is a function saved inside
the math object so we call math.random a
method as well so we've actually been
using objects and methods all throughout
this course and now we understand all
the code that we've been using so far
next we're going to learn about builtin
objects so the console object and the
math object are known as builtin objects
because they are built in to the
language they provided by the
language we're going to learn two more
built-in objects called Json and local
storage and we will use these objects to
improve our rock paper scissors project
let's start with the Json built-in
object this object helps us work with
something called
Json Json stands for JavaScript object
notation the easiest way to understand
Jason is it's BAS basically a syntax
it's a similar syntax to a JavaScript
object but it has less features for
example the code on the left uses
JavaScript object syntax and the code on
the right uses Json syntax so one
difference is that all properties and
strings must use double quotes in Json
Jason does not support single quotes
another difference is that Json does not
support function functions so as you can
see Json is basically a syntax that's
similar to a JavaScript object syntax
but with less
features so why would we use Json syntax
instead of a JavaScript object
syntax a JavaScript object only makes
sense in
JavaScript on the other hand Json syntax
can be understood by almost every
programming language so Json syntax is
more un
Universal for this reason we use Json
when we send data between two computers
that might use different programming
languages we'll learn how to do this
later in the course we also use Json
when we store data we'll learn how to
store data in this
lesson now that we understand what Json
is let's learn about the built in Json
object the Json object helps us convert
a JavaScript object to Json for example
let's convert our object product two to
Json so we'll create some new
lines and we'll type the Json object do
stringify and Open Bracket close bracket
so stringify is a method of the Json
object so it's a function that is saved
inside this object and we can call this
function using
brackets between the brackets we can
give it a JavaScript object we want to
convert like Product
2 this will convert the object into Json
so now let's
console. log the
result and
save and in the console it will display
the product using Json syntax if we we
scroll up you'll notice that the
function that we saved in the object is
not inside the Json and that's because
Json does not support
functions so one thing to note about
stringify is that it actually results in
a string so at the front if we type type
of and
save it will tell us that the result
that it gives is actually a
string so if we remove
this and
save now this Json string is ready to be
sent to another computer or to be saved
in
storage next let's learn how to convert
the other way from a Json back to a
JavaScript object to do that we'll use
another method in the built-in Json
object called json.parse
at the end we'll type Jon
dop
pars and
brackets and between the brackets we can
put a Json string that we want to
convert so we actually have a Json
string up here so let's just make a copy
of this we'll select it
rightclick
copy and let's create an extra variable
to make it more clear const Json string
and make get equal to right click and
paste and now let's convert this Json
string back into an object by putting it
into
pars and finally we console.log this
result so
console.log and
save and json. pars will turn the Json
string back into a JavaScript object so
that's the built-in Json object it helps
us convert back and forth between a
JavaScript object and
Json now we're going to learn the next
built-in object called local storage
local storage is used to save values
more permanently so far we've been
saving our values in
variables however variables are
temporary they only exist on the current
page if we refresh the page or close the
page all the variables are deleted for
example if we go back to our rock paper
scissors
project and open the tab for this
project and we play a few
games and play it again so we have two
games if we refresh the page
notice the score starts from zero again
and that's because when we refresh the
page all of these variables are deleted
and the score gets reset back to zero
however if we press okay and go to
superimple
dodev and we refresh the page and we
play the
game notice that the score doesn't start
from zero it starts from the previous
score even though we refreshed the page
and that's because this project saves
the score in local storage and local
storage doesn't get deleted when we
refresh the
page now let's learn how to use local
storage in our project let's press okay
and we'll go back to our code and we'll
scroll down to where we update the
score so here after we update the score
we're going to save it in local storage
but first first let's learn how local
storage works so at the bottom here
we're going to type the local capital S
Storage
object to save a value inside local
storage it has a method called set item
so we can type dot set capital I item
and brackets because this is a method or
a function saved inside the object
object and we're going to give two
strings to this method the first string
is a name this is how we're going to
access the value that we save later so
let's use the string
message as the name and we'll type a
comma and then we'll type the value that
we want to save into local storage so
local storage only supports strings so
let's save the string
hello inside local
storage if we
save and then go back to our Tab and
play the
game it will run all this code and save
this string into local storage now let's
learn how to get this string out of
local storage we'll press okay and we'll
scroll to the
top and when we first load the page
we're going to get that value out of
local local storage by typing local
capital S
storage. getet item this
time and
brackets so the get item method gets a
value out of local storage and we're
going to give it one string so this
string is the name that we used earlier
which was message so we'll type the
string
message now let's console log this
result so
console.log and a bracket at the
end and
save it will get the value that we saved
earlier out of local storage so we saved
the string hello and that's exactly what
gets displayed in the
console so using local storage we were
able to get the value that we saved
earlier even though we refresh the
page now let's save our score into local
storage so it doesn't get reset when we
refresh the page so let's scroll to the
bottom and instead of using the name
message we're going to use the name
score to save our score and instead of
the string
hello we're going to save the score
object now one problem here is that
local storage only supports strings so
we need to convert our object into a
string and we actually learned how to do
this earlier using json.stringify
so at the front we can type
json.
stringify and then brackets around the
score and this will convert the
JavaScript object score into a Json
string and then it's ready to be saved
in local store
so if we save this and then play the
game it will run this code and save our
score into local
storage now let's press
okay and then's scroll up to the
top and now instead of getting the
message we're going to get the score out
of local storage if we
save now when we load the page we're
able to get the score that we saved from
last time as a Json
string the last step is instead of
resetting the score to zero every time
we're just going to use the score from
local storage before we do that remember
that this is just a string so we need to
convert this back to an
object we also learned how to do this
earlier using json. pars so at the
front we can type
json. pars and then Open Bracket and at
the end a close bracket and it will
convert this back to an object if we
save it will convert the score from a
Json string back to an object so now we
can use it up here so instead of doing
this we'll remove it and replace it with
this code so right click cut
and then here right click and
paste and we'll remove
console.log and
save so now when we load the page it
will load the score from local storage
if we play the
game notice that the score doesn't start
from zero it starts from the score that
we had last time let's review what we
did step by step first when we update
our score in this code after we update
the score we're going to save it in
local storage using local storage. set
item now local storage only supports
strings so we have to convert our score
object into a Json string using json.
stringify and then after we've saved
this into local storage when we load the
page up here we're going to load the
score that we just saved from local
storage using local storage. getet item
and the score was saved as a Json string
so we need to convert it back into an
object using json.parse
so that's how we use the Json object and
the local storage object to save our
score more
permanently let's press okay
okay and the last feature we're going to
add is when we click the reset score
button we also need to remove the score
from local storage otherwise if we press
reset score and
refresh and then play the game it will
just grab the old score from local
storage so reset score doesn't really
work here let's press okay and fix this
issue so here in the set score button at
the end we're going to remove the score
from local storage so we'll type
local
storage and then a method called do
remove item and
brackets and between the brackets we're
going to tell local storage which value
we want to remove so we're going to
remove the score so we'll type the
string score
if we
save and we click the reset button and
then we refresh the page and try to play
the game
again unfortunately it now gives us an
error so what is happening here so
remember that we remov the score from
local storage so now when we load the
page this actually doesn't exist when
something doesn't exist in local storage
it's going to give us a value called
null
and at the
bottom if we try to access any property
on null it will give us an error so
that's what we see here so how do we
solve this problem if we scroll
up one way to solve this problem is that
if there is no score in local storage
we're going to give it a default value
let's look at how we can do that so
after this line we're going to check if
the score is null we can do that using
an if statement if brackets and curly
brackets and we'll check if score is
equal to
null and if it is equal to null we're
going to give this a default score so
inside the curly
brackets we'll just make the score equal
to the default object we had earlier
which was
wins zero and then
losses zero and
ties
zero and remember if we need to reassign
a variable we have to change it from
const to let if we
save the score will be null because we
removed it earlier and now this will
give it a default score so everything
should work as before
if we play the
game you'll notice that the score starts
from zero or this default score and
everything is working again so that's
how we create the score feature in the
rock paper scissors project as well as
the reset score
feature next we're going to use some
shortcuts to simplify our code so these
shortcuts are things that we learned in
the Boolean lesson so remember that null
is a falsy
value that means it will behave just
like false so a shortcut we can use here
is instead of checking if the score is
equal to null we can also remove this
and check if not
score so not score does the same thing
as checking if it's null if the score is
null not score will flip it into true so
both of these will return true if the
score exists it's an object then both of
these will return false so instead of
checking if a value is equal to null we
can just use the not operator as a
shortcut now also from the boolean's
lesson we have an even shorter shortcut
for doing this so notice here that this
code basically sets a default value if
the score doesn't exist in the boolean's
lesson we learned a technique called the
default operator which is exactly what
we need here so on this line we can
remove the semicolon and type
or and then a default value so we want
our default value to be this object so
let's select it and then
rightclick copy
and then here right click and
paste and I'll select these lines and
press shift tab to remove and indent and
I'll add a semicolon back at the
end so the way that the default operator
works is that if the left side is truthy
so in this case we have a score it will
use the left side if the left side is
falsy or in this case the score is null
then we will use the right side as a
default value so this does the same
thing as this code below but it's just a
shortcut so now let's comment out this
code using
slashstar and at the bottom start slash
so we'll leave it here just for
reference and then
save and if we click reset score again
and
refresh and play the
game it will still work so this is a
perfect situation to use the default
operator to simplify our
code so let's press
okay and that's all we're going to do
for this project in this
lesson now let's move on and learn more
details about objects the first thing
we'll learn is the value null so null is
one of the falsy values in JavaScript
it's similar to the value undefined they
both represent that something doesn't
have a value so what's the difference
between null and undefined we use null
when we intentionally want something to
be empty for example in the previous
lesson we learned that if a function has
parameters we can give the parameter a
default value if the parameter is
undefined
it will use the default value however if
we set this parameter to null it will
not use the default value and it will
just use null so null means we
intentionally want something to be
empty in most cases though null and
undefined work the same way okay so the
next detail about objects we're going to
learn is called
autoboxing let's go back to objects. HT
HML and open the tab for this
file and let's also comment out the
previous code so our console doesn't get
too messy so
slashstar and at the
bottom star slash and
save so let's scroll
down we learned in this lesson that
objects can have properties and methods
so you might be surprised to learn that
other values also have have properties
and methods for example at the bottom
we're going to type
console.
log the string
hello and then the dot notation and a
property called
length so strings can also have
properties the length property tells us
how many characters or letters are in
this string so hello has five letters so
if we save the length property will be
five here's another example we'll type
console.log the string hello and then
the dot notation and a method this time
2 capital u upper Capital C case and
brackets so this string also has a
method called two
uppercase and this method gives us a
copy of the string with all letters
capitalized or in
uppercase if we save it will give us
hello in capital
letters so as you can see simple values
like strings can also have properties
and
methods so now you might be wondering
these are strings not objects how can
strings have properties and methods the
answer is that JavaScript has a special
feature called Auto boxing JavaScript
automatically wraps this string in a
special object first and this object has
the property length and the method to
uppercase so this is done automatically
we don't see the special object that's
wrapped around this string so this
feature is called
autoboxing because JavaScript automat
automatically wraps the string in an
object like a
box so autoboxing also works with other
types of values like numbers and
booleans the only thing is that auto
boxing does not work with null and
undefined it would just give us an
error The Last Detail we're going to
learn about objects is a really
important detail and that is objects are
references to demonstrate let's create a
new variable with an object so
const object one and make it equal to an
object inside this object let's have a
property
message colon and the string
hello so you might think that when we
create an object like this we create a
value that has other values inside and
we save the whole thing and a variable
however this actually works a little
differently when we create this object
the actual value is created somewhere in
the computer's memory and this variable
actually just gets a reference that
points to that location in the
computer's memory this is like a
shortcut on your computer a shortcut
points to where the actual file or
folder is so there's no way to actually
see this reference but just just know
that this is a reference and the object
is somewhere else in the computer's
memory so the reason it works this way
is to make the language more efficient
for example below this line we can
create a variable const and call it
object 2 and make it equal to object
one so this code doesn't actually make a
copy of the object it this makes a copy
of the reference that points to the
object so this makes a language more
efficient because if we had a really big
object here it's not good to copy the
entire object over and over again
instead Javas just copies the reference
which is much faster this is called copy
by
reference now that we learned that
objects are actually references let's
learn some interesting behaviors of
references so at the bottom here we're
going to change the property message in
this object we can do that by typing the
object object
1. message property and make it equal to
something else like the string good
job and now if we
console. log object one
and
save notice that we were able to change
the message property even though we
created object one with const and that's
because this variable just contains a
reference that points to the object so
const prevents us from changing the
reference in the variable but it doesn't
prevent us from reaching into the
reference and changing the object that
it's pointing to so just be careful when
you're working with with objects even
though we use const we can still change
the values inside the object another
interesting behavior is that on this
line we're not actually copying the
object into this variable we're copying
the reference so object two actually has
the same reference as object one they
actually point to the same object in the
computer's
memory so at the bottom if we type
console
log object 2 and save you'll notice that
for object two the message property was
also changed even though we only changed
object one the last interesting behavior
is that we can't compare objects
directly for example let's go to the
bottom and we'll create a new object
using
const object 3 and we'll make it equal
to an object and then inside we're going
to have these same values as object one
so we'll have the property
message and the value is the string good
job so now let's try comparing object 3
to object one so here we'll type console
do
log and check if object 3 is equal to
object
one if we
save it will tell us that these two
objects are not equal to each other even
though they have the same values inside
and that's because remember objects are
references so object 3 also contains a
reference and this code compares the
references and not the values inside the
object so because object 3 is a
different reference than object one
that's why this code results in
false if we
did
console. log and we check if object 2 is
equal to object
1 object two has the same reference as
object one it points to the the same
object in the computer's memory so if we
save this will tell us that these two
variables have the same
reference so just remember that when
you're comparing two variables that
contain objects you're actually
comparing the references not the values
inside if we want to compare the values
inside we would do that manually by
checking the message property against
this message property so don't worry
object references are a little confusing
at first but the more you work with it
the more you just get used to
it the last thing we're going to learn
in this lesson are some shortcuts for
objects so first let's make a copy of
object 3 we'll select the code and
rightclick
copy and then at the
bottom we'll scroll down and right click
and paste
and let's rename this variable to object
4 so now let's say that we want to get
the message property out of this object
we can do that by typing object
4.
message and now let's also say that we
want to save this in a variable also
called message so at the front we'll
type con
message and make it equal to this
value so now if the variable name and
the property name are the same we
actually have a shortcut for this to use
a shortcut we're going to type const and
curly brackets
message and make it equal to object
4 so this shortcut is called
destructuring this will take the message
property out of object 4 and save it in
a variable called message so this line
of code does the same thing as the code
above so let's comment out this line
using double slash and we'll just keep
it for reference so at the bottom if we
type
console.log
message and Save
it will display good job so the
destructuring shortcut took the property
out of the object and saved it in this
message
variable next we can use this
destructuring shortcut for multiple
properties for example let's add another
property to this object using comma and
we'll add a price property colon
$7.99 and now we can take the price
property out of this object by typing
after message a comma and
price so this will take the price
property out of the object and save it
in a variable called
price if we
console.log the
price and
save it will display $799
so that's the destructuring shortcut
it's an easier way to take properties
out of an
object the next shortcut we're going to
learn is called the shorthand property
so at the bottom let's create some new
lines and let's say we want to create a
new object so we'll type const and let's
name this object 5 and we'll make it
equal to an
object and inside ins this object let's
say we want to create a message property
so we'll type message colon and for the
value let's type the variable
message so what this does is that it
takes whatever is inside the message
variable and substitutes it into this
code so at the bottom if we
console.log object 5 and
save this object will have a property
called message and the value is whatever
is inside the message variable which is
good job so now we actually have a
shortcut for this code if the property
and the variable name are the same we
can actually just type it out once like
message so this code does the same thing
as message colon message and this
shortcut is called the shorthand
property so if we comment out this line
using double
slash and
save you can see that this shortcut
creates the same object that we had
before the last shortcut we're going to
learn is called the shorthand method so
at the end let's create a new property
comma and let's name it
method Po in and we'll save a function
in this property so we'll type
function and let's name it Function One
brackets and curly
brackets and inside this function let's
console.log
method and now here at the
bottom let's run this function by Ty
typing object 5. method so this will
access this function and we'll run it by
typing
brackets if we
save this will run the code in the
function and display method in the
console so we actually have a shortcut
for writing this so at the bottom we can
type method again and just type brackets
and curly brackets
console.log string
method so this code does the same thing
as the code above so these brackets will
create a function just like here so this
function name is actually not needed so
if we comment out these lines of
code and
save it will still display method in the
console because this is a shortcut for
these lines of code so this shortcut is
called the shorthand method
syntax and that's the end of this lesson
in this lesson we learned another type
of value called objects objects group
related values together we added a score
to our rock paper scissors game we
learned about built-in objects and used
the Json and local storage objects to
save our our score more permanently we
learned more details about objects like
null autoboxing and references and we
learned some useful shortcuts like
destructuring shorthand properties and
shorthand methods here are some
exercises to help you practice working
with objects
in this lesson we're going to learn one
of the most important features of
JavaScript called the document object
model or the Dom and we're going to use
the Dom to improve our rock paper
scissors project so first we'll create a
new file for this lesson let's go to our
code editor and click this icon to show
our files and then click this icon to
create a new file and we'll name this
file 09
dd.
HTML and press
enter next let's copy objects. HTML into
dom.
HTML so we'll click here to open the
file file and then click inside and then
type contrl A or command a to select the
code and then
rightclick
copy and in
here right click and
paste now let's hide these files and
we'll prepare this file for this lesson
so let's scroll to the
top and we'll change the title to
Dom and let's delete all the JavaScript
code from the previous
lesson now let's save this file and
we'll open it in the browser by right
clicking open with live
server and let's also open the console
on this page we'll right click click
inspect and then click the console
and now we can close the previous
tabs as well as the previous code for
now and for this lesson we're going to
do an extra step in the setup inside the
body we're going to create a
button so here let's type the code less
than button greater than and inside the
button we'll have the text
hello now let's
save and we should have a button on the
page and now we're ready to learn the
document object model or the Dom in the
previous lesson we learned about objects
which group multiple values together we
also learned about builtin objects which
are objects that are provided by
JavaScript some examples of built-in
objects are console math Json and local
storage the Dom is another builtin
object called the document object so
let's go to our script element and we're
going to type
document so this is a built-in object
provided by JavaScript and we've
actually seen this document object
before in the first lesson one of the
first pieces of code that we learned was
document dot body do inner Capital
HTML equals the string hello and
semicolon so this code removes
everything on the page and replaces it
with the text hello if we
save it will remove the button and just
put
hello and now that we learned objects in
the previous lesson we can fully
understand this
syntax document here is a built-in
object and this is the dot notation this
means we're accessing a property of the
document object called body now body is
also an object so we can use the dot
notation again to access a property of
the body object called inner
HTML and finally we use an equal sign to
change the inner HTML property to the
string
hello but as you can see there's
something very special about the inner
HTML property when we change this
property it also changes the web page so
this document object and the web page
are linked together let's do another
example we'll go to the end here and
press enter and we'll type the document
object again
and we'll use the dot notation again and
this time let's access the property
title and we'll change the title
property using an equal sign and we'll
change it to the string good
job if we
save changing the title property we'll
also change the title at the top of the
tabs here so now this says good job
again as you can see the document object
is linked to the web page so from these
examples it shows us that the document
object represents or models the web page
and that's why we call this feature the
document object model or the
Dom now that we know what the Dom means
let's learn the syntax rules for the Dom
so the Dom is just this built in
document object and this object works
the same way as any other object it
contains properties like body and title
that we can access using the dot
notation now the special thing about the
document object is that it is linked to
the web page that means if we change
certain properties in this object it
will also change the web
page now in addition to properties the
document object also has methods we can
use and we'll learn about them later in
this
lesson now that we understand the syntax
of the document object let's learn about
the properties and methods we can use
first let's comment out this previous
code using
slashstar star slash and we'll create
some new lines at the
top so the first property will we're
going to learn is called
document.title
so this property will give us the title
at the top of the tabs here so if we
console.log this property
console.log and
save this will give us the text at the
top which is Dom and that's what gets
displayed in the
console if we change the doc do. tile
property it will change the text at the
top of the tab so here if we type
document.title and make it equal to the
string
changed and
save now the title at the top of the tab
will be
changed so as you can see the title
property is linked to the title at the
top of the tab
we can use it to get the title and we
can also use it to change the
title next we're going to learn another
property called
document.body so let's go into our
code and let's type
document.body now document.body is a
very special property so this will
literally get this body HTML element
element and put it inside our
JavaScript so let's actually console.log
this to see how it works
console.log Open
Bracket and then close bracket and
save and inside the console it will tell
us that
document.body is the body HTML element
and if I hover over this it will tell us
that it is a exactly the body on our
page if I expand this you can see that
this code is exactly the code that we
have here and this shows us one of the
most important features of JavaScript we
can have HTML elements inside
JavaScript the document object or the
Dom combines JavaScript and HTML
together and it gives JavaScript control
of the web page
okay so now that we have an HTML element
inside our JavaScript what can we do
with it a really important thing to know
is that when an HTML element is inside a
JavaScript like this the HTML element is
converted into a JavaScript object so
for example if we do
console.
log type of document do
body and
save it will tell us that the body HTML
element is just an object when it's
inside
JavaScript so just like any other object
this has properties and methods we can
use so one useful property of the body
element is inner HTML which we saw
earlier so down here let's type
document dot body dot inner Capital
HTML so the inner HTML property controls
all the HTML inside the body that's why
it's called inner
HTML so if we access this property it
will give us all the HTML inside the
body so let's console.log to
confirm
console.log and
save and inner HTML will give us all of
this HTML inside the body
element and if we change the inner HTML
property it will change the HTML inside
the body element so let's create a new
line and we'll type document
dot
body do inner Capital
HTML and we'll change it to the string
changed so this will replace all of the
HTML inside the body with a text changed
if we
save that's exactly what it does and we
can actually confirm this by going into
the elements tab so this tab is for HTML
and CSS we can find the body element
expand it and you can see all of the
HTML that we had before was replaced
with
changed and don't worry about this part
this part is just added by live server
after so this shows that inner HTML
gives us control of all the HTML inside
the body we can get this h HTML and we
can also change this
HTML now another feature of inner HTML
is that we can replace this HTML with
new HTML code not just text so for
example instead of just text we can
replace it with the code less than
button greater than and also less than
slash button greater than so so this is
HTML code for creating a button and
inside the button let's put the text
good
job and now this code will replace all
the HTML inside the body with this new
HTML if we
save it removes all the previous HTML
and this new HTML creates this button so
using this inner HTML property
JavaScript can replace the HTML inside
the body to whatever we want we have
full control of the web
page all right now we're going to learn
a method of the document object that we
can use as a reminder a method is a
function that is saved inside an
object so we're going to learn a very
important method called document. query
selector we just learned that
document.body lets us get the body
element and put it inside our
JavaScript document. query selector lets
us get any element from the page and put
it inside our JavaScript let's give it a
try so first we'll comment out the
previous code using
slashstar and star
slash let's create some new lines at the
top
and let's type
document. query capital S
selector and
brackets so document. query selector
lets us get any element from the page
and put it inside our
JavaScript between these brackets we're
going to put a string this string tells
JavaScript which HTML element to get
from the page
so if we type
button this will get the first button
element from the page and put it inside
our JavaScript so let's console.log this
to
confirm
console.
log close bracket and
save and let's go back to our
console now it will tell us that
document. query selector got this button
element and put it inside our JavaScript
which you can see in the console and if
I hover over this button element it will
tell us that it is exactly the button on
the page so that's what document. query
selector does it can get any element
from the page and put it inside our
JavaScript this string tells it which
element to get if we type button it will
get the first button element from from
the page if we type
body this will now get the first body
element from the page so it will do the
same thing as
document.body but for now let's just
change this back to Button as an example
and
save so remember when an HTML element is
inside JavaScript it's just a JavaScript
object so this button element
is also just an object and it has
properties and methods we can
use every HTML element actually has a
property called inner
HTML which lets us control the HTML
inside the element so for this button
element let's type at the end dot inner
HTML and this will give us the HTML
inside the button if we
save it will give us
hello and again if we change the inner
HTML property it will change the HTML
inside the button so let's make a copy
of this code we'll select it and
rightclick
copy and down
here right click and
paste and let's change the inner HTML
property using an equal sign and the
string
changed so this will only change the
HTML inside the button which is here to
changed if we
save you can see that the text inside
the button is now changed a little
syntax shortcut I'm going to show you is
that for the dot notation we can
actually put it on multiple lines so we
can type document. query selector and
then put doin HTML on a separate line to
make it easier to read and make sure to
put a tab at the front so that we know
it's a continuation of the previous
line okay so using document. query
selector we can get any element from the
page put it inside our JavaScript and
then we can control the h HML inside
that element and this allows us to only
change the parts of the page that we
need next what if we have two buttons on
the page so let's go up here and we'll
create another button using less than
button greater than and we'll have the
text
second
button and
Save so now we have two buttons on the
page but document. query selector will
only get the first button on the page
how do we get this second button the
solution is that we're going to add an
attribute to this button called the
class attribute so in the opening tag
we're going to type space class equals
double quotes So the class attribute
sort of adds a label to this button so
inside the double quotes we're going to
label this button a JS dash
button and now that we labeled this
button we can select it using document.
query
selector so at the bottom here we'll
type
document. query selector again and
brackets and we'll type A String inside
and this time we're going to start with
a DOT when we start with a DOT this
means that it's going to look for a
class rather than an element name so
we're going to look for the class
js-
button and now document. query selector
will select an element with the class JS
button which is this element here so
let's confirm this by
console. logging this
code and
save and now you will see that this code
gives us the second button on the page
so using a class attribute and then
starting with a dot in query selector we
can get any specific element from the
page and put it in our
JavaScript by the way when we start with
a DOT this is called called a class
selector and this is also used in CSS to
style elements with a specific class in
fact anything we use in CSS can also be
used in this
string and also a common practice is to
start the class with
js- to make it clear that this class is
being used in
JavaScript and again HTML elements are
JavaScript objects so this second button
is also just an object and remember
objects are values and we can save them
inside a variable so instead of
console.log let's create a variable
using const and we'll name the variable
button capital E
element we usually end the variable name
with element or LM to make it clear
clear there's an HTML element inside
this
variable and finally we'll type an equal
sign to save this element and we can
remove this extra
bracket and now if we console.log this
variable
console.log
button
element and
save it will tell us that the second
button was Sav saved inside this
variable so using the Dom we can get
HTML elements from the page put it
inside a JavaScript and then save it in
a variable so the Dom combines
JavaScript and HTML together it gives
JavaScript full control of the web
page all right now that we learned how
to use the Dom let's do some practical
examples so I've actually prepared some
projects that we can do for this lesson
to open these projects we'll go to our
browser and create a new tab at the
top and here we'll type
super
simple. SL projects
slod and press
enter on this page we'll be working on
three projects the YouTube subscribe
button the rock paper scissors project
we've been working on for the last few
lessons and this Amazon shipping
calculator and you'll notice that these
projects modify the web page so we're
going to be using the Dom to create
these projects and in the next lesson
we're going to use CSS to style these
projects and make them look nice and you
can preview that by clicking
here so using CSS we can make the sub
subscribe button look like the actual
subscribe button on YouTube and if we
click this link to see the rock paper
scissors game you'll see that we'll make
it look really nice with these icons but
for this lesson we're only going to
focus on the functionality and not the
styling so let's go back to the projects
we'll click back and click back
again until we're at projects sdom
and we're going to create the
functionality for these projects first
so before we start let's create a new
file just for these projects we'll go to
our code editor and click this icon and
then click this icon to create a new
file let's name this file 09
dd-
projects. HTML and press
enter now let's copy dom. HTML into this
file so we'll open it and then click in
here and type control a or command a to
select the code and then
rightclick
copy and in
here right click and
paste now let's close our files and
we'll prepare this file
so let's scroll up and we'll change the
title to Dom
projects and let's remove our HTML but
keep the script
element and we'll also remove the
JavaScript from
before finally let's save this file and
we'll open it in the browser by right
clicking open with live server
and let's also open the console just in
case right click click
inspect and then click the
console all right we're ready to start
with the projects let's go back to super
simple
dodev and we'll start by creating the
YouTube subscribe button let's actually
press refresh to get it back to normal
and when we click this button it will
change to subscribe
red first let's create the HTML elements
for this project we'll go to the body
we'll create some new
lines and let's create the paragraph
first we'll type less than P greater
than and inside the paragraph we'll have
the text
YouTube
subscribe
button and now let's create the button
so on the next
line we'll type less than button greater
than and inside the button
subscribe now let's save and go back to
our
Tab and now we have the HTML elements
that we need so now let's make this
interactive with JavaScript and remember
we have a process for this first we'll
figure out what steps we need to do this
is called an algorithm and then we'll
convert these steps into code so the
steps that we need here are when we
click this button if the text is
subscribe we'll change it to
subscribed otherwise we'll change it
back now let's convert these steps into
code let's go to our button element and
we're going to add an onclick attribute
we'll type space on click equals double
quotes and inside here we'll write some
JavaScript so first we need to get the
text inside the button and we learned
how to do this earlier we can use
document. Query selector to put this
button into our JavaScript and then use
inner HTML to get this HTML inside the
button so in our code let's type
document. query
selector brackets and a string and as we
learned we're going to use a class
attribute to select this specific button
so in the opening tag let's add a class
attribute and let's make the class
js-
subscribe Dash
button and then inside document. query
selector we're going to type a DOT to
select a class and we're going to select
the class
js-
subscribe Das
button and now let's console.log this to
confirm that we got this button so at
the front
console.log and
save and now let's click our
button and it will show us that
document. query selector got the button
on the page so now let's save this
button in a variable so we can use it
later instead of
console.log let's type const to create a
variable and we'll name it
button
element and make it equal to this
result so now that we have the button
inside our JavaScript we're going to
check if the text inside the button is
subscribe to check the text we can use
an if statement so at the bottom here
we're going to type if brackets and
curly
brackets and inside this condition let's
get the text inside the button so we'll
type button
element do inner Capital
HTML and we're going to check if it's
equal to subscribe so we'll type triple
equal the string
subscribe now if it is equal to
subscribe inside the curly brackets
we're going to change the text in the
button to
subscribed so let's type the code
button
element do inner Capital HTM L and we'll
change it with an equal sign to the
string
subscribed and the last step is
otherwise we'll change it back so we'll
add an else to this if
statement else and curly brackets and
inside we're going to change the text
back to
subscribe so let's type
button
element. inner Capital
HTML and make it equal to the string
subscribe and
save now before you try out this project
make sure that the text inside the
button has no spaces or new lines around
it and it looks like this and I'll show
you why in a second let's go to our
project and try it out so when we click
this button it will change to the text
subscribed if we click it again it will
go back to the original text so that's
how we create the Subscribe button
project using the Dom so now let's go
back into our code and I'll show you why
if we add new lines
and some spaces around this
text there's actually going to be some
problems so if we save this
code and then go back to our project and
click the button again you'll notice
that it no longer changes the text and
that's because now we have a bunch of
spaces around this text and these spaces
will show up in inner
HTML and now inner HTML will not equal
exactly
subscribe so how do we solve this
problem when there are spaces around our
text to solve this we're going to use a
different property of an HTML element so
instead of the inner HTML property we're
going to use the property inner capital
T
text so inner text will give us the text
inside this element but without all the
spaces around it
so now this will equal exactly
subscribe if we save and go back to our
project and click it again it'll start
working again so that's the inner text
property of an HTML element it gets us
the text without the extra
spaces so before we move on to the
second project I'm going to show you how
to make our code
cleaner right now we're mixing a HTML
and JavaScript together so to make our
code cleaner and easier to read we're
going to separate the JavaScript code
and to do that we're going to put this
code in a function
instead so inside the script
element let's create a function using
function and we'll name the function
subcribe brackets and curly brackets
and inside these curly brackets we're
going to move all of this code so let's
select this
code and we'll right
click
cut and in here right click and
paste and if we need to fix the
formatting we can select these lines and
press tab a few times and now that we
have this function we're going to go to
the onclick attribute and and we're
going to call this function so we'll
type the function name
subscribe and
brackets so this will run all the code
inside the function so it will do the
same thing as before except now our code
is cleaner because we grouped all the
JavaScript code at the bottom and we're
no longer mixing as much HTML and
JavaScript
together now let's move on to the second
project we'll go back to superimple
dodev and we're going to work on the
rock paper scissors project so let's
click this
link and it will show us the next
version of this project so you notice a
few changes here the first change is
that we're going to show the score on
the page instead of in a popup and the
second change is that when we click one
of these buttons to play the game it
will show us the result and the moves
that we picked on the page rather than
in a
popup let's create a new file for this
rock paper scissors game for this lesson
so let's go to our code
editor and we'll click this icon and
click this icon to create a new file and
we'll name this
09-
rock- paper Das
scissors.
HTML and press
enter and let's copy the previous rock
paper scissors which is here we'll click
here and type control a or command a
right click
copy and here right click and
paste and let's hide our
files and let's save this F file and we
can also close 08 rock paper scissors
and finally we'll open this in the
browser by right clicking open with live
server now we're ready to begin the
second project so let's go back to the
project at super simple Dev and we're
going to start by putting the score on
the page so to do this we're going to
need somewhere to put the score so let's
create an HTML element for this we'll
scroll up to our
HTML which is
here and after the scissors button let's
add a paragraph element where we're
going to put our score so less than P
greater
than and let's add a class attribute so
we can select this element in our
JavaScript so in the opening tag we'll
type space class equals double quotes
js-
score now that we have a class let's get
this element in our
JavaScript so let's just do it down here
so we'll type
document.
query
selector brackets and a string and then
we're going to type a Dot and we're
going to select the class js- score so
js-
score so this will get the paragraph
element from above and put it inside our
JavaScript and now let's put the score
inside the element to do that we can use
inner
HTML dot inner Capital
HTML and we'll make it equal to the
score if we scroll
down we actually create the score down
here so we can actually just copy this
string so we'll select it
rightclick
copy and let's scroll
up to here and I'll actually put this on
a separate line to make it easier to
read and now here we're going to type a
string using back
ticks and inside the string we're going
to rightclick and
paste so this will put the score that we
used to have in our popup inside this
element so inside this
paragraph if we
save and then go back to our
tab you can see that now it displays the
score on the page now before we move on
I want want to point something out with
HTML so remember that our reset score
button was beside our other buttons and
now it's below them so what determines
if an element appears beside something
or below something so the paragraph
element Here is known as a block element
a block element will always take up an
entire line by itself so this line
already has some buttons so the
paragraph will take up the entire line
under the buttons that's why this text
appears under the buttons and not beside
them and also because a block element
like this paragraph takes up this entire
line the next button has to appear below
it so that's why we get this layout here
so this is just a short review of
layouts if you want to learn this in
more detail you can check out my HTML
and CSS full course in the video
description all right the next feature
we're going to do is if we play the game
we also want to update the score right
now if we play it doesn't update it on
the page let's fix this in our
JavaScript so let's go down to where we
update the score so we'll scroll
down which is right here we update the
score and save it in local storage and
after we do this we're also going to
update the score on the page so we can
actually use the same code that we used
above which is here so let's make a copy
of this code
rightclick
copy and down
here right click and
paste and I'll add a tab at the front if
we save and then try out our game we'll
click a move press
okay and now you'll notice the score
also updates on the page so let's go
back into our code and do some cleanup
so you notice that this code is the same
as the code we had above and this is a
great situation to use a function to
reuse this code so at the bottom here
let's create a function using function
and we'll call it
update
score
element brackets and curly
brackets and we'll move this code into
the function so we'll select it right
click
copy and in here right click and
paste and now instead of writing this
code multiple times we're just going to
call the function
update score element and
brackets this will run all the code
inside the function so it does the same
thing as before except we can reuse the
code so let's scroll back
up and instead of typing out all this
code again we can just use our
function
update
score element
and
brackets now let's
save it will display the score on the
page at the start and when we click a
move and click okay it will update the
score on the page so the last feature
we're going to do in relation to the
score is when we click the reset score
button we also want to update the score
on the
page right now if we click it it doesn't
actually update it
so let's go into our code and let's go
to the reset button which is here and
after we reset the score we're going to
call that function again
update
score element and
brackets if we
save and now let's play the game and
press okay so we have a score and if we
click reset score it will reset
everything back to zero so now we
finished the score let's go back to
super simple
Dev and play the
game and now we're going to work on this
section we're going to show the result
and the moves that we picked on the page
so first let's create some paragraphs
for these as well we'll go to our
HTML and above the score
let's add a less than P greater than
this is going to be the result so let's
give it a class of
js-
result and let's create another
paragraph less than P greater than and
we'll give this one a class equals
js- moves
now let's use the Dom to put the result
and the moves in these paragraphs feel
free to pause the video if you want to
try it yourself first so let's scroll
down to where we display the
result which is here so we display it in
a popup and instead of a popup we're
going to get the paragraph and put this
result inside the paragraph so we'll
type
document. query
selector brackets and a string and we'll
type a DOT and select the class
js-
result and then dot inner Capital
HTML and we'll change this to
result and now let's also display the
moves so we'll type some new lines and
document. query selector again brackets
and a string dot
js-
moves do inner Capital
HTML and make it equal to this text
right here so let's type a template
string because we're going to insert our
Moves In inside the string and we'll
Type
U and we'll insert the player move
dollar curly
brackets Player move and then a dash and
then the computers move so dollar curly
brackets again and
computer
move computer at the end so now that
we're displaying everything on the page
we don't need this popup at the end so
we can actually delete this
popup all right now let's
save and go back to our
Tab and play our
game now it will show the result and the
moves that we picked on the page instead
of in a popup let's play it again to
make sure it works and finally when we
click reset score it it will reset
everything back to zero and that's it
now we're displaying everything on the
web page using the
Dom now let's move on to the third and
final project we'll go back to Super
simple.
deev and we'll click back to go back to
our projects and we're going to create
this third project here which is an
Amazon shipping
calculator the way this works is is that
inside this text box we're going to type
the cost of an order in dollars if the
order is under
$4 for example
$25 and we click
calculate it will add $10 of shipping
and display the total down here but if
we type a cost that is over
$40 like 50 and press
calculate it will be free shipping so so
it will display the same total down here
so let's learn how to create this using
the
Dom let's go back to our 09 Dom projects
file and we'll start by creating the
HTML
elements so under our subscribe
button let's create this paragraph using
less than P greater than
Amazon shipping
calculator and next let's create this
text box so the HTML element for a text
box is called input so we'll type less
than input greater than so the input
element is special because it doesn't
require a closing tag this is called a
void
element and lastly let's create the
button so here we create less than
button greater than
calculate now let's
save and open the tab for this file
which is right here and we have the text
the text box and the button that we need
now one other thing we're going to add
is that in the final project if we don't
have anything in the text box we're
going to have this gray text so this is
called a placeholder to add a
placeholder to a text box we're going to
use the placeholder attribute so inside
our input element we're going to type
Space Place
holder equals double quotes and inside
the quotes we'll put the text we want as
the placeholder which is cost of
order and
save now if we go back to our project we
now have a placeholder in our text box
that disappears when we start
typing so that's all the HTML that we
need now let's work on the JavaScript
and again we'll figure out what steps we
need to do so when we click this button
we're going to get the text inside the
text box if the amount is below $40
we'll add $10 of shipping and then we'll
display the total on the page let's
convert these steps into code so we'll
go to our button and add and onclick
attribute and inside here let's also
create a function to separate our
JavaScript code like we did before so in
the script we're going to create a
function function
and let's name it
calculate total brackets and curly
brackets and inside on click we're just
going to call the function so
calculate
total
brackets the next step is to get the
text inside the text box so first let's
get this input element and put it inside
our J JavaScript to do that we can use
document. Query selector again so we'll
add a class to this input so we can
select it class equals
js-
cost-
input and then inside our JavaScript
we'll use
document.
Query
selector brackets and a string and a Dot
and this class
js-
cost-
input so this code will get the input
element and put it inside our JavaScript
let's confirm by
console. logging the
result and
save and now when we click the calculate
button it will give us
the input element from the page let's
save this input element in a variable so
we can use it later instead of
console.log we'll use const and we'll
name the variable
input element and make it equal to this
element and remove the extra
bracket and next we need to get the text
inside the input element so so far in
this lesson we've been using the
property inner HTML to do this however
for input elements you notice that there
is no HTML inside so for input elements
we're going to use a different property
called
value so at the bottom here we're going
to type
input
element.
value this is how we get the text inside
a text box
so let's console.log this to confirm
that it works so we
console do
log and
save and now let's type something in the
text box like 50 and click
calculate and input. value will give us
the text inside the text
box let's save this text in a variable
so so we can use it later con and we'll
name the variable cost and make it equal
to the text in the text
box the next step is to check if this
cost is under
$40 if it is We'll add
$10 so down here let's type if brackets
and curly
brackets and inside the condition we'll
check if cost is less than
40 and if it is inside the curly
brackets we'll do cost equals itself
plus $10 of shipping and remember when
we change a variable we have to switch
from const to
let and finally we're going to display
the total cost on the page so let's
create a paragraph where we can display
the cost so down here we'll create a
paragraph less than P greater than let's
give it a class
js- total Das cost and now inside our
JavaScript let's use
document. Query selector brackets and
string and we'll Type A Dot and the
class
js- total Das cost and we're going to
put the cost inside the paragraph we can
use dot inner Capital
HTML and make it equal and let's use a
template string so back ticks and we'll
have a dollar and we're going to insert
the cost using dollar and curly brackets
cost now let's save and try out this
project so first we'll type a cost that
is over
$40 like 50 if we press
calculate we're not going to add $10 of
shipping and we'll display the same
total on the page now let's try a number
under
$40 like 25 and press calculate
and this number doesn't look right it's
saying that we have to pay
$2,510 so what's going on here let's go
into our code and let's use console.log
to figure out what's wrong so first
let's console.log the cost to make sure
that we're getting the right number from
the text box so down here
console.log the cost
and save and then let's Type 25 again
and press
calculate and it will give us 25 so
we're getting the correct text from the
text box now let's console.log down here
to see if the math is working so we'll
type
console.
log
cost and
save and let's try 25 again and
calculate
and down here when we add 10 this is
where things go wrong and it results in
20510 so it's not doing math properly
here so let's check if cost is a number
to make sure that it's doing math so
here we'll type
console.log the type of
cost and Save
let's Type 25 again and calculate and
aha it's telling us that the cost is a
string so this is actually not a number
it is a string that's why it's not doing
math so remember from the strings lesson
when we add a string with a number
JavaScript will automatically convert
this number into a string and combine
them together that's that's why it just
combines 25 and 10 here this is called
type
coercion so whenever we get a value from
the Dom like this the value will be a
string so in order to do math we have to
manually convert this string into a
number to do that JavaScript has a
builtin function called number so before
this code we're going to type capital n
number Open Bracket and close bracket so
the number function takes whatever's
between the brackets and manually
converts it into a number so now if we
save and we Type 25 and press
calculate the cost is now a number and
it will do the math properly and give us
35 so remember whenever we get a value
from the Dom the value will be a string
so if we want to do math with it we have
to manually convert this value into a
number first so now let's remove the
console. logs that we used to figure out
this
problem and
save okay we're going to add one more
feature to this project let's go back to
superimple
dodev and inside the text box we're
going to Type 25 and press
enter so pressing enter will also
calculate the total and display it on
the page so let's learn how to create
this feature so if we go back to our
code so far in this course we've been
using the attribute
onclick which runs some JavaScript when
we click an element HTML has another
attribute we can use called on key down
which runs JavaScript when we press a
key down on our keyboard so inside the
input this time let's add the attribute
on key down equals double quotes and
then inside here
console. log and the string
typing so now every time we type in the
input it will console.log this message
let's save it and give it a try we'll go
to the tab for this file and then inside
the text box we'll type some numbers and
you can see that every time we type
something it will run this code and
display this
message so that's how we do something
when we type in an element so clicks and
key Downs are known known as events on
click and on key down are known as event
listeners they check for events and runs
JavaScript when those events happen now
in addition to clicks and key Downs
there are many other events we can
listen for in
JavaScript okay so now let's figure out
what steps we need to do for this
project when we press a key down in the
text box we're going to check if the key
is the enter key if it is we'll do the
same thing as the calculate
button so how do we know what key we
pressed inside on key down we're
actually given a special object called
event so instead of this string let's
remove it and we'll
console.log
event so this is an object that's
provided to us by JavaScript and it
contains information about the event
every event listener including on click
also gets an event object if we
save and type in this text
box it will show us that event is this
object and inside the object it has a
bunch of information including the key
that we typed so here let's use the
event object and we'll get dot key and
save so now inside this text box if we
type something it will tell us the key
that we pressed and if we press
enter it will tell us that the key is
enter so the next step is to check if
the key is enter and we can do that
using an if statement so in our
code we'll type a new line
if brackets and curly brackets and
inside the condition we'll check if
event. key is equal to the string
enter if it is equal to enter we're
going to do the same thing as the
calculate button so we can actually just
use this function again inside the curly
brackets we'll type calculate
total and
brackets and
save so now let's go back to our project
and type 25 enter and it will calculate
the total and display it on the page so
that's how we create this keyboard
feature of this project lastly let's
clean up our code and move this into a
function like the rest of our code so
inside the script
element let's create a new function
using
function and we'll name it
handle cost key down brackets and curly
brackets and let's move this code into
the function we'll select it
rightclick
cut and in here right click and paste
if we need to fix the formatting we can
select these lines and press Tab and
let's remove this
console.log and now up here we're going
to call this
function
handle cost key down and
brackets now the last thing we have to
do is that event does not exist inside
this function so we have to put the
event object into the function
and remember to put a value into a
function we can use a
parameter so between these brackets we
can create a parameter called event and
now to save something inside this
parameter we're going to go up to these
brackets and type
event this will take the event object
and put it inside the function where we
can use it just like a variable so now
if we
save and try out the project 25 enter so
this still works and now we finished all
three projects in this lesson so in the
rest of this lesson we're going to learn
some more details about
JavaScript in the last project we
learned how to manually convert a string
into a number using the number function
we can also convert the other way from a
number to a string so let's go to the
top of the script
element and we can type capital S string
and brackets so the built-in string
function will convert a value into a
string between the brackets we can put a
number like 25 and this will convert the
number into the string
25 the next detail we're going to learn
is a special behavior of
strings So Below this line we can type
console do log the string
25 minus
5 so if a string only contains a number
and we subtract multiply or divide
JavaScript will automatically convert
the string into a number so this gets
converted into the number 25 minus 5 and
if we save it will do math and give us
20 so this is another example of type
coercion or automatic type
conversion however it's not recommended
to do math with strings like this
because adding Works differently for
example on a new line let's type
console.log the string 25
+ 5 and
save this will convert the number into a
string and combine them together into
255 so because adding strings Works
differently the best practice is always
do math using numbers don't do math
using strings if we need to we can
manually convert the string into a
number using the number function like we
did here the last thing we're going to
learn in this lesson is another built-in
object called the window object so in
this lesson we learned about the
document object the document object
represents the web page the window
object represents the browser so let's
go into our script element and Try It
Out Below this we'll Type
window so so this is the window object
and it represents the browser because it
represents the browser everything inside
the browser is inside the window object
so let's think what's inside the browser
well the web page is inside the browser
so the document object is inside the
window object if we type
window.
document this will give us the same
document object that we've been using in
this lesson so what else is part of the
browser well the console is also part of
the browser so here if we type
window.
console this will give us the same
console object we've been using in this
course so we can actually do
console.log and the string window
and
save and this will do the same thing as
console.log what else is part of the
browser well popups are also part of the
browser so if we type
window.
alert this will give us the same alert
function that we've been using in this
course to create
popups however you might have noticed
that we never Type window window. doent
or window.
console.log and that's because the
window object has a shortcut we don't
have to type window dot at the front we
can just type document or console and
JavaScript will automatically add window
dot at the front for us so window is a
built-in object that represents the
browser we don't have to type out window
dot ourselves because JavaScript adds it
for us automatically but it's still nice
to know how this works behind the scenes
and that's the end of this lesson in
this lesson we learned about the
document object model or the Dom which
allows JavaScript to fully control the
web page we learned how to use document.
Query selector to get elements from the
web page and put them inside our
JavaScript we learned how to use inner
HTML to modify the HTML inside an
element we worked on three projects
using the Dom we learned how to make
elements interactive with the keyboard
using on key down and we learned some
more details about strings as well as
the window object which represents the
browser here are some exercises you can
do on your own to practice using the Dom
in this lesson we're going to add CSS to
all of our projects and we're going to
finish our rock paper scissors project
CSS is a different language that changes
the appearance of our website it's one
of the three languages that we use to
create websites so first let's look at
the projects we're going to work on in
this lesson we'll go to our browser and
create a new tab at the
top and here we're going to type
super simple
dodev SL projects slash
Dom Das
with-
CSS and press
enter so these are the same three
projects we created in the previous
lesson except this time we're going to
add CSS to make these projects look nice
let's start by creating a copy of the
Project's HTML file from the previous
lesson we'll go to our code
editor and click this icon to show our
files and then here we're going to
select
09-- projects we're going to right
click
copy and down here right click and
paste and let's rename this file by
right-clicking
rename at the end we're going to remove
copy and at the beginning
we're going to change it to 10 and press
enter now let's hide our
files and we're going to open 10 Dom
projects in the browser by
right-clicking open with live
server now we can close our previous
tabs as well as the previous code from
lesson 9 which is this file and these
two
and now we're ready to add CSS to our
projects we'll start with the YouTube
subscribe button let's go to the tab for
our
project and we're going to style this
button first so we reviewed CSS in
lesson 4 and one of the ways we can
write CSS code is using the style
element so inside the head section we're
going to create an element using less
than style greater than so the style
element lets us write CSS code inside so
inside here we're going to write
button open curly bracket close curly
bracket so the code in front of the
brackets is called the CSS selector this
tells the computer which elements we
want to style or change the appearance
so button will style all button elements
on the page but in this situation we
only want to style the Subscribe button
because the calculate button will be
styled differently so to style a
specific element we can use the class
attribute so if we look at our button
currently it already has a class of JS
subscribe button but this class is being
used by our JavaScript a good practice
is to add a different class that will be
used by
CSS so an element can have multiple
classes we just separate them with a
space so inside this class attribute
we're going to type space and add
another class
subcribe dash
button now this element has two classes
and we're going to use this second class
in our
CSS so to style a specific class we're
going to remove button and we're going
to type a DOT so starting with a DOT
means we're going to style a class
rather than an element name so we'll
style the class
subscribe Das
button which is this button right here
and now inside these curly brackets
we're going to tell the computer how to
style this button for example border
colon none and
semicolon if we
save this will remove the border from
the button so it no longer has a border
like this button so that's how we style
a specific element with CSS we add a
class to the element and then inside CSS
we start with a DOT and the class and
between the curly brackets the code on
the left is called the property
this tells a computer what we want to
change on the right is called the value
this tells a computer what we want to
change the property to we separate the
property and value with a colon and we
end the whole thing with a semicolon so
this is also called a property value
pair as a reminder this is just a review
of CSS if you want to learn CSS in more
detail you can check out my HTML and and
CSS full course in the video
description so we just added one style
to this button we're going to add more
Styles so that it looks like our final
design to make this easier I'm going to
rearrange my windows and I'm going to
put the final design at the bottom and
then our project at the
top this will make it easier to compare
the two
designs next to make it look like the
final design we're we're going to style
our element one by one let's go back to
our
code and press enter and next let's
change the background color to Black to
do that we'll type
background Das color colon black and
semicolon and
save now our button has a black
background let's keep going one by one
we change the text color to white next
so in our code we'll type color colon
white and semicolon and
save now if you're wondering how I know
all these properties you can usually
find them by searching in Google just
make sure you search for what you are
trying to
do let's keep going one by one the next
thing we'll change is we're going to add
spacing on the inside of the button in
CSS space on the inside of an element is
called padding so we'll create a new
line and we'll use the property
padding Das toop colon
10px and
save so this will add space on the
inside of the element called the padding
at the top of 10 PX
so the PX here means pixels a pixel is a
unit of measurement in computers your
screen is made up of many small little
squares each of these squares is called
a pixel so a pixel is the smallest thing
that you can have on your screen screen
sizes are measured in pixels images and
video sizes are also measured in pixels
and don't worry the more you work with
pixels the more you'll get used to how
big a pixel is so in this example 10
pixels is equal to this amount of space
and it looks pretty close to the final
design so let's keep going we'll add
space on the inside of the element at
the bottom this time so we'll create a
new line and type padding Dash bottom
colon
10px again and Save
and that adds space at the bottom of the
element of 10
pixels next let's increase the space on
the left and the right we'll go into our
code and add padding Das left colon 10
pixels and padding Das right colon 10
pixels let's save
and it added some extra space on the
left and right but I think our final
design has a little more space on the
left and right so let's go back and
increase our padding so instead of 10
let's try 15 on both
sides so we'll
save and now the spacing looks close
enough to the final
design so in CSS it's normal to do some
trial and error to get the styling right
let's keep styling this one by one next
we'll make the text thicker or bold so
let's go into our code and to change the
thickness of the text we'll use the
property font Das weight colon
bold let's
save and that will make our text bold so
we're almost there now let's make the
corners rounded look like in the final
design we'll go back to our CSS and the
property for making the corners round is
called
border Das
radius and we'll make it colon 5
pixels let's
save and you can see that it made our
Corners round so the pixels here tells
the computer how round we want the
corners to be the higher the pixels the
more round it will get
so if we change this to 10 pixels and
save it will make the corners even more
round so let's change this to something
really big to make it completely round
we'll change this to 50 pixels and
save and now our button is completely
round the last style we're going to add
is in the final design if we put our
Mouse over the button it turns into this
hand the icon so we call this a pointer
and we're going to do the same thing in
our project so let's go to our code and
to create that pointer icon we're going
to use the property
cursor colon
pointer and let's
save and put our Mouse over the button
and you'll notice it turns into this
hand pointer icon and that's it now our
subscribe button looks like the final
design next let's click the Subscribe
button you'll notice that it only
changes the text but if we click the
final
design it also changes the background
color and the text color so we're going
to learn how to change the CSS when we
click a
button let's go back to our code and
this time we're going to scroll down to
our
JavaScript which is here so we learned
in the previous lesson we can get HTML
elements from the page and put them
inside our JavaScript and we also
learned that these HTML elements are
just JavaScript objects and they can
have properties like inner text and
inner
HTML every element has another property
we can use called class list class list
gives us control of the class attribute
so one solution we can do is when we
click the button we can add a class and
then this class will have different
styles so let's see how we do that in
our code we'll scroll down to the
Subscribe function and when we click the
button and make the button subscribed
we're also going to add a class so let's
create a new line and we'll type button
element dot class capital L
list so class list itself is an object
which means it has properties and
methods we can use one method is called
add which adds a class to an element so
after this let's type dot add and
brackets and now inside these brackets
we're going to put a string so this
string is a class that we want want to
add when we click this button let's add
a class called
is-
subscribed and
save so now every time we click this
button it will add a class to the button
called is- subscribed let's give it a
try first we'll rightclick on the page
and then click
inspect and we'll go to the elements Tab
and I'll rearrange my windows so you can
see
it and then inside the HTML pay
attention to the class of the button now
when we click the
button it's going to add an extra class
called is- subscribed so that's what
this line of code does and now that this
button has the is subscribed class we
can style it in our CSS so let's go back
to our code
and we'll scroll up to our
CSS and here we'll type dot to style a
class and we'll style the class is-
subscribed
is-
subscribed and curly
brackets and now inside these curly
brackets let's change the background
color to Gray and the text color to
Black
Background Das color colon
gray and then color colon
black and make sure to type these Styles
below the Subscribe button Styles so
that these Styles will override the
Styles
above now if we
save and then click our
button it will add the is subscrib class
and now this button will get our new
styles that we added here so that's one
way to change the CSS when we click a
button all right now I'm going to move
this back to the
top and notice that our background color
is different from the final design the
final design uses a much lighter gray so
how do we get this exact color to do
that we're going to open the elements
tab again so on this page we're going to
rightclick click
inspect and then click the elements
Tab and I'll rearrange my windows so we
can see
it so in this section in the style
section we can see the CSS that the
element has so first let's actually find
this button which is right here and
we'll click
it and here it will show us the CSS that
this button has and it will show us the
background color that we should use so
let's make a copy of this color and put
it into our code
rightclick
copy and here we'll remove it and
rightclick and
paste now let's
save and go back to our project and try
it
out and now we get get the exact same
color as the final design so by the way
this color is known as an RGB value RGB
means red green and blue and computers
can create any color using a combination
of red green and blue so the first
number here is how much red we want in
our color the second number is how much
green we want and the third number is
how much blue we want
each number goes from 0 to
255 Zer means less color and darker 255
means more color and lighter so this
color here uses 240 for all of the
colors so it's close to 255 and will
give us a very light gray color that you
see
here next if we go back to the final
design and we click our button again
it will change back to the original
style so we're going to create this
feature in our project as well so one
way to do this is when we click the
button again we can remove this class so
let's scroll down to the
bottom to the Subscribe function and
when we click the button and we change
it back to subscribe we can remove this
class to do that class list has a
another method we can use called remove
so let's create a new line and we'll
type
button element do class capital L
list dot
remove and
brackets so this does the opposite of
add it will remove a class from this
element so inside the brackets we'll
type a string and the class we want to
remove which is
is-
subscribed and
save now let's try out our project we'll
click the button it will get the class
is subscribed and get the extra Styles
and now when we click the button again
it will remove the class and it will
remove the extra
Styles so notice here that when we add a
class we just type the class name we
don't type a DOT and the class name like
we did for query selector typing a DOT
only makes sense in query
selector next we're going to style the
text on the page let's scroll up to our
CSS and one thing we can do is to style
all the paragraph elements on the page
using this code P and curly brackets
however we're going to use a better
solution instead of styling all the
paragraphs we're just going to style the
body
element when we change the text in the
body element it will change the text in
the entire page so inside these curly
brackets let's change the text here so
we're going to use a different style of
text this is called a font to change the
font font we're going to use this
property font Das
family colon and we'll change it to
aial which is what I used in the final
design so let's
save and this will style all the text
inside the body and change the font to
aial and a good practice is to write any
styles for the body at the top so if we
need to we can override it later so
let's move these to the top we'll right
click
cut and then up
here create some new lines and right
click and
paste and we're going to add one more
style before moving on let's add some
space between the Subscribe button and
the second project so earlier we learned
that space on the inside of it element
is called padding space on the outside
of an element is called margin so inside
our subscribe button at the
bottom let's add a property called
margin Das bottom colon 30 pixels and
save so this will add space on the
outside of the element at the bottom of
30 pixels
now let's move on and style the Amazon
shipping calculator with
CSS again we'll add a class to these
elements and then style them in our
CSS let's scroll down to the text box
which is the input element and we're
going to add another class by typing
space and let's use the class cost Das
input and now we're going to style this
in CSS so let's scroll up and here we'll
style the class using dot cost Das
input and curly
brackets and inside we'll style this one
by one let's look at our final design
and see what styles we need so first
let's change the text size because our
text is a little smaller than the text
here so the change the text size
we're going to use Font Das size colon
and let's try 15 pixels and
save and now our text looks close enough
to the final
design next let's add some space inside
the text box so remember space inside an
element is called padding so we're going
to type
padding Das
top of 10
pixels padding Das bottom also 10
pixels and let's add padding to the
left 10
pixels and padding
dasr of 10 pixels so this will add a
space on the inside of our text box in
every direction if we
save now it looks just like the final
design now I'm going to show you a
shortcut for padding that will save us
some typing so if we create a new line
we can actually use a property called
padding and colon and then type 10
pixels this padding property let us add
padding on multiple sides at once if we
type one value here like 10 pixels it
will add 10 pixels to every side so this
line does the same thing as these four
lines above so let's actually comment
this out using
slashstar and star slash and
save and you can see that this one line
of CSS did the same thing as the other
four lines of CSS so this shortcut can
save us some typing
next let's move on and style the
calculate
button again we'll add a class to this
button so we can style it so in this
button let's add a class
attribute class equals
calculate Das
button now let's style this in our CSS
by scrolling up and here we'll type Dot
calculate dash
button and curly
brackets and inside these curly brackets
we're going to style this button one by
one so let's start with the background
color so we'll type
background Das color colon green and
semicolon and
save next let's change the text color to
white
so we'll type color colon
white and save
again okay let's keep going and we'll
remove the border around this button so
we'll type
border colon
none
save next let's make our text a little
bigger like in the final
design so we'll type font Das
size and make it 15
pixels and
save okay so now let's add the space on
the inside of the button so we're going
to use this shortcut again we'll type
the padding
property colon and this time we're going
to give it two values separated by
spaces 10
pixels and maybe 50 pixels so it's
easier to see what this does so when we
give two values to padding the first
value is the vertical padding so the top
and bottom the second value is the
horizontal padding or left and right if
we
save so you can see that the left and
right has a lot of padding which is 50
pixels so now let's make this match our
final design so instead of 50 pixels
let's bring it down to 15 pixels and
save okay so that looks pretty close
let's also increase the padding on the
top and bottom so that the text box and
the button line up with each other like
in the final
project so let's change the vertical
padding to maybe 12 pixels and
save the last thing we'll style for this
project is when we put our Mouse over
the button it turns into the pointer
icon so to create this we're going to
use the property
cursor colon
pointer and save and give it a
try and that's it we just finished
styling the Amazon shipping calculator
so now let's give this a try we'll Type
25 in the text box and press calculate
and at the bottom it will add $10 of
shipping and show
$35 finally we're going to style the
last project in this lesson which is the
rock paper scissors project and this
will finish the project let's go back to
superimple dodev and we'll scroll down
on this page and then click this link to
show the final design for rock paper
scissors so I'll rearrange my windows so
we can see
this and we're going to change the
buttons to these nice big icons for each
of the moves and when we click a move it
will show the result in bold and show an
icon of the move that we picked and the
move that the computer picked so we're
going to make this project look really
nice now let's get started I'm going to
rearrange my windows back so we have it
at the bottom and let's create a cop
copy of the rock paper scissors project
for this lesson we'll go to our code
editor and click here to show our
files and we're going to make a copy of
09- Ro paper scissors so let's click
this file and then
rightclick
copy and down here right click and
paste and we'll rename this file by
right-clicking
rename and at the end we'll remove copy
and at the beginning we'll change it
from 9 to 10 and press
enter now let's click here to hide the
files and we can close the 09
file and let's open the 10 rock paper
scissors file in the browser so we'll
right click and then open with live
server and I'll move this tab to the top
here so we can see it side by side so
let's start by styling the body we want
to make the background color of the
entire page this dark gray color we'll
go into our code and let's create a
style element so we can write some
CSS inside the head let's type less than
Style
greater than and then inside here we're
going to style the body so we'll type
body and curly
brackets now inside here we're going to
change the background color so
background-color colon and we're going
to get the color that we see here by
right clicking click
inspect and then go to the elements tab
Tab and I'll rearrange it so we can see
it and then here we'll find the body
element and click it and in this style
section we can find the background color
that we need so let's select
this and
rightclick
copy and in
here right click and
paste and a semi colon at the end let's
save and I'll move this back to the
corner and now our project has the same
background color as the final design
next let's make the text color white so
in our CSS we'll use the color property
and colon white and semicolon and save
and that will make our text White
next let's change the style or the font
of this text we'll type font
dasam colon
aial which is what the final design uses
and
save all right now let's style these
elements one by one to match the final
design we'll start with this paragraph
at the top so inside the paragraph
element
let's add a class so we can style it in
CSS we'll add class
equals let's call this the
title and then in our CSS we can style
this class by starting with a DOT and
then
title and curly
brackets so let's make our title really
big like the final design we'll change
the font Das size colon 30 pixels and
save so that looks close enough next
let's make the text bold in our CSS
we'll use Font D weight colon bold and
save now let's move on to installing the
buttons so first we're going to need
these images in our project and I'll
show you how to get them we'll put our
Mouse over the rock image and we'll
rightclick and we'll click save
image and now we're going to find the
folder that contains all of our code so
for me it's on the
desktop and it's this folder right here
so I'll double click this folder and
then leave the file name as the default
rock- emoji and click save
and now in our code editor if we click
here we should be able to see the rock
image let's do the same with the paper
and scissors image so we'll hover over
it rightclick save
image and in the same folder that
contains our code we're going to save
the paper image and finally rightclick
save image and we'll save the scissors
image
all right now that we have these images
in our code editor let's learn how to
load them onto the page so we can do
this using an HTML element so we'll go
back to our HTML code and we'll scroll
down and inside the button we're going
to add an image element so let's type
less than IMG and greater than so this
is the image HTML element it loads an
image onto the page the image element
doesn't require a closing tag this is
called a void element now to load an
image we're going to add an attribute to
this element called
SRC so SRC stands for Source it tells a
computer which file or image to load so
let's look in our
project for this button we're going to
load rock- emoji.png
inside the source attribute we'll type
rock-
emoji.png
so what this does is it will look for
the file with this name beside the HTML
file and it finds it right here and it
will load it onto the page if we
save now inside our button it loaded the
rock
image right now this image is too big so
let's use CSS to decrease the size of
this image we'll hide the files and
let's give a class attribute to the
image element so we can style it so
we'll type class equals and let's call
this a move Das
icon and I'm also just going to add some
new lines to make the code a little
easier to read so we'll scroll up to the
CSS and we're going to style this class
using dot move Dash icon and curly
brackets and let's decrease the height
of this image we can use the property
height colon and a pixel value 50 pixels
and Save
so this will make the height of this
image 50 pixels and it will also resize
the width automatically so that the
image keeps its shape so this size looks
pretty close to the final design so we
can move
on another feature of the source
attribute is that we can put our files
into folders so let's open the files by
clicking
here and let's say that we want to
organize all of our images into a folder
so we're going to create a folder by
clicking this
icon and let's name this folder
images and we're going to drag these
images into this
folder and drag this in
here and in
here now unfortunately you can see that
the image doesn't load anymore and
that's because if we look at our code
Source tells a computer to look for this
file beside this HTML
file and right now there is no file
called rock- emoji.png because we put it
in a folder so to tell the computer to
look inside this folder we're going to
type the folder name at the start which
is
images and then we're going to type a
slash to go into the images folder and
then look for this file which is right
here if we
save the computer is now able to find
this image and load it onto the web page
so this feature is called file paaths we
can tell the computer to look for a
folder beside the HTML file like images
and then use a slash to tell it to go
into the folder and look for a file
now let's use this code to load the
other images onto our page so for the
paper image we're going to go to this
button remove the text and then create
an image element less than IMG greater
than and we'll give it an attribute
Source equals and we'll locate the image
it is in the images folder so we'll type
images and then slash to go into the
folder and we'll load the file paper-
emoji.png
so
paper-
emoji.png
and
save so our image is really big let's
give it the same class that we gave the
rock image so we'll add a class equals
move Dash icon and
save so these Styles get applied to all
elements with the class move- icon so it
applies to both of these
elements now let's do the same thing for
the scissors button we'll remove the
text and we'll replace it with an image
element and we'll give it the source
attribute images
slash
scissors Das
emoji.png
and we'll also give this a
class of
move- icon to resize the images like up
here let's
save and now we have all the images that
we
need now let's make these buttons look
like the final design we we scroll
up and let's add a class to these
buttons so we can style them with
CSS so we'll add class equals and let's
use
move-
button and for this button We'll add the
same class class equals
move-
Button as well as for the third
button class = move-
button now let's scroll up to our CSS
and we're going to style this class
using move- button and curly
brackets so first let's change the
background color to match the background
color of the page so we'll use
background Das color colon and we'll use
a special value called
transparent and this will make the
button see- through if we
save now these buttons are
see-through next let's add this white
border to our buttons so we'll use the
Border
property colon and we're going to give
it three values the first value is our
border width or how thick the border is
let's use one pixel for now the second
value is the Border style and we'll use
solid because it's a solid border other
values we can use here are dotted or
dashed and the third value is the Border
color so we're going to use
white and semicolon at the end and
save and that will add a border so let's
make our border a little thicker like
the final design we'll change this first
value which is the Border width to three
pixels and
save okay so that looks pretty close now
let's change the size of our buttons
usually we use the padding to add space
on the inside of an element but in this
case our images have different sizes so
we're going to use width and height to
set an exact size so so in our CSS we'll
type
WID colon and let's make it 100
pixels and
height and also 100 pixels and
save so it looks like our final design
is a little bigger than what we have
here so let's increase the width and the
height so let's try 120 pixels and Save
all right so that looks pretty close now
let's make these buttons round and the
property for that is called border Das
radius
colon and to know how much we need to
make it round we can set it to half of
the width or the height so we'll set it
to 60
pixels and
save okay so it's coming along really
well and lastly we're going to add some
space between the buttons so remember
that space outside of an element is
called margin so let's add some margin
on the right so we'll
type
margin
dasr colon and maybe 10 pixels and
save and finally when we put our Mouse
over the button it turns into a pointer
so the property for that is cursor colon
pointer and save and now our buttons
match the final design so let's keep
moving and style the next part of the
project which is the result and the
moves if you don't see this here you can
just play the game and it'll give us a
new
result so to make this easier to style
we're going to go into our code we're
going to find the result which is here
and we're going to add some fake results
like you
win let's save and now we have this
result and we're going to style it so
let's give this a class of
result and then in our
CSS we're going to style the class dot
result and curly brackets
so let's make the text bigger we're
going to use Font Das size colon and
maybe 25 pixels and
save okay that looks pretty good let's
make the text bold so we use Font Das
weight colon
bold and
save and finally we're going to add
extra spaces between this and the
buttons so we'll add
margin-top and maybe 50 pixels and
save okay so I think that looks close
enough now let's style the moves and
again we'll scroll
down and we're going to add some fake
moves in here so it's easier to style so
we'll Type U
and then an image so let's use the less
than image and the source
attribute and let's just load the rock
image and the scissors image for the
computer so to load the rock image we'll
look inside the images folder slash to
go into the folder and then rock-
emoji.png
so
rock- emoji
PNG and greater than and we'll add
another image less than image source
equals Images slash the scissors
Emoji scissors Das
emoji.png
and greater than and finally the text
computer
computer let's save
and this will create some results
although the images are really big so we
can use the class move icon to resize
them to be the same size as the buttons
so for both of these images let's add
the
class
move-
icon and here as well class equals
move- icon and Save
and now our images look
good next let's style this score section
so the only thing we need here is to add
spaces between these two so in this
score element let's add a class of
score and we'll scroll up and style this
element using DOT score
brackets and let's add some margin at
the top
so
margin-top colon 50 pixels and
save and let's compare it and it looks
like our final design has a little more
spacing than this so let's change this
to 60 pixels and
save and that looks close enough and
finally we'll style the reset score
button so let's go back to our HTM
ml we'll add a class to this button so
here class equals reset
dcore Das
button so at the top we'll type dot
reset
dcore
Dutton curly
brackets and we'll make the background
color white so background dasc color
colon
white and let's also remove the border
from our button using border colon
none let's save and see how it
looks and then let's increase the size
of this text because the final design
looks a little bigger so we'll add font
Das size colon 15 pixels and
save now let's add some extra space on
the inside of the button so that's
padding padding colon and we'll give it
two values the first value is the
vertical padding let's use 10
pixels and the second value is the
horizontal padding so let's use 15
pixels and Save
and it looks like our final project is a
little shorter than our button so let's
change the vertical padding to maybe
eight and save and the last step is to
add the cursor pointer so here cursor
colon
pointer and
save and that's pretty much it we
finished styling our rock paper scissors
project so now I'm going to rearrange my
windows so we can see the entire design
and it looks really nice the last step
here is to remove these fake results and
use JavaScript to insert these results
instead so let's scroll
down and we'll remove this
result and let's actually copy this code
because we want our JavaScript to
generate this code so we'll right click
and
copy and let's scroll to the
bottom to where we insert the moves onto
the page which is here and instead of
this text we're going to rightclick and
paste the code that we had before and
this time instead of picking Rock every
time we're going to substitute this with
the player move so we're remove this and
because this is already a template
string we can insert a value directly
inside using dollar and curly brackets
and we'll insert the
player
move let's also insert the computer's
move in here so we'll remove this and
insert a value using dollar and curly
brackets and we'll insert computer
move and now that we're inserting this
with JavaScript we can scroll up and
remove the fake
result which is here so we can select it
and delete
it now let's
save and we're not going to have
anything in our results and when we
click a move it will show us the result
and also show us the moves that we
picked and that's it we finished the
rock paper scissors
project the last thing we're going to
learn in this lesson is how to organize
our code into different
files so notice that right now all of
our HTML CSS and JavaScript is in one
HTML file and this makes the code harder
to read because the file is bigger and
it mixes three different languages to
make our code more organized and easier
to read we're going to separate each
language into its own file so let's
scroll down and we'll start by
separating our JavaScript into its own
file we'll click here to show our files
and then click this icon to create a new
file and we'll name this file
10-
rock-paper-
scissors. JS and press
enter so when we end a file
withjs it tells the computer that this
file contains JavaScript code not just
text now let's go back to our HTML
file and we're going to move all of this
code into the Javascript file so we'll
select this
code and then we'll
rightclick and
copy and inside the Javascript file
we'll rightclick and paste
now let's
save and we'll go back to the HTML file
and we can delete all this JavaScript
code and now we're just going to load
our Javascript file on to the web page
to do that we can use an attribute of
the script element called SRC or source
so we'll make it equal and this does the
same thing as the image element it tells
a computer which file to
load if we type
10-
rock-paper-scissors
DJs this will look for a file called 10
rockpaper scissors. JS beside our HTML
file which is this file here and it will
run all the JavaScript inside this file
so it does the same thing as before
except now our JavaScript code is in its
own
file and this makes our code cleaner
because each file only contains one
language and each file also contains
less
code now let's go back to the HTML file
and
save and you'll notice that our project
works the same way as before we just
organized our code
better another feature of The Source
attribute is that it also uses file
paths so we can put this Javascript file
in a folder and we'll be able to find it
for example let's show our files and
let's create a new folder by clicking
this
icon and let's name this folder
scripts so this folder will contain all
of our JS files so we can drag this file
into the
folder and now we can locate it using
the source attribute by typing the
folder name which is scripts and then a
slash to go inside this folder and look
for this file and it will find it right
here if we
save everything works as
normal another feature is we can use
multiple script elements this lets us
split our JavaScript into multiple files
and then load them all onto the page
from top to
bottom next we're going to learn how to
separate our CSS into its own
file let's scroll up to our
CSS so we can do the same thing with CSS
so let's click the HTML
file and let's create a new
folder and we'll call this folder Style
and press
enter so this folder will contain all of
our CSS code let's click the folder and
we'll create a new file by clicking this
icon and let's name this file
10-
ro-
paper-
scissors. CSS and press
enter so ending the file with CSS means
this file contains CSS code and now we
can go back to our
HTML and move our CSS into its own file
so let's select all this
code and then right
click
copy and in here right click and
paste and save this
file now let's go back to our HTML
and we can remove this
code and we'll learn how to load our CSS
file onto our
website so we're not going to use the
style element for this we're going to
use a different element called the link
element so we'll type less than link
greater than and the link element
doesn't require a closing tag this is
another void element so the link element
uses two attributes the first attribute
is called
R means relation this tells a computer
what type of file we're loading so we're
going to set this attribute to style
sheet this means we're loading a CSS
file and then we'll add a second
attribute called
href so href tells a computer which file
we want to load
so this also supports file paaths so we
can type the Styles
folder this will look for a folder
beside the HTML called Styles which is
this one right here and then we'll type
slash to go inside the folder and look
for this CSS file which is
10- Rock Das paper Das scissors
CSS so this will load all the CSS inside
this file and apply it to our page so it
does the same thing as before except we
separated each language into its own
file if we save everything still works
and all the Styles get applied and just
like the script element we can also use
multiple link elements to load multiple
CSS
files so that's how we separate our code
into separate files using the script
element and the link element it makes
our code a lot easier to read because
each file contains one language and it
contains less code and that's the end of
this lesson as a final reminder the CSS
we learned in this lesson is just a
review if you want to learn CSS in more
detail you can check out my HTML and CSS
full course in the video
description so in this lesson we
reviewed CSS and added CSS to all of our
projects we learned about the class list
property which lets us control the class
attribute of an element we finished our
rock paper scissors project and we
learned how to organize our JavaScript
and CSS code into separate
files thanks for watching this course so
far if you want to support this channel
you can check out the premium version of
my courses just like this one where you
can get a certificate of completion and
a Better Learning platform if you're
interested in extra videos from me more
in-depth videos and behindth scenes
content you can check out these links
here you can also support the channel by
liking the video subscribing and sharing
this video with others thanks again and
let's continue with the course
here are some exercises to help you
practice using HTML CSS and JavaScript
together
in this lesson we're going to learn two
more features of JavaScript called
arrays and loops and we're going to use
these features to create this to-do list
project first let's create a new file
for this lesson we'll go to our code
editor and click up here to show our
files and this time make sure you have
one of these HTML files selected so we
don't create the new file in one of
these
folders so now we're going to click this
icon to create a new
file and we're going to name this file
11- arrays Das and Das
loops.
HTML and press
enter now let's copy the previous lesson
into this file so we'll click on 10 Dom
projects and and we'll type here and typ
control a or command a to select the
code and then
rightclick
copy and in
here right click and
paste now let's hide our files and we'll
prepare this file for this lesson so we
can scroll to the
top and we'll change the title to arrays
and
loops and let's remove all of the
CSS and we'll also remove the
HTML which is right
here and we'll remove all the
JavaScript now let's
save and we'll open this file in the
browser by right clicking open with live
server and let's also open the console
so we right click click
inspect and click the
console and now we can close the
previous
tabs and the previous code for
now until we just have the lesson 11
file now we're ready to learn arrays an
array is another type of value in
JavaScript and it represents a list of
other values so let's do an example and
create our first array we'll go into the
script element and we're going to type
open square bracket and closed square
bracket and inside the square brackets
we'll type a value like the number 10
and then we'll type comma and and
another value like the number 20 and
then comma again and a third value like
the number
30 so this is an array and it represents
a list of three numbers 10 20 and
30 now arrays themselves are also values
which means we can save them in a
variable so at the front we can create a
variable using const
and let's name it my array and we'll
make it equal to this array and we'll
add a semicolon at the end so now we
created a list of values and we saved
this list in this
variable let's create a new line and
we'll
console.log my
array and Save
and it will display the list of values
in the console so that's basically what
an array is it's a list of
values now to get a specific value in an
array we can use square brackets so
let's create a new line and we'll type
my array and square
brackets inside these brackets we'll put
a number like
zero this number represents the position
in the array so zero means the first
value if we
console do log this
code and
save my array Square braet 0 gives us
the first value which is 10 and that's
what's displayed in the
console now if we change this to
one this will get us the second value in
the array which is 20 if we save it
displays 20 so this number represents
the position in the array zero is the
first value one is the second value two
is the third value and so on we can also
change a value in an array also using
square brackets so let's create a new
line and we'll type my array
square brackets and let's say we want to
change the first value so we'll type
zero for the first value and we just
make it equal to something else like
99 now if we
console.log my array
again and
save you can see that this changed the
first value to 99
so that's basically how arrays work we
can access a value inside an array and
we can also change a value inside an
array now that we understand the basics
of arrays let's learn the syntax rules
to create an array we start with an open
square bracket and we end with a closed
square bracket inside we can put a list
of values and we separate each value
with a comma
we can also write an array on multiple
lines like this we just put the new
lines after the
comma Now to get a value inside an array
we can use square brackets and a number
like one this number is called the index
it represents the position in the array
that we want to get so the first value
is index zero the second value is index
one 1 third value is index 2 and so on
notice that the index starts at zero
this is called a zero indexed
array now inside an array we can put any
type of value for example let's create a
new line and we'll create a new array
using square brackets and inside we can
put the number one and then comma and we
can also put a string like
hello and another comma and we can put a
Boolean value like true and another
comma and we can even put an object like
Curly
brackets Name
colon
socks now an array itself is also a
value that means we can save arrays in
very variables like this or even save it
in an array for example in this array we
can add an array inside like 1 comma
2 next arrays have a weird behavior when
we try to check the type of an array so
on a new line let's type
console.log type of and then square
brackets one comma
2 and
save this will tell us that an array is
an object and that's because an array is
actually an object but it's just a
special type of object if we want to
check if something is specifically an
array we can use this code capital A
array dot is
array
brackets and inside the brackets we'll
put an array like square brackets 1
comma 2 so this will check if this value
is an array if we
console. log this
result and
save it will display
true and finally because arrays are are
just a type of object they also have
properties and methods we can use so one
useful property is called length so
we'll type
console.log my
array.
length this will tell us how many values
are in the array so my array has three
values so if we save
it will display
three next we'll learn a useful method
of an array called push this adds a
value to the end of the
array if we did my
array.
push
100 this will add 100 to the end of my
array if we console.log
my
array and
save you can see that 100 was added at
the
end the last method we're going to learn
for now is called do splice this removes
a value from an array for example my
array do
splice and
brackets and a splice takes two numbers
the first number is the index that we
want to remove so let's say we want to
remove the first value which is index
zero the second number we give to splice
is the number of values we want to
remove if we give it one it will remove
one value at index zero if we give it
two it will remove two values starting
at index zero so for now let's just
remove one value
and let's create a new line and
console.log my
array and
save you can see that splice removed the
first value from the array or index0
which was
99 all right now that we understand the
basics of arrays and the syntax rules
let's do some practical examples so
prepared a project we can do for this
lesson we'll go to our browser create a
new tab at the
top and here we'll type
superimple
dodev SL projects slash arrays and press
enter so this page contains the to-do
list project we're going to create in
this lesson so down here is the final
version of the project we can type a
name for our to-do like make
dinner give it a due date and then click
add and it will add it to our list we
can add another to-do like wash
dishes and then select a due date and
click add again and it will add another
to-do to our list and each to-do also
has a delete button so we can delete it
when we're finished the task so this is
the final version of the project and
these two up here are simpler versions
of the project that we're going to use
to work our way up so let's start with
the first project up here we're going to
open our console by
right-clicking click
inspect and click the
console and the way way this first
project works is we can type a to-do in
this text box like make
dinner and when we click add it will add
the to-do to an array and display it in
the
console if we type another to-do like
wash dishes and click add it will add it
to the array and display it in the
console so let's create create this
project we'll start by creating a file
for this project we'll go to our code
editor and click up here to show our
files and click this icon to create a
file and we'll name this
11-
too-
list.
HTML and press
enter now let's copy the code from
arrays and loops. HTML
so we'll click here control a or command
a and then
rightclick
copy and down here right click and
paste and let's close this for
now we'll scroll up and change the title
to to do list and remove all the
JavaScript code
and this time instead of writing all the
JavaScript in here let's actually put
the JavaScript in a separate file which
we learned in the previous lesson so
we'll open our files
again and this time we'll go to our
scripts folder we'll click this JS file
and we'll click this icon to add a new
file to this folder and let's name it
11- to-do Das
list.js and press
enter next we're going to load this file
into our HTML file so let's open this
and in the script element we can remove
the spaces and we're going to add an
attribute called
SRC equals and we're going to load the
Javascript file that we just created
which is inside the script folder so
we'll type
scripts and then a slash to go into this
folder and we'll load the file
11-
too-
list.js and
save so now I'm going to drag this file
down here so I can see both the HTML and
JavaScript at the same time close this
for now and I can close the other code
for now as
well and finally let's open this in our
browser so we'll right
click open with live
server and let's also open the console
on this page right click click
inspect and click the
console now one more thing I'm going to
do for this video is I'll rearrange my
windows so that we can have the the
final design at the
bottom let's start by creating the HTML
elements let's go to the body and we'll
actually create a paragraph element to
start inside the paragraph we'll put the
text to-do
list next let's create the text box so
to create a text box less than
input greater than and add a placeholder
to this text box Place holder equals to
do name finally let's add this
button so on a new line let's type less
than button greater than and inside the
button we'll have the text
add now let's
save and this creates all the HTML
elements that we need
next let's write our JavaScript so first
we're going to create an array to store
our to-dos and then when we click the
add button we're going to get the text
from the text box and add it to our
array and finally we'll console.log the
array now let's convert these steps into
code let's create a new array first
using const
let's name it
to-do list and we'll make it equal to
square
brackets so this is an array with no
values inside we also call this an empty
array next when we click the button
let's get the value from the text box so
let's go to our button and add an
onclick
attribute and then inside here let's
create a function for this so down here
let's create a
function we'll name it add Todo brackets
and curly
brackets and then inside the onclick
attribute we're just going to call this
function add too and
brackets the next step is to get the
text in the text box we can do that
using document. query selector so to use
Query selector we're going to put a
class on this input element so we'll
type the class
attribute
js- name Das
input and then in here document do query
selector brackets and a string and we'll
type a DOT to get a class and we'll get
this class
js-
name-
input as a reminder this gets an element
with the class JS name input which is
this element and puts it into our
JavaScript and now let's save this in a
variable so at the start let's type
const in input element and make it equal
to this
result so now we took this input and put
it into our
JavaScript to get the text out we're
going to use a property of the input
element called value so down here
input
element.
value and let's save the value in the
text box in a variable so we can use it
later
at the front const name and we'll make
it equal to whatever's in the text
box before we continue let's
console.log the name to check if this is
working so let's save this Javascript
file and let's also save this HTML
file we'll go to our browser and I'll
resize it so we can you can see the
console and now if we type something in
the text box like make dinner and click
add it will get the text from the text
box and then display it in the
console okay so it's looking good so far
the next step is to add this name to our
to-do list so we learned how to do this
earlier we can use a method called push
push will add a value to the end of the
array so let's remove this for now and
at the
bottom we're going to type our
array to do
list. push
brackets and then between the brackets
we're going to add our name
here and now the last step is to
console.log the entire array
console.log Todo
list and
save now let's give it a try or'll type
make dinner in the text box and click
add it will take this text add it to the
array and then console.log the array and
now we have our to-do list let's add
another to-do we'll type type wash
dishes and click
add again it will get the text in the
text box and then add it to the array so
now our array has two values and then we
display them in the
console so that's how we create this
first version of the to-do list project
now one more feature we're going to
create is if we add something to our
to-do list and click add
it will reset the text box to do that
let's go into our
code and we'll create some new lines and
remember that the value property
represents the text in the text box so
to change the text in the text box we
can simply change the value property so
we'll type
input
element. value and change it to the
empty string
so this will make the text in the text
box become empty if we
save and now type something in the text
box and click
add it will reset the text in the text
box let's move on to the second version
of the to-do list so here when we type
something in the text box like make
dinner and click add it will actually
display it on the page if we type
something else like wash dishes and
click add it will also add it to the
page so how do we take our array and
display each value on the page to do
this we're going to learn another
feature of JavaScript called loops loops
let us run some code over and over like
a loop so let's go back to our 11 arrays
and Loops file and we can close this
JavaScript file for now and we're going
to learn Loops so first let's comment
out the previous code by typing
slashstar and at the bottom star
slash let's scroll
down and we'll create our first Loop
we'll start by creating a variable using
the word let and we'll name name this
variable I and we'll make it equal to
1 next we're going to type the word
while and then brackets and curly
brackets and then inside these curly
brackets we're going to put some code
that the computer will run over and over
just like a loop let's put the code
console.
log
I so this will display the variable I in
the console over and over again now
obviously we don't want to Loop this
forever so how do we get this Loop to
stop we can do that using the round
brackets up here inside these round
brackets we're going to put some code
that results in true or false for
example we can check if I is less than
or equal to 5 so the way this works is
that if this code results in true the
loop will keep going over and over once
this results in false the loop will stop
and it will go to the next line now you
may notice that this code will never
result in false because I is equal to 1
and 1 is always less than or equal to 5
so when does this actually become false
and Stop the Loop the answer is inside
this loop we're also going to update
this variable I so we'll type I and
we'll make it equal to itself plus
1 so now every time we Loop over this
code we're going to increase I by 1 and
eventually I will be greater than 5 this
will return false and it will stop the
loop if we
save and then go back back to the tab
for this file and I'll rearrange my
windows so we can see the console this
Loop makes the computer count from 1 to
5 so let's go over this code step by
step to make sure we understand how it
works first we create a variable I and
we make it equal to one and then we do a
loop so if this condition is true the
computer will keep running this code
over and over again so the first time it
Loops I equals 1 and then it displays
one in the console and then we increase
I to two now we go back to the top and
we check this code 2 is less than or
equal to 5 this is true so we're going
to run this code again this time I equal
2 and we display it in the console and
then we we increase I to three and now 3
is still less than or equal to 5 so this
is true which means we keep running this
code and eventually this is going to
increase I to six once I is six this
will become false which will cause the
loop to stop and then we go to the next
line so that's why it counts from 1 to 5
and then it stops at five
so this is called a while loop while
this condition is true it will keep
running this code over and over again
just like a loop as soon as this
condition is false it will stop the
loop all right now that we understand
how a while loop Works let's learn the
syntax rules to create a while loop we
type the word while and then round
brackets and curly brackets the code
inside the round brackets is called the
loop condition the code inside the curly
brackets is called the loop body the
variable I at the top is called the loop
variable every time we loop we're going
to increase the loop variable this is
known as the increment step the
increment step makes sure that the loop
ends at some point without this
increment step the loop would just keep
going forever this is known as an
infinite
Loop now remember that I = I + 1 has a
shortcut instead of this we can just do
I plus = 1 and remember we actually have
an even shorter shortcut for plus equal
1 instead of this we can also do I ++
so this will increase the value of I by
one every time just like before so those
are the three major parts of a loop the
loop variable the loop condition and the
increment
step now each time we run this Loop this
is called an
iteration so in this Loop we did five
iterations we ran this code five times
and lastly Loops create a scope any
variable that we create between these
curly brackets will only exist inside
the curly brackets so that's a while
loop while this condition is true it
will keep running this code over and
over again once this condition becomes
false it will stop the loop and go to
the next
line so in JavaScript there's actually
two types of loops
the first type is a while loop which we
just learned now we're going to learn
another type of loop called a for Loop
to create a for Loop we'll create some
new lines and then down here we'll type
four and brackets and curly
brackets inside these brackets we're
going to type three pieces of code the
first piece of code is a loop variable
which is the same thing as this line up
here so we'll type let I equal one and
then semicolon space and we'll type a
second piece of code which is the loop
condition so here we'll type I less than
equal to 5 and then semicolon and space
and the last piece of code is the
increment step which is this line right
here so we'll type
i++ and between these curly brackets
we'll write the code that we want to
Loop over and over so let's just type
the code
console.log I and
save so this for Loop does the same
thing as the while loop above it counts
from 1 to 5 and if we look at this code
we can see that a for Loop is just a
shorter version of this while loop
instead of writing the loop variable
condition and increment step separately
we group all of them together at the top
so this Loop works the same way first we
create a loop variable and then as long
as this Loop condition is true we will
keep running this code over and over and
every time we run this code we're also
going to increase the loop variable by
one so now that we learned two ways of
doing a loop which one should we use if
we're doing a standard Loop for example
it has a loop variable a condition and
an increment step every time it's
recommended to use a for Loop because a
for Loop is shorter and more organized
than a while loop however if it's a
nonstandard loop then it might be better
to use a while loop so what's an example
of a non-standard loop so let's say we
want to Generate random numbers until we
get a number that's at least
0.5 to create this Loop we'll create a
variable that will store the random
number using
let
random
number and make it equal to zero to
start and then we'll do a while
loop brackets and curly brackets now
inside the loop condition we want to
keep running this Loop until random
number is at least
0.5 so we'll check if
random number is less than
0.5 because if it is less than 0.5 we
want to keep running this Loop until we
get a random number that's at least
0.5 and then inside this loop we're
going to generate a random number
between 0 and 1 and then save it in the
variable up here so we'll type random
number and make it equal to capital M
math.
random so if this random number is less
than 0.5 it will keep generating random
numbers until we get a number that is at
least
0.5 so at the bottom if we
console. log
random
[Music]
number and
save it will give us a random number
that's at least
0.5 so notice that this is a
non-standard loop it doesn't really have
a loop variable that we increase every
time and it also doesn't have the
increment step so in this situation when
we have a non-standard loop it's better
to use a while loop because they're a
bit more
flexible all right now that we learned
the basics of Loops let's do some
practical examples we're going to learn
a technique called looping through an
array this means we're going to go
through each value of an array one by
one and do something with each each
value so first let's comment out the
previous code using
slashstar and star slash at the bottom
let's create an array of strings so
we'll create a variable const to do list
equal to an
array and inside this array we'll have
the string make
dinner another string wash
dishes and another
string watch
YouTube now let's take each value in
this array and display it in the console
to do that we're going to run a loop and
this Loop is going to count from zero to
the last index in the array so remember
that the index is the position of a
value in the array the first value is
index zero the second value is index one
third value is index 2 and so on So
Below this let's type four brackets and
curly
brackets inside these brackets we're
going to create the loop variable so
here we're going to count the
indexes let index equals zero semicolon
space and we'll do the loop condition so
we'll keep looping as long as the index
is less than or equal to the last index
so remember that the index starts from
zero this means that the last index in
an array will be the number of values in
the array minus one or the array. length
minus
one to do list do
length minus
1 and here we'll add another semicolon
and we'll add the increment step which
is index Plus+ so we'll increase it by
one every time now inside these curly
brackets we can do something for each
index of this array for now let's just
console. log this index
and
save so this will count from 0 to two
which is exactly all the indexes in this
array and now using this index we can
also access the value at this
index so instead of just the index here
we can do to-do list and then square
brackets and between the brackets index
this will take whatever the index
variable is and access that index in the
array so if the index variable is zero
this will access to-do list index0 which
is the first value when the index is one
it will access to-do list index one
which is the second value and so
on so for now let's save the value in a
variable using const value
and make it equal to to-do list bracket
index and now let's
console.log the value instead if we
save this will Loop through each index
of the array get the value at each index
and then display each value which is
what we see in the console so this
technique is called looping through an
array we use a loop to go through each
value of an array and then we can do
something with each
value now I'm going to show you a few
shortcuts we can use when looping
through an array instead of checking if
index is less than or equal to to-do
list. length minus one we can shorten
this to index less than to-do list.
length so this check does the same thing
as before the loop Loop will stop at
index equal length minus one but it
saves us some
typing another shortcut is instead of
naming the loop variable index we can
shorten this to
I and we'll shorten this as well and
this as well and that's why we often
name the loop variable I I means
index next we're going to learn a
technique that we can combine with
looping through an array called the
accumulator pattern so first let's
comment out the previous code using
slashstar and star
slash and at the
bottom let's say we have an array of
numbers like this how do we calculate
the total of all the numbers in the
array let's set up this problem let's
say we have an array of numbers const
nums equals array and then the numbers 1
1 and
3 and we want to calculate the total of
all the numbers in this array to
calculate the total we'll learn the
accumulator pattern the first step of
the accumulator pattern is to create a
variable to store the result so below
this let's create a variable const total
and we'll make it equal to zero and the
next step is to Loop through this array
and update the result so down here four
brackets and curly brackets and inside
the round brackets we'll create the loop
variable let I or index equals z
semicolon space and we'll create the
loop condition I less than nums do
length and then semicolon and the
increment step
i++ so as we learned earlier this Loop
will go through each index of this array
and now between these curly
brackets first let's use the index to
get each value so we'll type
nums and then square brackets and access
the index I and let's save this in a
variable using
const num equals this
value and finally we're going to add
each number to the total we can type
total and make it equal to
itself plus each number and remember
remember we have a shortcut for this
which is plus
equals and finally since we're changing
this total variable we have to change
from const to
let all right so after this Loop we
should have added each number in the
array to the total so at the bottom
let's
console. log the
total and Save
and it will display five which is the
exact total of all the numbers in this
array so that's the accumulator pattern
we first create a variable to store the
result and then we Loop through the
array and update the result so notice
that as we Loop through the array we're
adding or accumulating the results into
this variable and that's why this is
called the accumulator pattern pattern
and we call this variable the
accumulator
variable all right let's do another
example using the accumulator pattern
let's say we're given this array of
numbers again and we want to create a
copy of the array where each number is
doubled so if the array is 1 13 we're
going to create a new array with 2
26 so as at the bottom we'll create some
new lines and use the accumulator
pattern the first step is to create a
variable to store the result let's type
const and let's name this
nums
doubled and we'll make it equal to an
array this time so notice in the
previous example the accumulator
variable was a number in this example
the accumulator variable is an array so
we can use different types of values to
accumulate the result it all depends on
the problem we're trying to solve so now
the next step is to Loop through this
array and update the result at the
bottom we'll create a four Loop brackets
and curly
brackets inside the round brackets we'll
create the loop variable let I equal
zero and we'll create the loop condition
I less than nums do length and then the
increment step
i++ and now between the curly brackets
we're going to get the number at each
index so const num equals nums square
bracket I and then we're going to update
the result
so down here we're going to add this
number doubled to this
array so remember to add a value to an
array we can use the method push so
we'll type
nums
doubled do push
brackets and we're going to add to this
array the number num multiplied by 2 and
now at the bottom
let's
console. log the result nums
doubled and
save so this second Loop will create an
array where each number is doubled so
that's how we solve this
example all right now that we understand
how to Loop through an array and the
accumulator pattern let's go
back and we'll create the second version
of our to-do list so when we add
something to the list it will appear on
the page let's go to our code editor and
we'll open 11 Todo list.
HTML and we're also going to open the
Javascript file so it's this one and for
the video I'm going to drag it to the
bottom of my code editor so that I can
see the files side by side so I'll close
this for now
and I'll rearrange my windows a
bit let's open the tab for this project
so we'll review what we have so far we
can click in this text box and type a
to-do like make dinner and click add and
it will add this to-do to this array
which is this array right here we can
type another to-do like wash dishes and
click add and it will add it to the end
of the array so now that we have this
array of to-dos we want to display it on
the page to do that we're going to Loop
through this array and we're going to
create some HTML code for each to-do and
then put that code on the web page using
the Dom so first let's Loop through this
array to make this easier let's make a
copy of this array so right click
copy and then here we'll remove this and
rightclick and
paste so this will give us some default
values to work with so at the top let's
Loop through this array using a for Loop
so we'll type four brackets and curly
brackets and then in inside the round
brackets we're going to create the loop
variable let I or index equal zero
semicolon and the loop condition I less
than too list do
length semicolon and then the increment
step
i++ so this will Loop through each index
of this array and then inside the curly
brackets let's get the string for each
index so we'll create a variable to save
it const to-do and we'll make it equal
to to-do list square brackets and
I and now for each to-do we're going to
create some HTML code so we'll create a
new line and create a variable const
HTML and make it equal and we'll create
some HTML code using this to-do using a
template
string and then inside we'll create a
paragraph element so less than P greater
than and then less than SL P greater
than inside this paragraph we're going
to insert this to-do so we'll type
dollar and curly brackets and
Todo all right so now we're looping
through this array and for each to-do we
created some HTML code and now we're
going to combine all of this HTML code
together and put it on the web page to
combine this HTML together we're going
to use the accumulator pattern so at the
top of the loop we'll create a variable
to store the result let to do list
Capital
HTML and we'll make it equal to the
empty string at the start and then as we
Loop through the array we're going to
add this HTML to the variable up here so
let's create a new line and we'll do
to-do list Capital
HTML plus equals
HTML to combine all of this HTML code
together so now after the loop let's
console do log to do list
HTML to see what we get if we
save we took this array of strings
generated paragraph elements for each
string and then combine them all
together so now that we have all this
HTML we can put it on the page using the
Dom so first let's create an element
where we can put this
HTML so inside the HTML file after the
button we're going to create a different
type of element called a div element so
we'll type less than div greater
than so the div element represents a
container its purpose is to contain
other elements inside like paragraphs
buttons and even other
divs so in this situation we can't
actually use a paragraph element because
in HTML we cannot have a paragraph
inside another paragraph so that's why
we have to use a div element here for
now let's put some text inside this
element so we can learn more about it
we'll type text and Save
so like the paragraph element the div
element is a block element that means it
will take up an entire line by itself
and that's why it appears below the text
box and the button now one difference
between a div and a paragraph is that a
paragraph adds extra space above and
below the paragraph while a div does not
add any extra space above or below so it
doesn't have any default
styling all right so now that we learned
the div let's put this HTML code inside
this div first we need to get this
element into our JavaScript and to do
that we'll add a class to this element
class equals
js- too Das
list and then down here let's scroll
down and we'll put this div element
inside our JavaScript we can do that
using document do query
selector brackets and a string and we'll
type a DOT to select a class and we'll
select the class
js-
too-
list so this will get this div element
and put it in inside our
JavaScript and then every HTML element
has a property called dot inner Capital
HTML which controls the HTML inside this
element and now to put the to-do list
HTML into this div element we're going
to make the inner
HTML equal to the
to-do list HTML
and now let's save this
file and also save the HTML
file so this code will take the HTML
that we created using the loop and put
it into the div element and that's how
we make them show up on the page so now
let's try adding another to-do we'll
type watch YouTube and click
add and unfortunately
this new Todo doesn't show up on the
page and that's because when we click
add it will run this add Todo function
and update the list but we didn't
actually update the HTML on the
page so to update the HTML we need to
run all this code again every time we
add a too so let's create a function for
this code so we can reuse it so at the
top we'll create a
function and let's name this
render
to-do list brackets and curly
brackets so the word render means to
display something on the page so we'll
put all of this code into this function
so we can delete this curly bracket and
then at the end we'll type a closed
curly bracket and let's reformat this
code by selecting these lines and then
press tab to add an
indent so now let's use this function at
the start we'll display this to-do list
on the page so we'll call this function
by typing render
to-do list and
brackets and then let's scroll down
every time we add a to-do to the list
we're also going to display the list
again so at the bottom
render to do list and brackets again so
if we
save at the start it will display the
list on the page and then if we add it
to the list like watch YouTube and click
add it will add it to the list and also
display it on the page so that's how we
create the second version of the to-do
list
project by the way if we scroll up to
the render Todo list function this
technique is called generating the
HTML instead of writing all the HTML by
hand up here we looped through an array
and we generated the HTML using
JavaScript
so when creating websites with
JavaScript we usually follow a
three-step process first we save the
data in this case we saved our data as
an
array next we use the data to generate
the HTML which we did here and finally
we make the website interactive which
we'll do later in this
lesson this is the main idea of
JavaScript and we follow follow this
overall process when creating
websites the rock paper scissors project
from the previous lessons was a bit
different because all the HTML we needed
was already there we just had to modify
it with
JavaScript so this process we're using
for the to-do list is one step above
what we did for rock paper scissors we
need to generate some
HTML and this is a standard process for
creating websites we're going to use
this process for the to-do list and
later the Amazon Project as well as
websites that you build Beyond this
course let's take a break before
continuing with the rest of this lesson
here are some exercises that will help
you practice what we learned so far
now let's create the final version of
the to-do list we'll go back to
superimple
dodev and then here we'll scroll down
and we'll create this final version so
in this version we can type a too like
make
dinner and we can also add a due
date and when we click add each to-do
will now have a name and a due date and
they will also have a delete button that
we can click to remove it from the list
so let's build this out one feature at a
time we'll start by creating this delete
button we'll go into our code and
remember we're generating the HTML
for the to-do list so for each value in
the array we create a paragraph element
so to add a delete button we just have
to add a delete button inside here so
inside the paragraph we'll create a less
than button greater than and then less
than SLB button greater than and then
inside this button we'll put the text
delete
let's
save and in the console you'll see that
the HTML we generated now has a delete
button inside the paragraph and that's
what shows up on the
page next we're going to reformat this
HTML to make it a little easier to read
so we'll create some new lines here and
at the
end and let's put the content of the
paragraph on its own line like this
and also put the delete button on its
own line so remember that template
strings have a feature called multi-line
strings so this is perfect for writing
HTML
code the last step in the process is to
make the website
interactive so next let's make our
delete button do something when we click
it to do that we use the onclick
attribute as usual so inside this button
we're going to add an
onclick attribute equals double quotes
and then inside these double quotes we
can run some JavaScript when we click
this button so this works the exact same
way as what we've been doing so far in
this course the only difference now is
that here we're generating this HTML
using
JavaScript okay so when we click one of
these delete buttons we want to remove
this to-do from the list earlier in this
lesson we learned how to remove a value
from an array using a method called
splice so inside this onclick attribute
we're going to type the to-do list dot
splice and
brackets so splice takes two numbers the
first number is the index that we want
to remove
so if we click this delete button how do
we know which index to
remove well if we look at our Loop up
here we already have the index it's this
variable I so we're going to insert I
into this string and we can do that by
typing dollar curly brackets and
I now splice also takes another number
so we'll type comma and the second
number is how many values we want to
remove so here we just want to remove
one value at this
index and finally because we updated the
to-do list we need to display the list
again on the page to display the list we
can use this function render to do list
so down here we're going to type render
Todo list and brackets
now if we
save you can see that in the generated
HTML when we click the first delete
button it will remove the value at
index0 which is the first value if we
click the second button it will remove
the value at index one which is the
second value so we're basically
generating all this HTML using a loop so
now if we click this delete button
it will remove it from the list and then
display the updated list on the page so
that's how we create the delete
button next let's go back to superimple
dodev and we're going to create the due
date
feature so first let's create this date
selector in our
HTML we'll go to our HTML file and then
under the text box we're going to add
another input element
so less than input greater than and to
make it a date selector input elements
have an attribute called
type so this attribute determines what
kind of input it is if the type is text
which is the default value it's going to
be a
textbox now if we change the type to
date and
save it's going to create a date
selector now let's go back into our
JavaScript code and first we're going to
scroll up and remember that right now
our to-do list is just an array of
strings but this time each to-do is also
going to have a due date so how do we
group the name and the due date together
we can do that using an object so here
instead of just a string we're going to
create an an object and we'll give it a
name property which is make dinner and
we'll give it a due date property and
we'll make the due date a
string so you can type whatever date you
have on the page for me it's 20
22-12
d22 and I'll end this object with a
curly bracket and I'll turn this to do
into an object as well so open curly
bracket
name and do
date
2022
D12
d22 and closed curly
bracket now that each to-do is an object
we need to update the rest of our code
let's scroll down and we'll start with
the render function
so here inside the loop each to-do is no
longer just a string it's an object so
let's change this variable name to to-do
object to make it more clear and now we
need to get the name and due date out of
this object so we'll type const name
equals to do object. name and const do
date equals to do
object. do
date and now instead of inserting to-do
which no longer exists we're going to
insert the
name and we're also going to insert the
DU
date if we
save now each to-do will also display a
due
date before before we continue we're
going to review a shortcut we can use
with objects called
destructuring so here you'll notice the
variable name is the same as the
property name we actually have a
shortcut for this using
const curly brackets
name equals Todo
object so this is called destructuring
this takes the name property out of the
object and and puts it in a variable
also called name and this is a shortcut
for this line up here so we can comment
out this line we can also use multiple
properties in this shortcut to also take
the due date out of the object we can
just add a comma and do
date so this will do the same thing as
this line of code and we can comment
this
out if we save
everything still
works next let's scroll down and we're
going to update our add Todo function so
this time when we click the add button
we're going to get the name and the due
date and put it into our list so let's
get the due date out of this date
selector first we can do that using the
Dom like we did here so let's add a
class attribute so we can get it using
queries selector
js- do
dd-
input and then down here let's create a
variable
const date input element and make it
equal to
document. query
selector and a string Dot and then the
class we want to select which which is
this class
js-
do-
date-
input so this will get the date selector
element and put it into our
JavaScript and now below this let's get
the due date out of the
element we can do that using the value
property again so let's create a
variable first const do date and we'll
make it equal to the date input
element.
value so this will get the date that we
selected and save it in this
variable and now when we add a to-do to
our list instead of just a name we're
going to add an object so open curly
bracket We'll add a name property and
the value will be the name variable up
here so name and then comma and a doe
date
property and the value will be this due
date variable up here so due date and
then a closed curly
bracket and remember that objects also
have a shortcut for this if the property
and the variable name are the same we
can just type it out once like
this this will do the same thing as this
line above same thing with the second
line if the property and the variable
name are the same we can just type a
comma and type it out
once this is called the shorthand
property syntax so these two lines do
the same thing as these lines above so
we can comment this out using double
slash and double
slash so that's all the code that we
needed to update now let's save our
Javascript
file and we'll also save our HTML
file and let's go to our project We'll
add a new to-do like watch
YouTube and select a
date and click
add and scroll down you can see that it
added our new to-do with a name due date
and a delete button
if we click this delete button it will
remove that to-do if we click this one
it will also remove the correct
to-do and that's actually all the
functionality that we need for this
project so let's go into our code and
we're going to clean up by removing the
console.log
here and the console.log up
here and Save
finally let's add CSS to our project to
make it look like the final design we'll
go into our code editor and scroll to
the top and instead of writing all the
CSS in here let's put the CSS in a
separate file just like our JavaScript
so we'll click here to show our
files and then find the Styles folder
and we'll click the Styles folder and
click this icon to create a new file
inside and we'll name this file
11-
[Music]
to-do-list
docss and press
enter and for the video I'm going to
take this CSS file and put it at the
bottom of my code editor so I can see
these files side by side and now I'll
click here to close
it and will load this CSS into our
HTML to do that we can use a link
element so inside the head section let's
type less than link greater than and
we're going to give it two attributes
Rel equals style
sheet and
hre equals the file that we want to load
so we created this this in the Styles
folder so we'll type Styles and then a
slash to go into the folder and we load
this file
11-
too- list.
CSS and
save now let's style our project one by
one until it matches the final design
we'll start with the text on the page
we're going to change the font so in
here let's type
body curly brackets and then we'll
change the font Das family colon Arial
and
save so that looks pretty good now let's
work on styling the to-do list first
let's add some more to-dos to the list
so we'll type
watch
YouTube and then we'll select a date
and click
add and we're going to learn how to
style our list to look like this so
notice that this list creates a sort of
grid we're going to create this grid
using a feature called CSS grid so let's
go into our HTML
first we're going to add a class to this
div element so we can style
it to-do Das grid R and let's
save and inside our CSS we're going to
style this class using dot Todo Das grid
and curly
brackets and to turn this into a grid
we're going to use the property
display and
grid and we're going to add another
property called grid Das template Dash
columns so this basically sets how many
columns are in our grid the number of
values that we give it is the number of
columns for example if we give it 200
pixels 150 pixels and 100
pixels this will create three columns in
the grid the First Column will be 200
pixels the second Colum column will be
150 pixels and the third column will be
100
pixels and now each element inside this
div will go into the columns so the
first element will go in the First
Column second element will go in the
second column and the third element will
go in the third column if we have more
than three elements it will wrap around
and create a new
row so let's
save and and unfortunately that didn't
quite work and that's because if we go
back to our
JavaScript remember that each to-do is
one paragraph element so this entire
to-do with the name due date and delete
button will go inside the First Column
and then the next entire to-do will go
inside the second column but what we
actually want is for the name to go in
column 1 due date column 2
and delete button column 3 to do this
we're going to separate this element
into three elements so that each element
will go into each
column so instead of one
paragraph let's actually use a div
element so less than div greater than
and less than slash div greater than and
in between we'll insert the name
so the reason we use a div element is
because div elements don't have any
default styling so it's a little easier
to style with
CSS for the due date let's also create a
div element so less than
div and then at the end less than slash
div greater than and finally for the
delete button we already have an element
so so let's just reformat these lines
we'll select these lines and then press
shift tab to remove the
indent let's remove the extra line and
we basically separated each to-do into
three
elements if we
save now the grid is working because
this element goes into the First Column
this element goes into the second column
and the button goes into the third
column
and that's how we lay out these elements
in a grid like the final design next
let's also lay out the inputs and the
add button in a grid we'll go to our
HTML and let's put these three elements
in a div so we can use grid so we'll
create a less than div greater
than and then
inside let's remove this and we'll add
it at the end less than SL div and let's
reformat these lines by selecting them
and then press tab to add an
indent and now let's make this div a
grid as well let's go back to our CSS
and we'll add a class to this div class
equals let's call it to-do Das input d
dgrid and instead of writing all this
CSS again we can use a feature of CSS so
here we're going to type a comma and
enter so when we type a comma we can
style multiple classes at the same time
so we're also going to style dot
too- input Das grid if we save the CSS
file
and let's also save the HTML
file now the input and the add button
are also laid out in the same
grid next let's adjust the spacing
inside our grid so grid has some
properties for this we'll go to our CSS
press enter and we'll use the property
column Das Gap so this sets the spacing
between the Columns of the grid so let's
make this colon 10 pixels and
save so now it will add 10 pixels
between each column let's add some
spacing between the rows as well and
grid has another property for this row
Das Gap colon 10 pixels and
save so that will add 10 pixels of space
between the rows now notice it didn't
add space between these two rows and
that's because these two are separate
grids this is the to-do list and this is
the to-do input
grid so to add space between them we
just going to use
margin at the bottom we'll style dot
too- input Das
grid and we'll just add some margin
under this grid so margin Das bottom
colon 10 pixels and
save all right now let's move on to
styling the inputs and the buttons we'll
start with the inputs first let's add a
class so we can style them here let's
add a class name Das
input and down here let's let's also add
another class
do- dat Das
input let's
save and now inside our CSS we'll style
both of these
inputs so we'll style do
name- input curly brackets and first
let's make the text bigger like the
final design we'll set the font Das size
colon 15 pixels and save okay so that
looks pretty good now let's add spacing
on the inside of this input so we'll add
padding six pixels and
save and that looks pretty good let's
move on to the due date input so we
actually want the same Styles as the
name input so again we can use that
feature of CSS we'll type a comma and
then dot
do-
date- input so now these Styles will be
applied to this class and to this class
let's
save and that looks pretty good to me
let's move on and style the
buttons we'll go into our HTML and find
the add button let's add a class so we
can style
it and we'll use add-
too- button let's
save and then inside our CSS we'll style
that class using dot add-
too- button curly
brackets and let's start with the
background color we'll set the
background-color
colon
green and
save now let's do the text
color color colon
white and
save now let's remove the border around
our button using border colon
none
save and let's make the text a little
bigger so we'll do font
D size colon 15
pixels and
save and the last thing we'll add is
when we put our Mouse over the button it
turns into this pointer icon we can do
that using
cursor colon
pointer and
save next let's style the delete buttons
so these delete buttons are created in
our JavaScript we'll go into our
JavaScript
file and then here let's add a class to
each of the delete buttons so we can
style them so we'll add class equals
double quotes and then delete Das
too-
button let's
save and then inside our
CSS at the bottom we style dot delete
Das too Das button curly
brackets and let's start with the
background color so we'll set background
Das color colon and for this design I
use the color dark
red and
save so that will style our delete
buttons now let's change change the text
color to white so we'll use color colon
white and
save now let's remove the Border using
border colon
none
save and let's also make the text bigger
using font Das size colon 15
pixels save
let's add this pointer icon using cursor
colon
pointer save and let's add some padding
at the top and bottom of the button so
we'll add
padding-top colon 10 pixels and padding
Dash bottom colon 10 pixels and Save
so that's all the Styles we need for the
delete button and we can also close the
console to see the entire list however
now we have another problem which is
this text and this button are not
vertically aligned in the center to
vertically align in the center we're
going to go back to the grid Styles so
we'll scroll
up to the to-do
grid and CSS grid has another property
for vertical alignment and that is align
Das items Colon
Center to vertically align in the center
if we
save now the text is aligned with the
button but now we have a new problem our
add button is no longer stretching to be
the same as the inputs so by default
align items is
stretch that's why this button stretches
to match the inputs and now that we
changed it to align center it's no
longer going to stretch so to solve this
problem we just have to make this grid
stretch so down here in the to-do input
grid Styles we'll change align Das items
back to
stretch and Save
save and that will cause this Grid at
the top to stretch vertically again and
that's it that's all the styling that we
need and now we finished this to-do list
project in the rest of this lesson we're
going to learn more details about arrays
and
Loops so I'm going to put this back in
the same
window and I'll rearrange this
window and now let's go back to 11
arrays and loops.
HTML and we'll open the tab for that
file and we can also close these other
files for
now and first let's comment out the
previous code
using
slashstar and at the bottom star
slash and we'll scroll down and
save the first detail we're going to
learn is that that arrays are references
so in the object lesson we learned that
objects are references arrays work the
same way so for example if we create an
array
const array 1 equals the array 1 2
3 this variable doesn't actually contain
the values 1 2 3 this array is saved
somewhere in the computer's memory and
this variable only contains a reference
that points to where this array is in
memory and that means if we create a
copy of this variable
const array 2 equals array
1 array 2 doesn't contain a copy of the
values it actually just contains a copy
of the reference so now both of these
variables are pointing to the same array
so if we did array
2. push
for and then we
console.log array 1 and we
console.log array
two and
save it will show us that even though we
added four to array two array 1 and two
were both modified and that's because
arrays are references so both of these
point to the same array in memory to
avoid this Behavior we can create a copy
of the values in the array using a
method called slice so here if we did
array
1. slice instead
this will make a copy of the values in
Array one and now these two variables
point to two different arrays if we
save now you'll see that this line only
affected array
two the second detail we're going to
learn is a shortcut called
destructuring so at the bottom here
let's create a new array
const array 3 3 equals the array 1 2
3 and let's say we want to get the first
value and the second value out of this
array one way to do this is to use the
index like this another way is to use a
shortcut called
destructuring so here we're going to
replace this with square brackets and
now we can type some variable name
if we type first value it will take the
first value and save it in a variable
called first value if we type comma and
second value it will take the second
value and save it in this variable so
this is an easier way to get values out
of an array and save them inside a
variable next we're going to learn more
details about loops so Loops have two
features called break and continue break
lets us exit a loop early for example
let's create some new lines and let's
create a loop that counts from 1 to 10
so as usual we can use a four
Loop let I =
1 I less than or equal to 10
and I
++ and we'll
console. log I and
save so this will count from 1 to
10 so now let's say that when I is 8 we
want to stop this Loop early so first
let's check if I is equal to 8
if it is equal to 8 we're going to stop
this Loop by typing break and
semicolon if we
save once this reaches eight break will
cause this Loop to stop and now it only
counts up to eight so that's the break
feature of a loop it lets us stop a loop
early the next feature is called
continue continue lets us skip one
iteration of the loop or one run of the
loop for example let's say we want to
skip the number three so at the top we
can check if I is equal to
three and if it is we can use the code
continue this will skip the rest of this
code and go back up to the top of the
loop and do i = 4 if we
save this will skip three in the loop so
continue let us Skip One iteration of
the loop so now let's say that we want
to skip a number if it's divisible by
three divisible by three means the
number can be divided evenly into three
for example 3 and six are both divisible
by three but s is not divisible by three
because there's one remaining this is
called the remainder and we can
calculate the remainder using the
remainder operator which looks like this
so to check if a number is divisible by
three we can check if the remainder is
zero so here we're going to replace this
with I remainder 3 and we'll check if
the remainder is equal to to Z if we
save this will skip three and six
because they're both divisible by
three next let's use continue in a while
loop so at the end here we'll create
some new lines and let's say we want to
count from 1 to 10 using a while loop so
we'll create a loop variable let I equal
1 and we'll create a while
loop I less than or equal to 10 curly
brackets and the increment step
i++ and inside the loop we just
console. log I and
save so this will count from 1 to 10
again and let's say we want to not count
numbers that are divisible by three so 3
6 and 9 so at the top here we can check
if I remainder 3 is equal to zero and
curly brackets and we might just try to
do
continue however in a while loop
continue will actually skip the
increment step and this will cause an
infinite Loop Loop so when using
continue in a while loop we have to do
this increment step manually so before
continue we have to do I
++ to avoid an infinite Loop if we
save it will skip the numbers that are
divisible by three which is 3 6 and 9 so
remember in a while loop if we use
continue always do the increment step
manually in a for Loop however the
increment step is done automatically
after every
iteration all right the last detail
we're going to learn is how to use loops
with functions so let's say we have an
array of numbers and we want to create a
copy of this array where each number is
doubled so we already have the code for
this we can scroll up and the code for
this is here
so let's actually make a copy of this
code from before we'll
rightclick
copy and scroll down
here and at the
bottom right click and
paste at the top let's create an array
called
nums so const nums equals array and one
1 and
three if we
save this will create an array where
each number is
doubled now what if we wanted to use
this loop on a different array other
than one one and three we can do that
using a function so let's create a
function around this Loop we'll create
function let's name it dou full
array brackets and curly bracket we'll
remove the closed curly bracket and at
the bottom We'll add it back and we'll
select these
lines and press
tab so now instead of doing this loop on
the same array every time we can turn
this into a parameter so at the top here
we'll create a parameter called
nums and we're going to delete this
line and we're going to Loop over this
parameter instead so at the bottom we
can call our function using double array
and
brackets and between the brackets we're
going to save an array into nums so
square bracket 1 1 and 3 if we
save this will do the same thing as
before but now because it's in a
function we can use this loop with any
array not just one one and three so at
the end we can do double array
brackets and an array 2 2 five this time
and
save and it will create an array where
these numbers are doubled so using a
function we can reuse this Loop for any
value another feature of using a
function with a loop is that we can
break out of this Loop using a return
instead so first let's actually use a
return in this function instead of
console.log we're going to
return nums doubled
and here we're going to console.log the
result
console.log and
console.log and
save so this does the same thing as
before except we're returning the result
and console. logging outside of the
function now let's say that if we see
the number zero we want to stop this
Loop early to do that we can click here
and check if num is equal to
zero and if it is we can break out of
this Loop now when we're inside a
function we can also use a return
statement to break out of this Loop so
we can also do return nums
doubled so a return statement will end
this function immediately so this is
another way of ending the
loop so down here if we add the number
zero and then five and
save you'll notice that the loop stops
when we see the number zero so return is
another way of breaking out of a loop
when it's inside a function and that's
the end of this lesson in this lesson we
learned about arrays which represent a
list of values we learned about loops
which let us run some code over and over
just like a loop we learned a Technique
we can use with loops called the
accumulator pattern and we used it to
create a to-do list project we learned
that arrays are references and the
destructuring shortcut and we learned
more features of Loops like break
continue and using Loops inside a
function here are some exercises to help
you practice arrays and loops
in this lesson we're going to learn some
Advanced features of functions and we're
going to use them to improve our
previous
projects first let's create a new file
for this lesson we'll go to our code
editor and click here to show our files
and click here to create a new file and
we'll name this
12- Advanced D
functions.
HTML and press
enter now let's copy 11 arrays and Loops
into this file so we'll click here
control a or command a and then
rightclick
copy and in
here right click and paste
and we can close this for now and let's
prepare this file for this lesson so
we'll scroll
up and change the title to
Advanced
functions and let's remove all the
JavaScript code from
before and now let's save and open this
file in the browser by right click
clicking open with live
server and let's also open the console
on this page so we'll
rightclick
inspect and open the
console and now we can close the
previous
tabs as well as the previous
files and now we're ready to begin so
first we're going to review how to use
fun
functions inside the script element
let's create a function using the word
function will give it a name
greeting brackets and curly brackets and
inside the function we'll type the code
console.log the string
hello so this is a function and it lets
us reuse code to run the code inside
this function we can type the function
name which is greeing and then
brackets if we
save this line of code we'll run the
code inside the function and display
hello this is known as calling the
function or running the
function so now that we understand
functions we're going to learn an
advanced feature of functions which is
functions are values so we learned many
types of values in this course like
numbers strings and booleans and we can
save a value in a variable for example
let's create some new lines and we'll
create a variable const num equal
2 so this will save the value two inside
the variable num
now functions are also values and this
means just like a number we can save a
function inside a variable so let's give
it a try we'll create a new line and
type
const function one and we'll make this
equal to a function this time so we'll
just type
function and a name
greeting brackets and curly
brackets and inside the function we'll
type
console. log the string hello
2 and we'll put a semicolon at the end
since we're saving in a
variable so this variable now contains a
function we're using the exact same
syntax as before except we're just
taking this function and saving it in a
variable because functions are values
so now that this function is inside this
variable let's actually console.log it
so we
console.log function one and
save and this will show us that the
variable function one actually contains
this
function now on a new line we can also
do console.log
and check the type of function one and
save and it will tell us that the type
of this variable is a function so as you
can see a function is just another type
of value and we can save it in a
variable we can also run the function
inside this
variable by typing the variable name
function 1 and because this contains a
function we can actually just call it
using
brackets so this will run the code
inside this function if we save it
displays hello
to now let's do some Cleanup in this
code in JavaScript as long as there's a
way to access a function this function
name is not needed so here we can access
this function using this variable so
this function name is not needed and we
can actually just delete it like this
and now this is called an anonymous
function which means a function without
a
name now an interesting thing to know is
that the function syntax that we've been
using this entire course up here is
actually a shortcut for this code now
even though this syntax uses VAR and we
usually don't recommend VAR this syntax
actually has a couple advantages number
one it's easier to read and number two
it gives us a feature called hoisting
which means we can call this function
greeting brackets before we create it in
the code so using hoisting we don't have
to worry about what order we write this
code hoisting doesn't work when we
create our function and save it in a
variable like this so in JavaScript
functions are values and just like any
other value we can save it in a
variable now let's think what else can
we do with a value well we can save a
value in an object for example let's
scroll
down and create some new lines and we'll
create an object
const object 1 equals curly
brackets and inside this object we'll
have a property num with the value
two so this saves the number two inside
this object now because functions are
values we can also save a function
inside this object so we'll type comma
and then a property fun colon and we'll
create a function this time function
[Music]
greeting brackets and curly brackets and
inside we type
console. log the string hello
3 so this saves a function inside this
object under the property fun now to
access this function we just use the dot
notation as normal so object one dot
fun and because this value is a function
we can call it using
brackets if we
save this will run the code inside the
function and display hello 3 so remember
this is called a method when we have a
function saved inside an
object again as long as there's a way to
access this function for example using
object one. fun then we don't need this
function name so we'll delete it and use
an anonymous
function now let's think what else can
we do with a value we can pass a value
into a function for example down here
let's create a function
function
display brackets and curly brackets and
we'll give this function a parameter so
in here we'll create a parameter and
name it
param and inside the function we can use
a parameter just like a variable so we
console.log the
param and then down here let's call this
function using
display brackets and two
this will take the value two save it
inside Pam and then we can use it just
like a variable if we
save this will display two in the
console so this is known as passing a
value into a function now because
functions are values we can also pass a
function into a function so let's give
it a try down here
we'll create a new function
function run brackets and curly
brackets and this function will also
have a parameter let's call it
param and down here we'll call this
function run
brackets and between the brackets we're
going to give it a function this time so
we'll type function
brackets and curly brackets and inside
the function we'll type
console.log the string hello
4 so this will take this function and
save it inside Pam and now up here we
can use Pam just like a variable so we
can type
Pam and because Pam contains a function
we can actually just call it using
brackets if we
save this code will run the function
that we created down here and display
hello 4 so this is called passing a
function into another
function the function that we're passing
in is called a callback function or a
callback so to summarize functions are
values anything we can do with a value
we can also do with a
function now let's do some practical
examples using functions as values we're
going to learn a feature of JavaScript
called set timeout set timeout allows us
to run a function in the
future first we'll comment out the
previous code using
slashstar and at the bottom
star slash and let's create some new
lines and we're going to type the code
set capital T time
out so set timeout is a built-in
function so we can type brackets to call
this function Now set timeout takes two
parameters inside these brackets the
first parameter is a function that we
want to run in the future
let's create a
function brackets and curly brackets and
inside this function let's type
console.log the string time
out so here we're using a function as a
value and we're passing it into another
function at the end we'll type a comma
and we'll give set timeout a second
parameter the second parameter is how
long to wait before running this
function so this is a number in
milliseconds 1,000 milliseconds is equal
to 1 second so if we type 3,000
milliseconds this is equal to 3 seconds
so set timeout will wait for 3 seconds
and then call this function if we
save after 3 seconds
it's going to display timeout in the
console so that's set timeout we give it
a function and it will call this
function after a certain amount of
time so now we're going to learn an
important concept called a synchronous
code so after set timeout let's type
console.log the string next
line and Save
so notice that it displays next line
first and then after 3 seconds it
displays timeout so what's happening
here why are they reversed set timeout
sets up a timer and after 3 seconds it
will call this function however it
doesn't actually wait for the 3 seconds
to finish it just sets up the timer and
immediately goes to the next line so
that's why this line is displayed first
so this is called asynchronous code
asynchronous code means the computer
won't wait for this line to finish
before going on to the next line so for
set timeout it'll just set up the timer
and then immediately go to the next line
synchronous code on the other hand means
the computer will wait for one line to
finish before going to the next line so
all the code we've written in this
course so far has been synchronous code
in addition all the code inside this
function is also synchronous code so if
we added
console.log the string time out
to and
save the code inside the function will
still run line by line it will wait for
each line to finish before going to the
next line and after 3 seconds it will
display timeout followed by timeout
2 so don't worry all the code that we
normally write will be synchronous code
it will run line by line as usual the
only time that code becomes asynchronous
is when we use certain features of
JavaScript like set timeout so set
timeout is the only part that is
asynchronous now the advantage of set
timeout being asynchronous is that it
does doesn't block our code for 3
seconds waiting for this timer to finish
it just sets up the timer in the
background and then goes to the next
line of code so this allows our code to
do other things while this timer is
running in the background and this is
similar to real life if you set up a
timer on your alarm clock you're not
going to stop and wait for the timer to
finish you're going to go and do
something else asynchronous code is the
exact same concept
next we're going to learn a similar
function to set timeout called set
interval so at the bottom let's type the
code set capital I
interval and set interval is another
built-in function so we can call it
using
brackets and set interval takes these
same two parameters as set timeout the
first parameter is a function that we
want to run in the future so let's type
function brackets and curly brackets and
inside we'll type
console. log the string
interval now let's add a comma and the
second parameter is also a number in
milliseconds so we'll type 3,000
milliseconds or 3 seconds so set
interval will run this function 3
seconds in the future but this time it
will keep running the function every 3
seconds if we
save in the console every 3 seconds it
will run the function and display
interval so set interval is also
asynchronous below it if we type
console.log the string next
line
two and
save it will set up the interval and
then immediately go to the next line and
display next line two so that's set
interval we give it a function and it
will keep running this function after a
certain period of time so now let's do a
project using what we learned so far
let's go to our browser and we'll create
a new tab at the top
top and here let's type
superimple
dodev slash projects slash Advanced Das
functions and press
enter so this is basically the rock
paper scissors game that we created
earlier except this time it has an extra
button called autop playay if we click
this Buton
button every second the computer will
play by
itself so this feature will help us
practice using set
interval so first let's make a copy of
the project files we'll go into our code
editor and click this icon to show our
files and let's make a copy of 10 rock
paper scissors for this lesson so we'll
rightclick copy
and down here rightclick and
paste and I'll stop this for now so here
we're going to change the name by right
clicking
rename we'll remove copy at the end and
at the beginning we'll change it to 12
and press
enter and let's also make a copy of the
JavaScript and CSS files so we'll click
this file and right click
copy and then click the folder right
click
paste and we'll rename this file
rightclick
rename remove copy at the end and at the
beginning change it to 12 and press
enter and let's also make a copy of the
CSS file select it rightclick copy
click the folder right click and
paste and right click
rename remove copy and at the front
change it to 12 and press
enter now let's scroll down to 12 rock
paper
scissors and I'll close this for
now and inside the head let's change
this to load 12 rock paper scissors and
we'll scroll to the
bottom and here instead of the lesson 10
file we'll load The Lesson 12 Javascript
file let's save and we'll open this in
the browser by
right-clicking open with live
server so now we're ready to begin let's
go back to superimple
dodev and the first thing thing we're
going to create is this autoplay button
so beside the reset score button which
is here we're going to create a new
button less than button greater than and
inside we'll have the text auto
play let's
save and go back to our
Tab and now we have this button so next
let's style this button with CSS so
we'll give it a
class class equals
auto-play Das
button and
save and now let's open the CSS
file I'm going to take this file and
then drag it to the bottom so I can see
it side by side so I'll close this for
now and rearrange this a little bit and
then down here and we're going to style
the autop playay button so let's just
make the style the same as the reset
score button so in the CSS we'll scroll
down to the reset score button Styles so
we'll add a comma at the end and type
dot
auto-play dasb button so now these
Styles will apply to the class reset
score button and the auto playay button
if if we
save now we styled our project so next
let's make this button interactive so at
the top here we'll add an onclick
attribute and then in here we're going
to run some JavaScript code let's
actually create a function so we can
separate the JavaScript into its own
file so we'll run a function called auto
play and
brackets so now let's
save and right now this function doesn't
exist so we have to create this function
in the Javascript file so for me the
file is right here I'll select it and
then drag it down here so I can see it
side by side so let's scroll down and
I'm going to create it just above the
play game function so here we'll create
some new lines and type function
auto play brackets and curly
brackets and now inside this function we
want to play the game every second so we
can use set interval to run some code
every second so let's type set
interval
brackets and inside the brackets will
give it a function that we want to run
so brackets and curly
brackets and then at the end let's type
a comma and we'll give it
1,000 so this means it will run this
function every 1,000 milliseconds or 1
second and now inside this function
we're going to automatically play the
game and to play the game we can use
this function right here play game so
here we'll type play game
brackets now we need to provide this
function with a Player move and remember
we have another function pick computer
move which will give us a random move so
above this line let's create a variable
const
Player move and we'll make it equal and
we'll pick a random move using pick
computer move
and
brackets and finally we'll take this
move that we picked and pass it into
this function so Player
move so now when we click this button it
should play the game every second let's
save and click
autoplay and it works the computer is
playing against itself every second so
now let's make this button button stop
playing when we click it again so at the
top let's create a variable to keep
track of whether or not we're playing so
we use let is auto playing and at the
start we'll make it equal to
false and
save and now inside this function we'll
check using an if statement brackets and
curly
brackets and inside this condition let's
check if we're not playing so not is
auto
playing so if we're not playing then we
want to start playing the game which is
this code down here so let's select this
code and then right click
cut and in here right click and
paste and also after we start playing
the game we're going to change this
variable to true so is auto playing and
we'll make it equal to true because now
we are autop playing so now let's add
the else Branch to this
statement else curly
brackets so now we need to stop this
interval so how do we do that the answer
is that set interval actually returns a
number and this number is like an ID we
can use this ID to stop the interval so
at the front let's create a variable to
save this ID
const
interval ID and
equals however there's another problem
here every time we run the function
we're going to get a different ID so in
order to save the ID from last time we
need to put this variable outside the
function so let's select this and remove
it for now and we'll scroll up and here
we'll create the variable let
interval ID and we'll leave it undefined
to start and now down here we're going
to save the return value into this
variable by typing
interval ID equals set
interval and now at the bottom we're
going to use the interval ID to stop the
interval let's scroll down and to stop
an interval we can use a function called
clear interval so we'll type clear
capital I interval
and
brackets and between the brackets we're
going to give it an ID that we want to
stop so we'll give it this interval
ID
interval
ID and then at the bottom let's also
change is autop playing to false because
we just stopped it so is auto playing
equals false
and
save so now if we try out this
button it will start playing the game by
itself every second and if we click the
button again it will stop playing the
game so that's how we stop an interval
we need to save the ID and then call
clear interval with this ID so now I'll
clean up the code a little by removing
this extra line and Save
and now we're finished with this
feature so next let's go back to our
Advanced functions file so I'll click up
here and then at the bottom I'll open 12
Advanced
functions and hide the files for now and
we're going to learn some more features
of functions as values so let's actually
close the other files that we opened
and first let's comment out the previous
code with
slashstar and at the bottom star
slash let's scroll down and
save and let's open the tab for this
file so now we're going to learn another
way to Loop through an array first let's
create an array we'll type square
brackets and inside the array we'll have
the string make
dinner and another string wash
dishes and another
string watch
YouTube so in the previous lesson we
learned how to Loop through an array
using a for Loop or a while loop another
way to Loop through an array is using a
method of the array called four each so
at the bottom let's type dot for capital
E each and
brackets so this is the four each method
and it allows us to Loop through this
array inside these brackets we're going
to give for each a function so we'll
type
function brackets and curly brackets so
again we're just passing a function into
another
function however this function will be a
little different we're going to give it
a parameter so up here let's create a
parameter called
value so what four each does is that it
Loops through the array and for each of
these values it will save the value in
the parameter and run the function so
let's
console.log
value and
save so this will Loop through the array
and display each value in the console so
let's go through this step bystep so
it'll take the first value save it in
this parameter and run the function then
it will take the second value save it in
the parameter and run the function then
it will take the Third value save it in
the parameter and run the
function so the for each method is
actually the preferred way to Loop
through an array because this is easier
to read than a for Loop like this and
for each also has another feature we can
give this function a second parameter so
we can type comma and the second
parameter is the
index or the position of the value in
the array so for the first value index
will be zero for the second value index
will be one third value index will be
two and so on so above this line let's
also
console.log the
index and
save and this will also display the
index of each
value all right now let's do a practical
example using the for each method we're
going to go back to the to-do list
project that we created in the previous
lesson so we'll click up here to show
our
files and let's scroll up and let's open
11 too
list.js so in this code we used a for
Loop to display the to-do list on the
page we're going to switch this to using
a for each method instead said so first
let's actually make a copy of the files
for this project we'll click up
here and let's click 11 to-do list and
rightclick
copy and let's click the script
folder rightclick and
paste and now we'll rename this by
right-clicking
rename remove copy from the end and
change the beginning to 12 and press
enter let's also make a copy of the CSS
and HTML file for this project so we'll
click the CSS file right click
copy click the Styles folder right click
and
paste rightclick
rename remove copy
and at the front change it to 12 and
press
enter and finally we'll scroll down
click 11 Todo list.
HTML
rightclick
copy and then down here right click and
paste right click
rename remove copy at the end and at the
beginning change it to 12 and and press
enter now we can hide these
files and we can close the lesson 11
files and now here we're going to change
the CSS file that we load to 12 to-do
list and we'll scroll down and we'll
also change the Javascript file that we
load to 12 to-do list now let's
save and we'll open this in the browser
by right clicking
open with live
server okay now let's go back to the JS
file so I'll take this file and drag it
to the
bottom and I'll rearrange the windows
here we're going to scroll down and
we'll change this for Loop to use a for
each method so first let's type above
this for Loop and we'll type the array
that we want to Loop through which is
Todo list and we'll type Dot and use the
four each method and
brackets inside the brackets we'll give
it a function that we want to run for
each to do so we'll type
function brackets and curly
brackets and this function can have two
parameters the first parameter will
contain each value in the array so we'll
call it too
[Music]
object we'll type a comma and the second
parameter contains each index in the
array so we'll just call it
index and now inside this Loop we
basically want to do everything that we
did here so let's just make a copy of
this
code right click
copy and then up here inside for each
right click and and
paste so now if we scroll up we already
have the to-do object up here so we
don't need to get it from the array like
before so we can remove this line and
let's also remove these
comments the other thing we have to
change is that previously we were using
I for the index but now the index is
called index so we just change this to
to
index so that's how we use a for each
method instead of a for Loop if we
compare this code to the four Loop that
we had before the for each method is
easier to read so for the rest of this
course we're going to prefer to use four
each instead of a for Loop so we're
going to remove this for
Loop let's scroll back up and
save and the project still works so
that's a practical example of using the
for each method now let's go back and
learn some more details about for each
we'll close the Javascript file for now
and go back to Advanced functions. HTML
and open the tab for this
file so in the previous lesson we
learned a feature of Loops called
continue continue lets us skip to the
next iteration or the next run of the
loop for each methods don't have
continue but we can do the same thing
with a return statement so let's say in
this Loop we don't like washing dishes
if the value is wash dishes we're going
to skip it and not display it in the
console so above we'll create an if
statement
and then inside the condition we'll
check if value is equal to the string
wash
dishes and then in the curly brackets if
it is equal will return and
semicolon so this return statement will
end this function early and it will go
on to the next function so it basically
does the same thing as continue in a for
Loop if we
save you'll notice that it skipped wash
dishes in the previous lesson we also
learned a feature of Loops called break
break lets us exit a loop early
unfortunately there's not an easy way to
break in a 4 each Loop so if we need to
use break to exit this Loop early then
it's better to use a regular for
Loop let's take a break before
continuing with the rest of this lesson
here are some exercises that will help
you practice what we learned so far
so next we're going to move on and learn
a shorter way to write functions called
Arrow functions so let's go to the
bottom of this code we'll create some
new lines and let's create a variable
const and we'll name the variable Arrow
function and we'll make it equal to to
brackets equal greater than or an arrow
and then curly
brackets inside the curly brackets we'll
type some code
console.log brackets and the string
hello and we'll put a semicolon at the
end so this is an arrow function it
works the same way as a regular function
for example we can call this Arrow
function by typing the variable name
Arrow
function and
brackets if we
save this line of code will run the code
inside this Arrow function and display
hello so Arrow functions mostly work the
same way as regular functions so to
compare them let's actually type above
this code we'll create some new lines
and type
const
regular
function equals the word
function brackets and curly brackets
console.log string
hello so these two syntaxes do the same
thing the difference is that instead of
using the word function an arrow
function just uses an
arrow now parameters work the same way
in an arrow function we just type the
parameter between these round brackets
so here let's type
param and here as
well if we want multiple parameters it
also works the same way up here we can
type comma param 2 and down here comma
Pam 2 and finally return statements also
work the same way so in this function we
can return five and in the arrow
function we can also return
five so now let's learn some differences
between these two Arrow functions have a
few shortcuts that regular functions
don't have for example at the bottom
let's create an arrow function using
const and we'll name it one
perm and make it equal to an arrow
function brackets arrow and curly
brackets now in this Arrow function
we're going to give it one parameter
param and inside the function will
console.log param plus
one so when an arrow function only has
one parameter these round brackets are
optional so we can actually remove
them if we do one param brackets 2 if we
save it will display 2 + 1 which is
3 let's learn another shortcut we'll
create some new lines and type const one
line and make it equal to an arrow
function brackets arrow and curly
brackets and inside will return 2 +
3 so when an arrow function only has one
line like this we can actually put it on
the same line as the
arrow and now that everything's on the
same line the curly brackets are
actually optional so we can remove them
and we can also remove the return
statement so this is a oneline arrow
function if we just have an arrow it
will automatically return the result on
the right so at the bottom we can
console. log and call the one line
function with
brackets if we
save this function will return to plus
three and it will display five in the
console so that's Arrow functions it's a
shorter way of writing a regular
function and it has a few
shortcuts for now let's get some
practice using Arrow functions so let's
scroll up in this code to the for each
method so let's use an arrow function
here instead we just have to remove the
word
function and after the round brackets
add an arrow equals greater than if we
save the loop still works so when we're
passing a function into another function
like for each it's recommended to use
Arrow functions because it makes our
code easier to read so now let's use use
Arrow functions in some of our previous
projects we'll start with the rock paper
scissors game let's open our files by
clicking
here and we'll find the 12 rock paper
scissors. JS
file and then inside this file we're
going to scroll down to the autoplay
function so here we're passing a
function into another function so it's
recommended to use an arrow
function let's remove the word
function and add an arrow so now this
code is a little easier to read now what
about this function up here function
autoplay should we also switch this to
an arrow function so this situation is
more personal preference so above this
let's actually create an arrow function
version of this const
auto play equals brackets and arrow and
curly
brackets so even though we could create
an arrow function version of this I
actually prefer the regular function
syntax here for two reasons number one I
think this is easier to read than this
and number two this function syntax
enables hoisting which means we can call
this function before we create it and we
don't have to worry about which order we
write the code so for these reasons I
actually prefer this situation to use a
regular function syntax and not an arrow
function so we'll comment out the arrow
function using double
slash and double
slash now let's
save and let's open the tab for this
project and we'll give give it a try so
click
autoplay and this still works after
replacing with an arrow
function next let's go to the to-do list
project and switch to Arrow functions so
we'll go to our code editor and find the
to-do list project which is
here and let's scroll
down so inside render to-do list we're
using four each and we're passing this
function into another function so it's
recommended to use an arrow function
here so we'll remove the word
function and after the brackets We'll
add an
arrow and again I'll leave this function
syntax as a regular function because
it's easier to read and enables hoisting
so let's
save and go back to our to-do list
and everything still
works next let's go back to 12 Advanced
functions.
HTML and we'll scroll to the
bottom and we'll open the tab for this
file and we'll review another place we
could use Arrow functions which is
inside an object so at the bottom here
let's create a new object con
object 2 equals
object and then inside let's type the
property method colon and an arrow
function brackets arrow and curly
brackets so even though we could save an
arrow function inside an object like
this objects already have a shortcut for
functions so at the bottom we could just
type
method brackets and curly
brackets so this syntax is called the
shorthand method syntax so this
shorthand method syntax is actually
easier to read than an arrow function so
when saving a function in an object it's
actually recommended to use this syntax
instead there's also another difference
between regular functions and arrow
functions but we'll learn about it later
in in this course because it's a more
advanced
feature now let's move on and we're
going to learn another Improvement we
can make to our projects so let's
comment out this code we'll scroll up
and type SL star and at the
bottom star slash and
save and next we're actually going to
scroll up to the very top of this file
and we're going to create a button on
the page so inside the body we'll type
less than button greater than and inside
the button we'll have the text
click now let's say that we want to run
some JavaScript code when we click this
button so here we can type on click
equals double quotes and write some
JavaScript inside this double quotes
quot now we're going to learn a better
way of doing this called add event
listener to use add event listener first
we're going to get this button and put
it into our JavaScript using document.
query selector so let's add a class to
this button so we can select it and
we'll set it to
js-
button and now inside the script element
we're going to use
document. query
selector brackets and the string do
js-
button so now let's save this button in
a variable so we can use it later at the
front we'll type
const button element equals this
result now every HT H ml element has a
method called add event listener add
event listener let us run some code when
we interact with the element so it sort
of does the same thing as
onclick so at the bottom let's type
button
element dot add capital E Event capital
L
listener and brackets
so add event listener has two parameters
the first parameter is the event or what
type of interaction we want to listen
for so between these brackets let's type
the string
click so this will run some code when we
click the button the way to find these
event names is to look at this attribute
the word after on is the
event next the second parameter is a
function that we want to run when we
click this element so we'll type a comma
and because we're passing a function
into another function we're going to use
an arrow function so we'll type
brackets arrow and curly
brackets so inside here let's just do
console. log string click
and
save and now when we click this button
it will run this function and display
click so this code does the same thing
as the onclick attribute however add
event listener has some advantages over
using an attribute first it lets us add
multiple event listeners for an event
for example let's add another click
event listener we can select this
code and
rightclick
copy and then down
here rightclick and
paste and let's change this to log click
to if we
save and click the
button it will run both these functions
so add event listener let us add
multiple listeners to one event another
advantage of doing this is that we can
remove an event listener using a method
called remove event
listener so under this code we can type
button
element do remove capital E Event
capital L listener and
brackets and remove EV listener also has
two
parameters the first parameter is the
event so in this case it is the string
click and we'll type a comma and the
second parameter is the function that we
want to remove so that when we click
this button it will no longer run that
function now we can't just type a copy
of this function we need to use this
exact function inside remove event
listener to do that we'll save this in a
variable first so above this let's
create a
variable
const event
listener equals and we'll select this
code right click
copy and in here right click and
paste and now we'll replace this with
the VAR
variable event
listener and down here we'll remove this
same
variable event
listener if we
save and click the button again it will
only display click two because we added
this event listener and then we removed
it so it will no longer run this
function when we click the button so as
you can see
add event listener gives us more control
over event listeners we can add multiple
listeners to an event and we can also
remove a listener from an event so
because of these advantages the best
practice is to use add event listener
instead of an onclick attribute so let's
go back into our projects and switch to
using add event listener we'll start
with the rock paper scissors project so
we'll open our
files and we'll open 12 rock paper
scissors and click here and
save and we'll scroll up to 12 rockpaper
scissors. JS and for the video I'll drag
this down to the bottom and I'll hide
the files for
now and then rearrange the
windows and finally open the tab for
this file
now let's go to the HTML we'll scroll up
to these move buttons which is up
here so here we're using the onclick
attribute and we're going to switch it
to add event listener so first let's get
this button into our
JavaScript We'll add a class so we can
select it
js-
rock- button
and
save and then down
here let's go below the autoplay
function right here and we'll use add
event listener so we'll get this button
into our JavaScript using
document do query
selector brackets and a string dot
js-
ro-
button and we're going to use dot add
event
listener
brackets so we're going to listen for a
click and a comma and we'll give it a
function that we want to run so a common
mistake here is to actually run the
function for example play game brackets
and the string
Rock so we're supposed to give a
function to add event listener however
this doesn't result in a function this
will actually run play game and give us
the return value which is undefined so
this code will actually result in
undefined and then we're giving
undefined to add event listener so it
won't
work so in order to give add event
listener a function we need to create a
function here
so let's remove this code and we'll
create a function using brackets arrow
and curly
brackets and then inside this function
we're going to call play game so we'll
type play game brackets and
rock so now when we click the rock
button it will run this function and
play the game so let's remove the
onclick
attribute and save the
HTML and also save the
JavaScript and then go to our project
and click the rock button you can see
that it works except this time we're
using add event listener so let's do the
same thing for the paper and the
scissors button feel free to pause the
video if you want to try it
yourself so we'll scroll down here and
let's add a class to the paper button so
we can select it
js-
paper- button and then in our JavaScript
we'll make a copy of this code so right
click
copy and then down
here right click and
paste and now we're going to replace the
rock button
with
paper and when we click this button
we're going to play the game with
paper now let's
save and we'll remove the onclick
attribute and save the
HTML if we click the paper button it
works as
before finally let's do the scissors
button so we'll add a class Js
s- scissors dasb
button and then inside our JavaScript
we'll make a copy of this rightclick
copy and then down here create some new
lines rightclick and
paste and now switch to the scissors
button and play game with
scissors let's save
and remove the onclick
attribute save the
HTML and try the scissors
button so everything still
works and I'll leave switching the reset
score button and the autop playay button
as
exercises so now let's try add event
listener with a different event we'll
use it with key down so let's say that
in our project we want to make it so we
can play the the game with our keyboard
if we Type R it will play Rock if we
type P it will play paper and if we Type
S it will play
scissors let's go into our
JavaScript and we'll scroll
down and we're going to add an event
listener to the body this time so that
if we type anywhere on the page we can
run some code so we're going to get the
body element using document
body and
then add event listener and
brackets this time the first parameter
or the event will be the string key
down and let's type comma and give it a
function that we want to run brackets
arrow and curly
brackets inside here let's just type
console.log key down for now and
save so now if we go to the project and
we open the console
rightclick and click
inspect click the
console and then click on the page if we
type a key on our
keyboard it will run this function and
display key down so now we have to check
what key was pressed and play the game
so how do we know which key that we
pressed earlier in this course we used
the attribute on key down and we learned
that it gets a special object called
event and the event object contains
which key was pressed add event listener
also provides this event object but it
provides it as a parameter to this
function so inside the round brackets
let's add a parameter
event now every time we type on our
keyboard add event listener will save
the event object in here and run the
function and this event object contains
the key that we
pressed so in the console.log let's
display event. key this time and
save now if we click on the page and
type R
event. key will contain R if we press P
event. key will contain P so that's how
we know which key we pressed so now
let's close this and instead of
console.log we'll create an if statement
to check which key we pressed so if
brackets and curly
brackets and here we'll check if event.
key
is equal to the string R if it is we're
going to play the game with rock so
inside here we can just run this play
game
function play game and brackets and
inside we'll type the string
Rock now let's check if we pressed P so
we'll add another Branch else if
brackets and curly brackets and in the
second condition we'll check if event.
key is equal to the string P if it is
we'll play the game with paper so inside
here we'll run play game brackets and
the string paper and finally we'll check
if we pressed s so at the end We'll add
another else if brackets curly brackets
and inside here we'll check if event.
key is equal to the string s if it is
we'll play the
game with the string
scissors now let's
save click our page and type R
and it plays the game with rock if we
type P it will play the game with paper
and if we Type S it will play the game
with
scissors so that's an example of using
add event listener with a different type
of event with a key down if we need the
event object we can get it using a
parameter up here so those are all the
features we're going to create for our
rock paper scissors project
now let's move on to the to-do list
project and switch to add event listener
we'll go into our code editor click up
here and find 12 to-do list.
HTML we'll also scroll up to the scripts
folder find 12 to-do
list.js and open this file and I'm going
to put it at the bottom here so I can
see it side by side I'll close this for
now
and close rock paper
scissors and then open the tab for this
project okay so let's start by switching
the add button to use add event listener
we'll go into our HTML and find the add
button which is here and we're going to
add a class so we can select it in
JavaScript
js-
add- too dasb button
now let's go to our JavaScript and
scroll
down above the add Todo
function we'll get this button into our
JavaScript using
document. query
selector brackets and then a string Dot
and the class we want to get
js- add- too dasb button
and then after this we use do add event
listener
brackets inside these brackets we'll
give it the event the string click comma
and then a function to run when this
event happens so brackets arrow and
curly
brackets and in here we just want to do
the same thing as the onclick attribute
which is ADD too and call this function
let's
save and then in the HTML let's remove
the onclick
attribute and
save and let's try it out so we'll type
A
too watch
YouTube select a due
date and then click add
and the add button still works as before
but we're just using add event
listener next let's switch all the
delete buttons let's scroll up to where
we create these delete buttons which is
here and first We'll add a class to all
the delete buttons so we can select them
in
JavaScript
js- delete Das too dasb button
and now we're going to use document.
Query selector and add an event listener
to all of these buttons however there's
two problems here first is that at this
point in the code this is just a string
we haven't actually put this button on
the page yet we do that down here in
this line of code we put the HTML that
we generated onto the page so in order
to add an event listener we need to put
the HTML on the page first so we have to
do it after this code so down here we're
going to type
document. query
selector brackets and the string Dot and
we'll select this class
js- delete Das too
Dutton however there's also a second
problem here which is we're going to
have multiple delete
buttons and query selector only gives us
the first one so how do we select all
the buttons on the page that match this
criteria instead of just the first one
to do that the document object has
another method called query
selector
all so query selector all will give us
all the elements on the page that have
the class JS delete Todo button so down
here let's console.log this result to
see what it looks like
[Music]
console.log brackets and close bracket
and
save and then here
rightclick
inspect and the
console and expand this you'll see that
document. query selector all gives us a
list of elements and this list works
just like an array this is index zero or
the first button and this is index one
which is the second button so now let's
remove
console.log and add event listeners to
all of these
buttons to do that we're going to Loop
through this list of delete buttons
so again this list works like an array
so we can use a for each method to Loop
through it so at the end let's type
enter and tab and then dot for each and
brackets as usual we'll give for each a
function that we want to run for each of
these values so we'll type brackets
Arrow and curly
brackets and now every time we Loop
through the list for each will give us
two parameters the first one is the
value in the list which is a delete
button element so let's name it delete
button and we'll type comma and the
second parameter is the index so
index so now we want to add an event
listener to each delete button so inside
here we'll type delete button dot add
event listener and
brackets inside these brackets we'll
tell it what event we want to listen to
which is the string click and comma and
then a function that we want to run when
this event happens so brackets Arrow and
curly
brackets so now when we click a delete
button we want to do the same thing as
this onclick attribute above so let's
select this
code we'll
rightclick
copy and then down
here right click and
paste and now we can remove these
characters because we're not in a string
anymore and that's all we need to
do so to summarize we used query
selector all to get a list of all the
delete buttons on the page and then we
looped through the list using four each
and for each delete button we added a
click event listener and ran the same
code that we did before so now we can
scroll up and remove this onclick
attribute and Save
go back to the page close a console and
try out the delete
button and you can see that it still
works so that's how we switch the to-do
list project to use add event
listener so now we're finished improving
all of our
projects in the rest of this lesson
we're going to learn more features that
use functions as
values so let's close this for now and
we'll go back to
12 Advanced functions.
HTML and we'll open the tab for this
file and let's also comment out this
JavaScript code using
slashstar and star
slash let's
save and now let's scroll to the bottom
of this
code and create some new
lines so in this lesson we learned the
array method for each which lets us Loop
through an array now we're going to
learn two more array methods called
filter and map so let's start with
Filter let's say we have an array of
numbers and we want to create a copy of
this array with all the negative numbers
removed so let's go up here and create
an array of the number one comma -3
comma 5 and type the method do
filter and
brackets so Filter Works the same way as
for each we give it a function so
bracket arrow and curly bracket and this
function has two parameters the
value and the
index so filter will take the first
first value save it in here and run the
function then it will take the second
value save it in here run the function
and the third value save it and run the
function now the only difference is that
this time this inner function will
return a value so we'll type
return and we're going to return a
Boolean like
true so now the return value matters so
what filter does is it creates a new
array if the inner function returns true
it will put this value in the new array
if the inner function returns false it
will not put this value in the new array
for example at the front let's
console.log the result of this so we'll
type
console.log Open Bracket and down here
close bracket and Save
so in this example the inner function
always returns true so all three values
will be in the new array if we change
the return value to false every time and
save all three values will not be added
to the new
array so now let's use this to solve our
problem we want to remove the negative
numbers from this array so inside this
inner function we're going to return
true if the number is positive and
return false if the number is
negative so we'll check if value is
greater than or equal to
zero curly brackets will return true and
include it in the new
array
else will return false and not include
it in the new array so let's remove this
and
save so now only values that are greater
than zero will be in the new copy so
using this we can sort of filter out
values based on a criteria that's why
this method is called
filter now we can shorten this logic by
using this code return value greater
than or equal to zero so this comparison
will return true if it's greater than or
equal to zero and it will return false
otherwise so this line does the same
thing as this code up here so we can
comment this out with slashstar and star
slash and
save and as always we can return a
truthy or falsy value instead of just
true or
false the last array method we're going
to learn is called map so let's create
some new lines and scroll
down and let's say we have an array of
numbers again like the array 1 1 3 and
we want to make a copy of this array
with each number
doubled so at the end we'll
type map
brackets and Map works just like for
each and filter between the brackets
we'll give it a function bracket arrow
and curly brackets and this function
will get two
parameters the first parameter is each
value in the array and the second
parameter comma is the
index so map will take the first value
save it in this parameter and run the
function take the second value
save it in this parameter run the
function third value save it and run the
function and inside this function we're
going to return a
value so what map does is it creates a
new array and then whatever we return
will be added to the new array so if we
return
10 and then we console.log this result
console.log
and close bracket and
save it will create an array where each
value becomes
10 now the interesting thing is that we
can actually use the value itself in the
return so here if we did value + 10 and
save it will take each value in the
original array add a 10 and put it in
the new array
so map will transform an array into
another array based on the return value
so if we want to return an array where
each number is doubled we just have to
multiply each value by two and save and
this will give us 2
26 next we're going to review some
shortcuts of Arrow functions to make
this code more
compact first let's make a copy of this
code rightclick
copy and down
here rightclick and
paste so notice in the inner function
we're not using index so let's just
remove it for now and now that this
Arrow function only has one parameter
these round brackets are optional so we
can also remove these to make the code
more compact another shortcut is if we
only have one line of code in an arrow
function we can put the code on one line
like
this and now the curly brackets and the
return are optional so we can actually
just remove all of this
code so if we have just an arrow it will
automatically return this result on the
right and we don't have to type return
ourselves
so this code does the same thing as the
code above but as you can see these
shortcuts make our code very Compact and
clean so let's save and this will give
us the same
result the last thing we're going to
learn in this lesson is a feature of
functions called a closure a closure
means if a function has access to a
value it will always have access to that
value so let's take a look at an example
we're going to go back to the to-do list
project so we'll click up here and then
scroll up to 12 to-do
list.js and close this and then open the
tab for the to-do list which is here and
let's scroll down to the query selector
all so we're going to focus on this
inner function here so notice that this
fun function uses index from above now
the interesting thing about index is
that as soon as this for each ends index
gets deleted for example if we add some
new lines and we try to
console.
log
index and
save and then go into our project
rightclick
inspect and the con
it'll tell us that the index is not
defined so as soon as we end the for
each Loop index doesn't exist
anymore however if we move this into the
inner function so inside here and we
console.log
index and
save and we click a delete button it
will tell us that the index is zero so
even though index gets deleted right
away down here if we click one of these
buttons later on it still has access to
Index this feature is called a closure
if a function has access to a value it
will always have access to that value
the value like index gets packaged
together or enclosed with the function
that's why we call it a closure
so even if the value index gets deleted
after the loop we can click the delete
button 5 seconds later or even 5 minutes
later and this function will always have
access to
index so closures are something that
naturally happens as we write JavaScript
code and it's nice to know how this
feature works there are some Advanced
Techniques that we can do with closures
but they're not used that often so I
won't be covering them in this course
but maybe in a different video now let's
remove
console.log and
save and that's the end of this lesson
in this lesson we learned that functions
are values we learned set time out and
set interval which lets us run a
function in the future we learned an
array method called for each which is a
cleaner way of looping through an array
we used four each Arrow functions and
and add event listener to improve our
projects we learned two more array
methods filter and map and we learned a
feature of functions called
closures here are some exercises to help
you practice what we learned in this
lesson
in this lesson we're going to start the
Amazon Project and we're also going to
learn a very useful technology called
git so first let's take a look at the
Amazon Project to see how it works we're
going to go to our browser
and create a new tab at the top and
we're going to type super simple dodev
SL projects SL Amazon and press
enter so this is going to be the project
we're going to build in this course this
is an e-commerce website that looks like
Amazon where we can see a list of
products on the homepage and then we can
add these products to a cart by clicking
add to
cart and then we can see our cart by
clicking the top
right and on this page it will show us
which products are in our cart and it
will also show us the cost of our order
including shipping and taxes and once
we're ready to create an order we can
click this button to create the order
and it will take us to this page which
shows us a list of our past orders we
can also track our order by clicking
this track package
button and it will take us to this page
which tells us the progress of our order
whether it's preparing it's shipped and
it's
delivered so that's an overview of the
project we're going to built this is a
complex multi-page website where the
different pages interact with each other
to create a full app the first thing
we're going to do is to download the
starting code for this project we're
going to create a new
tab and here we're going to type
github.com
slup
simple Dev SL JavaScript D Amazon d
project and press enter
you can also find the starting code in
the description by clicking
here and then going to the links for
this
lesson and on this page we can see the
starting code for the Amazon Project so
this code contains all the HTML and CSS
that we need the reason we're going to
use some starting code instead of
writing all of this ourselves is because
this course is focused on JavaScript not
HTML and CSS if we were to write all of
this code ourselves it would just take
up too much time and it would be an
entire course by itself if you want to
learn how to create this code you can
check out my HTML and CSS full course
which would teach you all the skills
that you need but for this JavaScript
course we're going to start with the
HTML and CSS here and we're just going
to focus on adding JavaScript to this
website so now let's download all of
this code we can do that by clicking
this green code button here and then
click download
zip once that's finished downloading
we're going to go to our downloads
folder so for me it's this folder right
here called downloads
and then we're going to unzip this file
by double clicking
it and this will give us a folder that
contains all the code so we're going to
select this folder and move it to our
desktop next let's go to our desktop so
we're going to close this for now and
I'll hide the
browser and on the desktop we're going
to select the folder that we downloaded
and we're going to rename this so at the
end we'll remove Main and press enter to
rename it to JavaScript Amazon
Project next we're going to take this
folder and open it in our code editor so
let's open vs
code and we're going to click
file open
folder and we're going to find the
folder that we downloaded for me it's on
the desktop and it's this folder right
here so we'll click this folder and then
click select
folder and then we can close this
welcome
message okay so now we have our starting
code and we're going to set up the
project so first let's open our browser
again and we can close the GitHub
page as well as the tabs for the
previous lessons so we'll close these
tabs right
here but we'll leave the final Amazon
Project
open next let's go back to vs
code and we're going to open this
project in our browser so we're going to
select this file amazon.
HTML so this file corresponds to the
homepage here so let's select this file
and then
rightclick open with live server
so I'm just going to rearrange my
windows here so we can see these side by
side and now we're ready to begin so
let's take a look at the code that we
have to start with as I mentioned all we
have here is the HTML and CSS for this
website there's currently no JavaScript
at all on this
page so one thing you'll notice is that
we can actually create almost all of the
website using just HTML and CSS we
actually don't even need JavaScript to
create all of this we're able to create
the header at the top as well as three
products to start with and this shows
that HTML and CSS can pretty much create
everything that we see visually on the
website where JavaScript comes in is
that JavaScript makes this website
interactive so right now if we click the
add to card button it looks pretty nice
but it doesn't actually do anything and
that's because we haven't added
JavaScript yet so the role of JavaScript
is to make our website interactive after
we created all the content and The
Styling now before we begin adding
JavaScript to this website we're
actually going to take some time and
learn another very useful technology
called git so git is a technology that
lets us track changes in our code for
examp example do not follow along here
but let's say that I'm working on this
website and I go into my code editor and
I change some code here so let's say
that I add some code
here and then in this file I'm going to
delete some code so I just select some
code and delete it and then
save and then in this file I'm going to
change some code at the bottom
so now let's say that I made a mistake
and I want to undo all the changes that
I just made so how would I do that how
would I remember all the code that I
changed in the different files so right
now this is really difficult and this is
a problem that we run into in bigger
projects we're changing lots of code in
different files and it's really hard to
keep track of what code has changed and
this is where git comes in git lets us
track changes in our code and it helps
us solve this
problem so here's what it looks like if
I have git set up in my project I can go
into this section of VSS code this
section is for git and then here git
will tell me which files I changed and
if I click these files it will tell me
which lines I changed and exactly which
code I changed if I want to I can click
this button
to reverse all the changes in this
file I can also click here to reverse
all the changes in all the
files so as you can see kit helps us
track changes in our code and it lets us
easily undo our changes if we need
to and this technology is really useful
in bigger projects like this Amazon
Project where we're going to be changing
lots of code in in many different files
so before we start this project we're
going to learn how to set up and use
git the first thing we need to do is to
install git to do that we can go to this
section of vs code called Source
control now if this section looks like
this with a button initialize repository
that means you already have git
installed otherwise if you're on Windows
you can click this button and then click
open or you can go to this website
directly and then click this link to
download
git once it's finished downloading we're
going to run the installer and then just
go with the default
options if you're using a Mac you can
click up
here and then type
terminal and press enter
and inside here you're going to type git
and press
enter and then click this link and
install
git all right after installing git we're
going to restart vs
code and make sure you have the Amazon
Project
open and now if if we go into the git
section it should look like this with
the button initialize
repository so now that we've installed
git we're going to set up git in our
Amazon Project we can do that by
clicking initialize
repository if this button doesn't work
for you you can also try going to the
terminal menu and click new terminal
and then inside this terminal type kit
in it and press
enter so a repository is just a folder
where changes are being tracked by
clicking initialize repository this
turns the current folder which is
Javascript Amazon Project into a
repository and now all the changes
inside this folder will be tracked by
git so to start off git will tell us
that all of these files are new files
and that's because we just set up this
repository so all of these files are
considered new changes that we're
starting to keep track
of next we need to configure a username
and email with Git now don't worry this
information is not used anywhere online
this is just forget to add an author to
the changes that we make so to configure
a username and email we're going to go
to the
top and open the terminal menu and click
new
terminal and then inside
here we're going to type get config
user.name and double
quotes now if this looks familiar to you
and you've already done this before you
can skip this step and and the next
step so between these double quotes
we'll pick a username that we want to
use so for me I'll use super simple Dev
and press
enter and we'll also configure an email
by typing get config user. Emil double
quotes and between these double quotes
we'll put an email so I'll put Simon at
superimple
dodev and press
enter so now that we configured a
username and email we can close this
terminal next we're going to save these
changes into git so that git will start
tracking any new changes that we make to
save these changes we're just going to
type type a message here describing what
we changed so let's just type the
message add the starting
files and then we're going to click
commit and if this popup shows up we're
going to click
yes so that will take all of our changes
and save them into git so now that we've
saved those changes into git any new
changes that we add will start showing
up here so let's do an example and let's
change some code in a couple different
files for practice so let's click this
icon up here to show our code and let's
go into amazon.
HTML and we'll just change this title to
intro to git and
save and then let's go into checkout.
HTML and at the top let's actually
remove the title and save and then let's
open orders.
HTML and at the top let's just add
something to the title like
page if we
save and then go into the source control
section or the git
section it will tell us all the changes
that we just made in our code in the
three different files if we click one of
these files it will actually tell us
exactly which code that we
changed now if your git section looks
like this where the changes are on top
of each other instead of side by side if
you want to you can change this by
clicking these three dots here making
sure that inline view is unchecked and
also unchecking use inline view when
space is
limited so now it's very easy to undo
this code we can just take the code on
the left and then copy paste it on the
right to undo this change we can also
click here to undo all the changes in
this
file and up here we can also click this
button to undo all the changes in all
the different
files so that's an intro to Git it helps
us keep track of changes in our code and
it's very useful for bigger projects
like this Amazon Project where we're
going to be changing lots of code in
many different files if you want to
learn about git in more detail you can
check out my git and GitHub full course
in the video
description so now that we've setup git
let's start the Amazon Project so first
make sure that this section is empty and
we've reversed all the changes that we
made when practicing
git next let's click the this icon to
show our
files and let's remove the previous
code and we're going to start in the
amazon. HTML
file and let's close the git page and
then open the tab for this file it
should say amazon. HTML up
here so we'll start by creating the list
of products on the homepage so right now
we start with three products if we go to
the final project we're going to add the
rest of the products that you see here
and we're also going to make this
interactive so that when we click the
add to card button it will add this
product to our
cart so let's go back to our
project and in order to create this
we're going to learn the main idea of
JavaScript so when using JavaScript
script we usually do a three-step
process the first step is to save the
data and then we generate the
HTML and finally we make it
interactive let's go through each step
to create this list of
products so right now we have three
products on our page to start with and
we're going to add more products to this
page so let's start by finding the HTML
for one of these products because we can
always just copy and paste this to
create another one now we're going to
learn a very important skill for bigger
projects which is how to find the code
for something on this page so let's say
that we want to find the code for one of
these products we're going to
rightclick and click
inspect and this will bring up the
console and I'm actually going to click
these three dots and click this icon to
move the console to a separate window so
that we can see the whole web page so
now we're going to click this icon in
the top
left and we're going to hover over and
click the thing that we want to get the
code for so I want to get the code for
this entire first product so I'll click
in this
space and this will tell us that the
code for the product is this code a div
with the class product -
container so now we're going to take
this class and then search for it in our
code editor so let's open vs
code and we're going to type contrl f on
Windows or command F on Mac to search
for code in this file so we're going to
search for the class that we saw earlier
which is
product-
container and this will take us to the
code for one of these products so we can
actually click the arrow on the left to
collapse this code and we'll see another
product container which corresponds to
the second product we can click this
Arrow again and we'll see a third
product container which corresponds to
the third
product so that's how we find the code
for something on the page now to add
another product to this page one thing
we can do is to take this HTML and just
make a copy of it at the bottom of the
page however this is not a good idea
because if we add lots of products we're
going to be copying this HTML over and
over and if we expand this you can see
that each product has a lot of HTML code
so we don't want to be copying all of
this over and over again it's going to
be a lot of code and it's going to be
hard to manage in instead another
strategy is to generate this HTML code
using JavaScript so let's learn how to
do that before we can do that we need to
add JavaScript to this page so we're
going to create a Javascript file so
let's click up here to show our
files and first let's create a new
folder to contain all of our JavaScript
code so let's name this folder SC
scripts and press
enter next let's click on our folder and
we're going to click this icon to create
a new file and we'll name this file
amazon. JS and press enter so this will
be the Javascript file for this HTML
file next inside this Javascript file
let's type the code
console.
log
hello just to make sure that this works
and
save next we're going to load this
Javascript file in our HTML file so
let's go back to amazon.
HTML and then at the bottom of the code
we're going to scroll down and then
right above the closing tag for the body
we're going to add a script element
and we're going to give this element an
attribute SRC or Source equals double
quotes and we're going to load this
Javascript file so this Javascript file
is in a folder called scripts so here
we're going to type the folder name
scripts and then a forward slash to go
into the folder and we'll load the file
amazon. JS and
save so now let let's go back to the
page and we'll open the console right
click
inspect and then click the
console and it should display hello so
now we're loading JavaScript on this
page so let's open up vs code
again and we're going to generate all of
this HTML using JavaScript instead so
the first step in our process is to save
the data what does this mean data means
information so in this case the data is
the information about our products for
example the products name the price
ratings and the image so right now the
information about the products or the
data is inside our
HTML so in our code if we click here to
expand this element you can see that the
inform
about the products for example the name
and the image is inside the
HTML so what we need to do is to take
this data and save it inside our
JavaScript so that our JavaScript can
use it so let's go to our Javascript
file and I'm just going to put it down
here so we can see it side by
side and we're going to move this data
into our JavaScript
so let's remove
console.log and let's create a variable
to save the data so we'll type const and
let's name it
products and make it
equal and now we want to create
something that closely matches our data
so in this case we have a list of
products so in here we're going to
create an array because an array
represents a list
and now each product in the list has
many values like an image a name and a
price so we're going to use an object to
represent each product because an object
lets us group multiple values
together so inside this array we're
going to create an object using curly
brackets and now inside this object
we're going to save the data for the
first product so first let's find the
data in our HTML we're going to search
for the product's name by typing contrl
F or command F and we'll search for
black and
gray and this will take us to the code
for the first product so this is the
name of the first product so let's
actually scroll up and we're going to
get get the image for the first product
and we're going to take this and save it
in our JavaScript so let's select this
code we're going to
rightclick
copy and then inside this object let's
create a property called image colon and
then here right click and
paste and let's save this as a string so
at the front we'll type a single quote
and at the end we'll type a single
quote so we just saved the image inside
our
JavaScript let's move on and save the
name inside our JavaScript so we'll
scroll down we'll select this code and
then
rightclick
copy and in this object we'll type comma
and a property called name col in a
string
and we'll right click and
paste next we're going to save the
rating into our JavaScript so we'll type
comma and let's create a property called
rating
colon for the rating there's actually
two parts the stars and the number of
ratings that it has so let's actually
group these two values into an object
because these values are related to each
other so in here we'll make the rating
and
object and each rating will have the
stars and for the socks it's
4.5 comma and the rating will also have
a
count and for the first product it's
87 next let's save the price into our
JavaScript
so we'll create another property called
price and for the first product the
price is
$10.90 however JavaScript has problems
doing math with decimal numbers or
floats like this so a best practice when
calculating money is to calculate in
cents instead of dollars so for this
reason we're going to save the price as
cents so we'll save it as
1,90 as a reminder $1 is equal to 100
cents and because we're saving in cents
it's helpful to rename this property to
price cents
instead so now if we scroll up we just
saved all the information or the data
about the first product into our
JavaScript next let's go to the end here
and type comma and create another object
and we're going to save the data for the
second product into this object so feel
free to pause the video if you want to
try it yourself
first so again let's find this product
in our HTML we'll go to our HTML and
type contrl f or command F to search for
code and we'll search for the name
intermediate
size basketball so now this is the code
for the second product we're going to
scroll up a bit and find the image for
this product and we're going to select
it rightclick
copy and then inside the second object
we'll create an image property just like
we did up
here and we'll save it as a string and
we're going to rightclick and
paste and let's type comma and we'll
save the name inside the second object
so we'll scroll down and select the
name and then right click
copy and then down here create a string
and rightclick and
paste and we'll type a comma and we'll
save the rating
colon
object and we'll save the number of
stars which is
four and the number of ratings that it
has count colon
127 and finally we'll type a comma and
we'll save the price of the product in
cents colon
295 so now the data for these second
product is saved inside our
JavaScript let's go to the end and type
comma and create another object and
we're going to save the data for the
third product inside again feel free to
pause the video to try it yourself first
so let's save the image we'll find the
code for this product in our HTML so up
here we'll typ contrl F or command
F and we'll search for the product name
which is
adults plain cotton
t-shirt and scroll up and we're going to
save the image first so let's select
this right click copy and then down here
create an image property colon and a
string and then right click and
paste and we'll create a comma and let's
save the name in our Javas script next
create a string and then we'll scroll
down here we'll select the
name right
click
copy and then in here right click and
paste and comma and we'll save the
rating colon and object and we have the
number of stars for this one it's
4.5 colon and the
count and for this one it is
56 and lastly type a comma and we'll
save the price in
cents colon
799 and now let's save our Javascript
file now one really important thing is
to make sure that in each of these
objects we have the same property so we
have the image property the name
property and the same rating property
with the same structure we want all of
our objects to have the same structure
so that our code can handle each product
the
same so that's what it means to save the
data we create something in JavaScript
that closely matches the data that we
have on the Page by the way this is
called a data structure because its
structure structures or organizes the
data and this represents a list of
products so we usually use a combination
of objects and arrays to create a data
structure in
JavaScript so now that we've saved the
data the next step is to use this data
to generate the HTML instead of writing
the HTML
manually to generate the HTML we can
Loop through this array and for each of
these products we're going to create
some
HTML so let's go ahead and loop through
this array first we'll scroll down to
the
bottom and we'll type the name of the
array which is products and then we'll
Loop through this array using a for each
method so we'll type Dot 4 Capital each
brackets and inside we create a function
using brackets arrow and curly
brackets and we'll give it a parameter
called
Product so I'm going to move this back
to the top here so we can see more of
the code so the way that for each works
is that it takes each object saves it in
this parameter called Product and then
runs the function so it takes the first
object saves it in product runs the
function function takes a second object
saves a product runs a function and so
on so for each of these products or each
of these objects we want to create some
HTML so inside this function let's
create a variable const
HTML equals and we'll create a template
string using back
ticks and now inside this template
string we're basically going going to
copy all the HTML for one of these
products so let's go back to our HTML
file and how do we find the HTML for one
product so we learned this earlier we
can
rightclick
inspect and then click the top left
icon and click the element we want to
get the HTML for so this HTML represents
one product and we can search for this
class product- container in our code so
we'll go back to our vs
code inside the HTML file we can contrl
f or command F to search for code and
we'll search for the class product Das
container and let's go to the first
result so we'll go to the first result
which is here and let's copy all of the
code inside this ele element one trick
we can do is to click the arrow on the
left to collapse it and then we'll
select all this code and we'll
rightclick
copy and then inside our Javascript file
inside the string we're just going to
rightclick and paste the
HTML and if we need to fix the
formatting we can select all of this
code and then press tab a few times to
add some indexs and here we can remove
the indent and let's
save so now we're basically looping
through the array of products and for
each product we're creating all of the
HTML that we had before so we're
generating this HTML using
JavaScript now let's console.log this
HTML to make sure that it's working
we'll scroll down to the
bottom and here let's
console.log the HTML that we just
created if we
save and then go back to our page right
click and
inspect and click the
console you can see in the console that
we just generated all this HTML and we
generated three of these
let's go back to our
code and scroll
up now one problem here is that in the
HTML that we generate we don't want to
have the name black and gray socks every
time for the second product we want to
have a different name and a different
image and for the third product we want
to have a different name and a different
image so how do we create slightly
different HTML for each
product to do that we're going to
replace this part of the code with
whatever the image property is so for
here we're going to delete it and we're
going to insert the property image into
this string so to insert values into a
template string like this we can use
Dollar open curly bracket Clos curly
bracket and then inside here we're going
to insert the
product. image property so it's going to
take whatever the image property is of
the product and put it inside this HTML
code same thing for the name instead of
black and gray socks every time we're
going to delete this and then insert a
value we're going to insert the
product Dot and we'll insert the name
property this time into this HTML so dot
name and we'll do the same thing for the
other pieces of data so for each product
the number of stars could be different
so instead of 4.5 every time let's
delete this and we're going to insert
the products rating and stars so
product.
rating. Stars
one thing we have to watch out here for
is that this image has to exist so right
now if we substitute the product.
ratings. Stars into this we will get
this image and if we go into our files
by clicking here and open the images
folder and then open the ratings
folder we can see that there's no image
called rating
-4.5 instead there's an image called
rating
-45 so if the rating is 4.5 we should
convert it into 45 so that this image
actually
exists similarly if the rating is four
we should convert it into 40 so that
this image actually exists so in here we
should actually multiply this by 10 so
that this points to an actual image that
exists
here next let's move
on and we'll work on replacing the count
so we'll remove this and dollar curly
brackets and we'll replace it with the
products. rating Dot and the count
property so
count and finally we're going to replace
the price for each product so in here
we're going to remove this and
substitute
product. price
sense and remember that this is a number
in cents but when we display it on the
page we want to display it as dollars so
we're going to divide this by 100
because there are 100 cents in each
dollar so now in the HTML that we're
generating we're actually inserting the
details about each product if we
save and then go back to the console
right click
inspect and
console and look at the HTML that we
generated you'll see that it's different
for each of the products so that's how
we use JavaScript to generate all the
HTML
here so now the last step is we're going
to combine all this HTML together into
one string and put it on the web page
let's go back into VSS
code and to combine all this HTML
together let's create a variable at the
top for combining all the strings
together so we'll type let let's call it
products cap Capital
HTML and make it equal to an empty
string to start and then each time we go
through the loop we're going to add this
HTML string up here so instead of
creating a new variable we're just going
to add products
HTML equals itself products
HTML plus this string and remember a
shortcut for this is to just type plus
equals so this is called the accumulator
pattern we Loop through an array and
each time we're adding to the result so
we're accumulating the result and now
that we combine all the HTML into this
variable we can scroll to the
bottom and let's remove this line
because this doesn't exist anymore
and then after the loop let's
console.log the products
HTML and
save and now if we go into our
console we combined all the HTML for all
the products
together and now the last step is to
take this HTML and put it on the page
and we can do that using the Dom
so let's go back into our
code and to use the Dom we're first
going to get an HTML element from the
page and put it inside our
JavaScript so first let's go to our HTML
file and remember that a product-
container represents one of these
products here so we're going to look for
this element here a div products- grid
so this element contains all of our
products so we're going to use the Dom
to take this element put it into our
JavaScript and replace all the HTML
inside so to put this element in our
JavaScript we're going to give it a
class so let's add a class
js-
products- grid and
save and let's go into our JavaScript so
I'm just going to move this this down to
the bottom again so we can see it side
by
side and then inside our JavaScript at
the bottom we're going to use the Dom by
typing
document. query selector brackets and a
string and we're going to type dot to
select a class and we're going to select
js-
products-
grid so the DOT means we're going to
look for a class called JS products grid
which is right here and it's going to
take this element and put it inside our
JavaScript and now we can change the
HTML inside the element to do that we'll
use the property do inner Capital
HTML and we'll change it to the products
HTML that we created Above So for
products Capital
HTML and
save so it's not going to look any
different but now we're actually
generating all the HTML with JavaScript
and then using the Dom to put this HTML
inside here so now we can actually
delete all of this because we're
generating this with
JavaScript if we save this file
our products will still be here because
even though we deleted the HTML we're
now generating it with
JavaScript now one problem that I see
here is that the price shows up with one
decimal but we actually wanted to show
up as
10.90 so let's scroll up to this part in
the code so we'll scroll up
here and look for Price
sense and the reason this happens is
because price sense is
1,90 so if we divide that by 100 the
result is actually
10.9 if we want to force this to show
two decimals like
10.90 we actually have a special method
that we can use with a number so here we
can add brackets around this to make
sure we calculate this number first and
numbers have a special method called dot
2 Capital fixed and brackets so to fixed
we'll convert a number into a string but
we can tell it how many decimals we want
between the brackets if we type two it
will show two decimals so if we save now
it shows correctly on the page if you're
wondering how to find this method you
can find it by searching in Google or
using an AI
tool okay let's let's take a break here
and take a look at git to see all the
changes that we made so I'm going to
expand this here and we're going to
click the git
section and it's going to tell us that
we changed two files if we click the
HTML
file git will tell us that we deleted
all of the HTML code for the products
which is correct if we open the
Javascript file it will tell us that we
added all of this new JavaScript code
including the data and the loop for
generating the
HTML so git helps us track all of the
changes that we made so now let's
actually take these changes and save
them into git so we can track new
changes at the top let's type a message
to describe the changes that we made so
let's type
generate HTML with
JavaScript and click
commit and yes if this shows
up so now let's talk about the benefit
of generating the
HTML so let's close git for now and I'll
move this to the side
here so the benefit of generating the
HTML is that if we want to add another
product we don't have to copy paste all
of this HTML again all we need to do is
to go up to the data and add the data
for a new product so let's do an example
and add a fourth product to our list so
at the end here let's type a comma and
create another
object and let's go to the final
project and we'll scroll down to this
four fourth product here so we're going
to take the data about this product and
save it in our JavaScript so first let's
create a property image colon string and
we're going to take this image and put
it in here to do that we can rightclick
the image
inspect and then we're going to copy
this Source attribute so we can double
click it and we can select this
attribute
rightclick
copy and then inside our JavaScript
we're going to right click and
paste and at the end we'll type a comma
and create the name
property and a string and we're going to
select this
name rightclick copy and then in here
right click
paste copy comma and a rating property
colon and object we have these Stars
which is five and the
count which is
2,197 and at the end we're going to add
the price in cents colon
1,899 so now if we save this JavaScript
file and then go back to our
project and we scroll down you'll notice
that it automatically added the fourth
product and all we had to do was to add
another object to our array and then our
Loop will handle generating all the HTML
for us so you can see that generating
the HTML with JavaScript is a lot easier
than copy pasting this HTML every time
and that's why we use this
technique next we're going to add the
rest of the products in the final
project now one thing we could do is to
manually copy this over one by one but
to make this easier inside the starting
code I've actually created a file that
contains all the data so if we scroll up
and close this for now and we're going
to go to this data folder and open it
and inside this folder I've provided a
Javascript file called products. JS and
in here it contains an array with the
data for all the products in the final
project so we don't have to create it
ourselves so now let's use this products
array in our code so first we need to
load this file on our page we can go to
our amazon. HTML file and then scroll
down to the
bottom and then at the bottom in the
script element we're going to add
another script element above it so we
type script and then the source is going
to be equal to this Javascript file so
we'll type the folder called data and
then a slash to go into the folder and
load the file
products.
JS so what this does is that it will run
the files one by one
first it will run the products. JS file
and create the array and then it will
run our amazon. JS file and generate the
HTML so back here let's
save and then go back into amazon.
JS so now instead of using our own
products array let's just use the
products array in this
file so we'll go back to to amazon.
JS and we're just going to delete this
array so over here we can click this
Arrow to collapse the code and I'm going
to select it and then just delete
it and
save so now this variable will be coming
from this file if we go back to our
project and scroll down you can see that
we created all the products in our final
project so the way this works is that
inside our amazon.
HTML we're loading two JavaScript files
this Javascript file creates all the
products and then this Javascript file
Loops through the products and creates
all the
HTML so keep in mind that script
elements are loaded one by one so the
order matters we have to first create
the products array and then we can use
it if these two were reversed then the
code wouldn't
work so this is how a real world website
is created we don't write all the HTML
manually instead we save the data for
the website in a data structure like
this and then we use JavaScript to
generate the HTML using the data so now
let's go into get and look at our most
recent
changes so here it will tell us that we
changed two files in the amazon. HTML
file we added a script element and then
in the amazon. JS file we deleted the
products array that we created on our
own so let's type a message to describe
our changes use products. JS file and
then click commit and yes
now one other thing I want to show you
about git is if we go back to our files
here and then open amazon. JS git has a
really useful feature called a history
so we can open this timeline section and
then click this filter icon and only
check git
history and now you can see that we
actually have a history of all of our
changes for this file so if we click the
first line in the history it will show
us that here we added all of the code
and then the second line in the history
we deleted this part of the code so this
gives us a step-by-step history of all
the changes in our code and in git this
is called a version history you can also
see that the messages that we created
when we commit show up here and these
messages help us us understand what was
changed in each version in the
history all right so let's close this
for
now and the last step in the process is
to make it
interactive so let's take a look at our
current
project so we'll go here and open this
tab and let's scroll
up so right now if we click the add to
cart button Buton it doesn't do anything
so we're going to add some JavaScript to
make this interactive and actually add
this product to a cart so first let's
find the add to cart button in our code
we'll go back to our amazon. JS file
close this for
now and to find the code we can actually
just search the text in the button so
inside here let's typ contrl F or
command F and we're going to search for
the text add to
cart and this will take us to the code
for this button so now we're going to
add an event listener to this button and
make it do something when we click it to
add an event listener we're first going
to add a
class
js-
add-2
dcart and then we're going to use the
dawn to add an event listener to this
button so down
here after we've put this HTML on the
page we're going to use
document. Query
selector all brackets and then a string
a DOT and we're going to select all the
js- add to cart so
js- add-2 to- cart so this will give us
a list of all the add to cart buttons on
the page and then we can Loop through
each of the buttons so we can type dot
for each
brackets and then in here we'll give it
a function bracket arrow and curly
brackets and a parameter so the
parameter is going to be the button
element that we got from the page so now
for each of these buttons we're going to
add an event listener so we can do
something when we click the button to do
that we'll type
button. add event
listener brackets and then the event
that we want to listen for which is the
click
event and then a function that we want
to run when we click this button so
brackets arrow and curly
brackets so for now let's just
console.log a message to make sure that
this is working so we'll
console.log added
product and
save and we can also remove this line
for now because we're not using it and
save again and then now on our page
we're going to click add it to
cart and then look inside our console so
rightclick
inspect and click the
console and it displays added product so
now whenever we click one of these
buttons it will display this message so
that means that our code here is working
correctly next we need to figure out how
to add the product to a cart and we need
to figure out what this looks like if we
think about a cart a cart is basically
just a list and inside this list we have
the product that we want to buy and the
quantity or the number of this product
that we want to buy so we can actually
represent this in JavaScript as an array
inside the array we can have some
objects and each object is going to
contain the product and a
quantity so we can use something like
this to represent our cart so let's go
ahead and create create this cart array
now to keep things cleaner let's
actually separate the cart into its own
file so we'll click up here to show our
files and then we'll go into the data
folder and click this folder and click
this icon to create a new
file and we'll name this file cart. JS
and press
enter so this file will contain all the
code related to the cart and the reason
we separate it is to keep our code
organized each file will focus on one
particular thing so inside
C.J let's create our cart so we can just
create a variable const cart and make it
equal to an array so we'll start off
with an MD cart and let's save this
file and now we need to load this file
into our
HTML so we can open amazon.
HTML and again we can just add another
script element so let's add it at the
top to make sure we load the cart before
running the rest of our code so we'll
type less than
script and the attribute
source and we'll load the data folder
slash to go inside cart. Js
and
save so now it will run this file at the
start and it will create an array
representing our cart so now that we
have a cart we need to figure out what
happens when we click a button how do we
add a product to this cart so let's go
back into amazon. JS and we'll figure
this out together so down here this is
the function that is run when we click
the button so in here we have to figure
out how to add this product to the
cart one way to do this is to just add
an object to the cart like this we have
the product's name and the quantity that
we want however when we click this
button how do we know which product
we're supposed to add to the cart to
solve this problem we're going to learn
a feature of HTML called a data
attribute
a data attribute is just another HTML
attribute except the purpose of a data
attribute is that it allows us to attach
any information to an HTML element so
let's do an example and create a data
attribute we're going to scroll up to
the add to card button here and then at
the end of the opening tag after the
class we'll type enter
and then we're going to type data Dash
and then we can type any name that we
want like
product-name and we'll make it equal to
double
quotes and then inside the double quotes
we're going to put the product's name
like a basketball or a t-shirt so to do
that we're going to insert using dollar
and curly
brackets product
AME and
save so now let's inspect the HTML on
the page we're going to rightclick on
this add to card button and
inspect and then in the elements tab it
will show us the HTML for the button and
now you can see that each of these
buttons now has a data attribute called
data- product-name and it's equal to the
product name
so before we continue let's learn the
syntax rules for the data
attribute a data attribute is just an
HTML attribute that means it follows the
same syntax rules we have an attribute
name on the left and an attribute value
on the right the one difference is that
data attributes have to start with data
Dash and then we can give it any name
that we want like product- name but we
have to make sure to separate the words
with a dash this is also known as Kabob
case so the purpose of a data attribute
is that we can attach any information to
an element so here we attached the
product name to this button but we can
also attach the product's image or the
price and so on so now that we attached
the product's name to this button when
we click this button we can actually get
the name and this will tell us which
product we should add to the
cart so let's see what this looks like
in our code so we'll go to our
code and then when we click the button
we're first going to get the product
name from the button to do that we're
going to type button and then the
property dot data set
so the data set property basically gives
us all the data attributes that are
attached to this button so now we're
able to get the product name so let's
console.log this to see what it looks
like
console.log Open Bracket close bracket
and
save and then in here let's click the
basketballs add to cart
button and we'll go into our console
right click
inspect and
console and I'm just going to move this
to the left so we can see it side by
side with our
code so this is what the data set
property looks like it gives us all the
data attributes that are attached to the
element so in our case we have the
product name now this works just like an
object so to access the product name we
just have to type dot product capital N
name so notice that the name gets
converted from Kebab case to camo case
so now if we
save and let's go back to our
website and click the add to cardart
button it will get that data attribute
from the button and display it in the
console if we click the socks at to cart
button this will tell us which product
we should add to the cart so now that we
have the product name let's actually put
this into our cart so let's go into our
code and here let's save the product
name in a variable called const
Product name
equals and then here we're going to add
this to the cart
so we already created a cart variable
here so we're just going to type the
variable cart and we're going to dot
push into the array and let's push an
object because we said we wanted a
product and the
quantity so we'll add an object
containing the product name which is
this variable product
name and a quantity
of
one and that's pretty much it we first
attached the product name to the button
using a data attribute and then when we
click the button we got the product name
out and then we add the product to the
cart so at the bottom let's
console.log thee cart to see what it
looks like if we
save and then go here and open the
console right click inspect
console and let's add a basketball to
our cart so we'll click here and then in
our cart we now have a basketball with a
quantity of one so now let's add another
product to our cart we'll go to the
t-shirt and click add to
cart and now we have two products in our
cart one b basketball and one
t-shirt so now we're successfully adding
products to a cart next let's try adding
one t-shirt again if we click add to
cart and unfortunately this doesn't look
quite right the T-shirt product is
repeated twice and each of them has a
quantity of one what we actually want to
do is we want one t-shirt product with a
quantity of two
because this is how we're going to
display it on the cart page so let's
figure out how to achieve this and we'll
do this step by step first we'll check
if the product is already in the cart if
it is in the cart we'll just increase
the quantity by one if it's not in the
cart We'll add it to the cart so let's
convert these steps into code so the
first step is to check if a product is
already in the cart so how do we do that
let's go back to our
code and one way to check this is we can
Loop through our cart and look for a
particular product name so up here let's
create some new lines and let's check if
this product name is already in the cart
array so we'll type cart and we'll Loop
through the cart using dot for each
brackets and then inside we'll give it a
function brackets arrow and curly
brackets and we'll give this a parameter
and let's just call it an item so an
item will contain a product name and a
quantity so we want to see if this
product name is already in the
card so we're going to check if the
product
name over here is equal to this item's
product name so we'll type equals the
item.
product name and curly
brackets so if the product names match
that means this product is already in
the
cart so let's save this matching item in
a variable so we can use it later so
we're going to create the variable
outside the for each Loop and outside of
its scope so we'll type let matching
capital I item and we'll make it
undefined to start and if we find a
matching item we're going to save it in
this variable so
matching item equals
item so this is how we figure out if a
product is already already in the cart
now the next step is If the product is
in the cart we'll just increase its
quantity by one so we'll type
if
matching item and curly brackets so we
can just type matching item here because
if we did find a matching item it will
be an object which is a truthy value so
in here we're going to increase the
matching items quantity by one using
matching
item. quantity and we'll plus equal
1 and finally If the product is not in
the cart We'll add it to the cart which
is basically what we do here so at the
end we can just type else if we did not
find a matching item curly brackets and
move this code so we'll select it right
click
cut and then in here rightclick and
paste and remove the new lines and
save so now let's go into our project
we'll
rightclick inspect the
console and let's click the add to card
button for the basketball so we'll click
this
and then in our cart we have a
basketball with a quantity of
one let's add a
T-shirt and now we have one T-shirt with
a quantity of one and if we click add to
cart on the T-shirt
again now we have a t-shirt with a
quantity of two so that's how we solve
the problem of combining the quantities
together now there's one last problem
that we have to solve here
which is it's not good to use the
product name to identify the product in
the cart because in an e-commerce
website we might actually have two
products that have the same name but
from different brands so to fix this we
should give each product an ID and this
ID should be unique so no two products
will have the same ID so let's use an ID
to identify these products instead of
using the name we'll go back to our
code and if we open our files here and
go to data products.
JS you'll notice that I've actually
added an ID for each of these products
and this ID is unique so I added it here
to save us a bit of work so we don't
have to create the IDS
ourselves so now let's just use this ID
in our code so we'll go back to amazon.
JS and then in here instead of using the
product name we're going to use the
products ID to identify it in the cart
but first we need to attach the ID to
the button so we'll scroll up and
instead of a data- product name
attribute we're going to use a data
product-id attribute and we're going to
save the
products ID
instead and now down here we're going to
grab the ID from the button to do that
we'll change this to product ID so
remember this gets converted from Kebab
case to cam case and we'll rename this
variable product
ID and then here we'll compare product
ID is equal to the items product
ID and lastly when we add to the cart
we're just going to add the product ID
to the
cart and
save so now if we go to our website and
click add to cart and check our
console and expand this you can see that
we're saving the product ID so that two
products with the same name will be able
to be added to the
cart okay so that's how we make the add
to cart button
interactive and now we finished all
three steps first we save the data for
the website in our JavaScript and then
we use this data to generate the
HTML and finally we made it
interactive and this is the main idea of
JavaScript this is generally how we use
JavaScript on a real
website now let's go back to git so
we'll open our code editor and open the
git section and review the changes that
we made so we'll expand it and then in
the HTML file we just added the cart. JS
file and then in here we just created
the cart array and in our amazon. JS
file we basically added a data attribute
to the button and then down here we made
the button interactive by adding an
event
listener so now let's save these changes
into git we'll type a message to
describe our
changes make add to cart button
Interactive
and click
commit all right so let's close this for
now and the last feature we're going to
create in this lesson is we're going to
make this cart quantity in the top right
interactive so we'll do this step by
step first we need to calculate the
quantity or the total number of products
in our cart and then we're going to put
that quantity
on the page here so how do we calculate
the total quantity of the cart so
remember that the cart is an array of
objects and each object has a quantity
so to calculate the total quantity we
can Loop through this array and add the
quantities together let's go into our
code and we'll open amazon. JS and let's
scroll to the
bottom so here after we update our cart
we're going to calculate the total
quantity so let's create some new lines
and as we saw earlier we can Loop
through the cart array so we'll type
cart dot for each brackets and a
function arrow and curly brackets and
we'll give this a parameter
item so this is going to Loop through
each object in the cart
next we need a variable to store the
total quantity so let's create a
variable up here we'll type let and name
it cart
quantity and make it equal to zero to
start and then as we Loop through this
array we're going to add the items
quantity to this variable up here so
here we can type cart quantity plus
equals the
items.
quantity so this will add up all the
quantities and save it in this
variable so at the bottom let's
console.log the cart quantity to make
sure that this is working so we'll
save and go back to our page and open
the console right click inspect and
console when we click add to cart on the
basketball the quantity will be one if
we click add to cart on the T-shirt the
quantity will be two if we click again
the quantity will be three so looking at
the cart it basically added one
basketball and two T-shirts to get a
total of three so that's how we can
calculate the total quantity of the cart
so now that we have the total quantity
we're going going to put it on the page
here and we can do this using the Dom so
let's go back to our
code and to use the Dom we first need an
HTML element where we're going to put
this quantity so let's find the HTML
element for this number here we can go
back to our page we're going to
rightclick this number and then
inspect and then we can click this icon
in the top
left hover over this number and click
it so this will tell us that the code
for the number is this code right here a
div with a class cart quantity so now
we're going to search for this class
cart quantity in our code so let's go
back to our
code and let's go to the amazon. HTML
file because the header is still in this
file and we'll type contrl f or command
F to search for code and we'll search
for cart Das
quantity and it will tell us that it's
this line right here so next to use the
Dom we need to get this element into our
JavaScript to do that we're going to add
a class to this element so let's add the
class
js- cart D quantity and say
save now let's go back to our JavaScript
file and I'm just going to move it down
here so we can see it side by
side and we'll scroll down after we
calculate the quantity let's get this
element into our JavaScript using the
Dom so at the bottom we'll type
document. query
selector brackets and a string we start
with a DOT and the class
js- cart D
quantity and now that we have this
element we can change the HTML inside
using the property do inner Capital
HTML and we'll make it equal to the cart
quantity that we calculated above so
let's
save and go back to our website and
let's click the add to card button for
the
basketball now it will update the
quantity to be one let's click the add
to cart for the T-shirt it will update
the quantity again and it will be two if
we click it again it will increase to
three so now the cart quantity up here
is
interactive the last thing we need to do
is we'll go back to our
HTML and in instead of starting at three
the card quantity should start at zero
so let's
save and now the cart quantity starts at
zero if we click add to cart it will
increase to one so that's how we create
this cart quantity feature in the final
project so now we're finished all the
features that we're going to do in this
lesson let's go back to our JavaScript
and I'm just going to move it back up
here
and let's clean up this code by removing
these console.
logs and
save and finally let's check git one
more time to see the changes that we
made so we can expand this and go to the
git
section if we click amazon. HTML it will
tell us we added this class and if we
click amazon. JS it will show us the
code that we added for C calculating the
card quantity and putting it on the
page so finally let's type a message to
describe our
changes make the cart quantity
interactive and
commit so now we can close
this and that's the end of this lesson
in this lesson we started the final
Amazon Project
we set up and learned how to use git to
track changes we learned the main idea
of JavaScript which is save the data
generate the HTML and make it
interactive we created a list of
products on the homepage we made the add
to cart button interactive and we made
the cart quantity
interactive thanks for watching this
course so so far if you want to support
this channel you can check out the
premium version of my courses just like
this one where you can get a certificate
of completion and a Better Learning
platform if you're interested in extra
videos from me more in-depth videos and
behind the scenes content you can check
out these links here you can also
support the channel by liking the video
subscribing and sharing this video with
others thanks again and let's continue
with the course
here are some exercises to help you
practice what we learned in this lesson
in this lesson we're going to learn a
feature of JavaScript called modules
which is a better way to organize our
code so first let's take a look at a
problem that we have in our current code
we're going to go to our files here and
we're going to open amazon.
HTML and then we're going to scroll to
the bottom of this file to our script
tags so right now we're using three
script tags to run all of our
JavaScript so this runs all the code in
cart. JS and then it runs all the code
in products. JS and finally it runs all
the code in amazon. JS so this is
basically the same thing as combining
all the files together into one big file
and then running all of our code however
there's a big problem with using script
tags like this and that problem is it
can cause naming conflicts so in our
situation here we created a variable
named cart in cart. Js
this means we can't use the variable
name cart in any of our other files so
for example if we went to amazon.
JS and then we scroll to the top
here and let's say that we try to create
another variable named cart so at the
top we type const cart equals square
brackets and
save and now if we go back to our
project you'll notice that the website
stops working and if we rightclick
inspect and open the
console it will tell us that we got an
error and it says that cart has already
been declared so this is happening
because we created a variable called
cart in cart. JS and then later in
amazon. JS we created another variable
named cart now we can't have two
variables with the same name in
JavaScript and this causes an error and
it causes our website to break so this
is called a naming conflict when we have
two variables with the same
name so the big problem with script tags
is if we go back to our
code you can see here that it's really
hard to tell which variables have been
created in other files and it's really
easy to accidentally create a naming
conflict like this so that's the problem
with using script tags like this and
running our code one file at a time it's
very easy to get naming
conflicts so now we're going to learn
how to solve this problem using a
feature of JavaScript called
modules so a module basically contains a
variable inside a file so now this
variable is not going to cause conflicts
with anything outside the file for
example in our project we created a
variable called cart and we want to
contain this variable inside the cart.
JS file so that it doesn't conflict with
the cart variable inside the amazon. JS
file so we can do this using a module so
now let's learn how to create our first
module we're going to go back to amazon.
HTML and then here to create a module
we're simply going to delete this line
of code that uses a script tag to load
cart. JS so we'll delete it and
save and you'll see that the website is
working again so how does this work when
we use a script tag it will run all the
code inside cart. JS so this code will
create a card variable and this will
cause a naming Conflict by removing the
script tag we're no longer running the
code inside cart. JS so we're no longer
creating a cart variable and it will no
longer cause a naming
conflict so to create a module we simply
do two steps number one we create a file
and write our code inside the file and
number two don't load the file with a
script tag by doing this any variables
we create inside the file will be
contained inside the file and it won't
cause naming conflicts so that's
basically how we create a
module okay so now we run into another
problem in our code if we open amazon.
JS we created this card variable as an
example but what we actually want to do
is to keep the cart variable inside
cart. JS because we want to keep all the
code that's related to the cart inside
this file so in
and if we
save and then go back to our project and
click add to cart you'll notice that it
no longer works so let's look at the
console again to see what error we get
we'll right click
inspect and open the
console and it's going to tell us that
cart is not defined so the problem that
we have here is that in this file we're
using the variable cart but now because
we're not loading cart. JS using a
script tag the cart variable doesn't
exist anymore it's contained inside
cart. JS and we can't access it from the
outside so now we're going to learn how
to get a variable out of a file or a
module to do that we're going to do
three steps the first step is to add a
type equals module attribute the second
step is to export and the third step is
to import let's learn these steps one by
one so the first step is to add a type
equals module attribute we're going to
open amazon.
HTML and we're going to scroll to the
bottom and here in the last script tag
where we load amazon. JS we're going to
add an HTML attribute here so we're
going to type type equal equal module
and
save so the type equals module attribute
basically lets this file get variables
out of other files it basically enables
this feature now the second step is to
export so we're going to go to cart.
JS and now we're going to choose which
variables can be accessed outside of
this file so for example we want to
access the VAR variable cart outside of
this file to do that in front of the
variable we're just going to type the
word export and space and save so now
this variable can be used outside of
cart.
JS the last step is to
import so we're going to go to the place
where we're going to use this variable
which is inside amazon.
JS and now at the top we're going to
tell the computer which variable we want
to get from another file so we'll type
import open curly bracket close curly
bracket and between these brackets we're
going to give the name of the variable
we want to get which is the cart
variable and then we'll tell the
computer which file we want to get this
variable from so we'll type
from single quotes and and
semicolon and now inside these quotes
we're going to locate the file using a
file path so let's open up our files
here so it's easy to see what files we
have so right now we're in amazon. JS
and we want to locate cart. JS so the
first step is we actually need to get
out of the scripts folder we're in the
scripts folder and we need to get out of
it and into the data folder so to get
out of the current Cent folder that this
file is in we're going to type dot dot
so dot dot basically represents the
folder outside of this current folder
which is this folder right here
JavaScript Amazon projects and then
we're going to type a forward slash to
go outside of the scripts folder so now
that we're outside of this folder we're
going to go into the data folder so here
we're going to type data and then a
slash to go into this folder and we're
going to locate the file cart. JS
C.J and
save so what this code does is that it's
going to take the variable cart out of
the file cart. JS and we use this file
path here to locate that file so as a
reminder dot dot means to go outside of
the current folder outside of scripts
into here and then we go into the data
folder and then inside the data folder
we find cart.
JS so those are the three steps to get a
variable out of a module first we add a
type equals module attribute to enable
this feature and then we export the
variables that we want to get out and
finally we import the variables when we
need
them now there's two more things that we
need to know about modules number one we
have to put all of our Imports at the
top of the
file and number two in order for modules
to work we need to use live server so
for example if I open the folder that
contains amazon.
HTML so I open JavaScript Amazon Project
and then I select this HTML file and
rightclick open with Google
Chrome the website won't work and that's
because modules don't work if we open
the HTML file directly like this so
let's close this for
now and to get modules to work we need
to open our code editor and then
rightclick the HTML
file and open with live
server so in this course in order for
modules to work we need to use live
server to open our HTML files
so now that we learned how to use a
module let's talk about the benefits of
modules the first big benefit is that it
helps us avoid naming conflicts the only
time that this causes naming conflicts
is if we import this variable and we
have another variable named cart inside
this file like
this so this will again create a naming
conflict if I save this the website will
stop working but at least now we have
control over when naming conflicts
happen they will only happen if we
import the same variable name now
modules have another feature that allows
us to avoid this problem as well so
after the variable name that we import
we can type as and then a different name
such as my cart and save so this will
basically take the input and rename it
to my cart so that this will no longer
conflict with this variable name so as
you can see modules have a lot of
features that help us avoid naming
conflicts when we have lots of files in
our project so now I'm just going to
delete this and put the code back
because that was just an example and
save so the second big benefit of
modules is that we don't have to worry
about the order of our files
before when we loaded everything with
script tags we had to make sure that we
load C.J first because we need the cart
variable to be created and then we can
use it in amazon.
JS so the order of our script tags
really matter and it becomes really hard
to manage when we have lots of files in
a big
project but now with modules we can just
import the variables that we need and we
don't have to worry about the order that
we're loading our
files so as you can see modules are a
better way to organize our code
especially in bigger projects so now
let's use git and save our changes so
we'll go to the git section here and it
will tell us we changed three files in
amazon. JS we removed the script tag and
added type equals module in cart. JS we
exported the cart variable and in
amazon. JS we imported the cart variable
from cart. JS so now let's save these
into get so here we'll type a message
use
modules and import cart from cart. JS
and
commit now that we learned modules let's
use them in more places in our project
so let's close this for now and we're
going to open amazon.
HTML and next we're going to turn
products. JS into a module as well so
we'll start off by deleting the script
tag because the script tag will just
load all the code onto the page so we'll
delete this and
save so notice that our website stops
working and now inside amazon. JS we
need to to access products from
products. JS so again we're going to do
three steps the first step is to add a
type equals module attribute which we
already have so we don't need to do this
again the second step is to export the
variables that we want to get out so in
this case we want to get the products
variable out of the products. JS file so
let's open our files and open products.
Js
and we'll scroll to the
top so to get the products variable out
of this file in front of the variable
we're going to type export and space and
save and the last step is to import the
variable that we need so inside amazon.
JS we need the products variable so at
the top we're going to type
import curly brackets
and then inside here we're going to type
the variable name that we want to get
which is
products and we're going to get this
variable from single quotes semicolon
and then inside here we're going to
locate the products. JS file so we're
going to type dot dot and slash to go
outside of the current folder so outside
of the scripts folder and then we're
going to go into the data folder so type
data and a slash to go into the folder
and we're going to locate the file
products. JS and
save so now that we're importing this
variable from this file the rest of our
code will work and our website will
start working
again so that's how we turn products. JS
into a module as well so let's go into
get and take a look at our
changes so in amazon. HTML we deleted
the script tag and then in products. JS
we exported the variables that we wanted
to get out and then in amazon. JS we
imported the variables that we need from
the
file so let's type a message and save
these changes into git import products
from products. JS and
commit let's close
this and let's open amazon.
HTML now the last thing is you might be
wondering should we also delete this
script tag that loads amazon. JS and the
answer is no because we still need one
Javascript file to load our code so this
file will import from all the other
files that we created
and this is how we organize our code in
a real
website so this file is called the entry
point so now that we've seen some
examples of modules we're going to use
modules to organize our code better so
let's go into amazon.
JS and then we're going to scroll down
to the code for the add to card button
so inside this file we're going to
scroll down here all the way down to
this code here so this is a code that we
run when we click add it to cart and
you'll notice that we're running a lot
of code here when we click that button
we're running code that adds the product
to the cart and we're also running code
that calculates the quantity and updates
the page so a best practice in
programming is that when we have a lot
of code here that does different things
it's better to split these up into
smaller functions to make our code
easier to read so here this part of the
code takes the product ID and then adds
it to the cart so it makes sense to
split this into its own function so
let's scroll up and at the top here
let's create a function for this code so
we'll type function and let's call it
add to cart brackets and curly brackets
and then we're just going to move all
this code into the function so we'll
select this
code and then
rightclick
cut and then inside this
function rightclick and
paste and then down here we're going to
run this function inside here so when we
click add to cart we're going to run add
to cart function that we just created
and Save
so now let's give this a try so we'll
click add to
cart and unfortunately it doesn't work
anymore so let's take a look at the
console to see if there's any errors
we'll rightclick
inspect and then open the
console and it's telling us that product
ID is not defined so if we look at our
code
here and scroll up in the function
you'll notice that we're using product
but it's no longer anywhere in the
function and that's because product ID
is outside the
function so we actually want to keep
this code outside because it's using
this button so instead we're going to
take product ID and put it into a
function using a parameter so at the top
of the function we're going to add a
parameter product
ID and then when we call this function
we're going to pass it the product
ID so we're going to take this value put
it into the function and save it in here
and then the function can run as normal
so now if we save and then go to our
project and click add to cart you can
see that it's working
again next let's go back and scroll
down and we're going to put the rest of
our code into its own function as well
to make it more organized so at the top
here let's create some new lines and
create a
function and this code updates the card
quantity on the page
here so let's name this function
update cart quantity brackets and curly
brackets and we'll move this code into
the function so let's select this code
and then rightclick cut and then in here
rightclick and
paste and then down here we'll call the
function using update cart quantity and
brackets and
save so as you can see by splitting up
our code into smaller functions it makes
our code a lot easier to read when we
click add to cart it's really easy to
understand what's going on first we're
going to add a product to our cart and
then we're going to update the card
quantity so now let's save and then go
back to our project and try it out and
you can see that everything is working
again so we're going to do two more
things to better organize our code so
let's go back to our code and the first
thing is we're going to scroll up to the
add to cart function and I made a small
mistake in the previous lesson I
actually want to rename this parameter
from item to cart item instead to make
it a little more clear so we're just
going to rename this to cart item and
here as well we name it to cart item and
save and we'll scroll down here and
we're going to do the same thing for
this parameter so we'll rename it to
cart item and then here cart item and
Save
and the last thing we'll do is let's
scroll up to the add to cart
function so you'll notice that this code
manages our cart so it's actually a best
practice to move this function into
cart. JS because cart. JS contains all
the code that's related to the cart a
best practice is to group related code
together into its own
file so here let's take the function add
to cart we'll select it and then
rightclick
cut and then inside cart. JS we're going
to rightclick and paste and just move
that function into this file because
this file contains all the code that's
related to the cart so now that this
function is inside the file we need to
access it from amazon.
JS and we can do that using modules
using the features export and import so
inside cart. JS in front of the function
we're going to export it so we can use
it in other files so let's save this
file and then inside amazon. JS we're
going to scroll to the
top and you'll notice that we're already
importing something from cart. JS so we
actually don't need to write import
again here we can actually import
multiple things from this file by typing
comma and space and then something else
that we want to import so in our case
we're going to import the function add
to cart so here we'll type comma add to
cart so now it will import both the cart
and the add to cart function from this
file so Imports can import multiple
things from a
file Imports have another syntax import
Star as this Imports everything from a
file and groups it together inside this
object and then we can access each
import as a property or a
method so lastly I'm just going to
scroll down to my code
here and I'm just going to remove this
extra new line and
save now you might be wondering if we
should move update cart quantity into
cart. JS as
well so this function actually handles
updating the web page rather than
managing the cart so we're going to keep
this function inside this file for
now so now let's go into get and save
our changes so we'll go here and inside
cart. JS we moved the add to cart
function and then we exported it and
then inside amazon. JS we imported the
add to card
function and then down here we took the
big block of code that we had before and
we separated it into two functions add
to cart and update cart quantity and
this made our code a lot easier to
read so now let's type a message
describing our changes move add to cart
into cart. JS and commit
next we're going to create the checkout
page in our final project and we're
going to use modules to organize our
code again so let's open the final
project and we're going to click this
cart icon in the top
right and this will take us to another
page which is the checkout page so on
this page we can see the products that
are in our
cart so if you're wondering how that
cart icon works it basically uses is an
HTML element called a link element which
looks like this link elements have a
special attribute called href when we
click a link element whatever is inside
the href attribute it will open it in
the page so if we put youtube.com inside
the href and we click the link it will
open youtube.com in our browser if we
put a file like checkout. HTML inside
href it will look for a file called
checkout. HTML and open that
file so in our project if we look at our
code and open our
files inside amazon.
HTML we're basically just using a link
element or an a element and this has an
hre of checkout. HTML so what this does
is it's going to look for a file called
checkout. HTML beside the current file
amazon. HTML so here's amazon. HTML and
it's going to look for checkout. HTML
beside it and then open that in our
browser which is how that cart icon
works so in our browser at the top you
can see that it opened checkout. HTML so
that's basically how a link element
works and how we can navigate from one
page to another you can learn more about
link elements in my HTML and CSS full
course but for now now we're going to
learn how to build the checkout page
using
JavaScript so first let's take a look at
the code for this page so again the code
is inside checkout.
HTML so in our code editor we're going
to open checkout.
HTML and this is a code for the page
that we saw earlier that contains our
cart so just like with the homepage
instead of writing all this HTML
manually we're going to use JavaScript
to generate this
HTML so first we need to add JavaScript
to this page so let's scroll down to the
very bottom
here and right before the end of the
body we're going to create a script
element to load some
JavaScript and we'll give it an
attribute Source equals double quotes
and then a file we want to load so let's
create a new Javascript file file for
this page so inside our scripts folder
let's click amazon. JS and then click
this icon to create a new file and let's
name this file checkout. JS and press
enter and now we're going to load this
page inside checkout.
HTML so here in the source attribute
we're going to locate this file so first
we need to go into this scripts folder
so we'll type
scripts and then a slash to go into the
folder and then we'll load the file
checkout.
JS and next we're going to add another
attribute type equals double quotes
module so remember from earlier in the
lesson this attribute enables module
features for this file so now this file
can import from other JavaScript files
so now let's
save and let's open checkout. JS and
we'll start creating this page with
JavaScript so let's go back to our page
first and take a look at the structure
of this page so you can see on this page
we actually have two sections we have
the cart section on the left which shows
the products in our cart and we also
have the payment section on the right
which calculates the cost of our order
so let's use JavaScript to create the
cart section first so remember the main
idea of JavaScript is first we're going
to save the data and then we're going to
generate the HTML and finally we'll make
it
interactive let's start by saving the
data that we need for this section of
the page so for this section we're
basically displaying a list of products
along with the quantity of each product
that we want to buy and and if you
remember we already created a data
structure to represent this which is our
cart inside our cart we have the ID of
the product as well as the quantity that
we want to buy so we can just reuse this
data structure to create this section so
let's go into our
code and we're going to open cart.
JS so inside here we have an array
called cart that's supposed to represent
our data here
so right now our card is empty so to
make it easier for us to develop we're
just going to add some default values
into this array so inside here let's
create an object and put one product
into our card first so looking at this
page the product that we want to put is
the socks so we'll go back into our code
and I'll rearrange my windows so we can
see it side by side and we're going to
get the product ID for the socks here so
we're going to go into products.
JS and then here's the socks we just
going to take this
ID right click
copy and then inside the
cart and remember we structured our data
so that each card item has a product ID
as well as a
quantity so here we're going to create
the same structure that our current code
uses
so we're going to give each object a
product ID colon and single quotes and
we're just going to rightclick and
paste the ID that we copied earlier and
then we'll type a comma and we'll give
it a
quantity colon and for the first item
we're going to give it a quantity of two
so we'll just create a cart that kind of
matches what we see on this page
next let's create a second card item to
represent the basketball so we'll type
comma curly brackets we'll give it a
product ID colon and single quotes and
then we're going to get the ID for this
basketball so inside products. JS we
going to scroll down to the basketball
here and we're going to copy this
ID right click copy
and then inside cart.
JS in here right click and
paste and we'll give this one a
quantity colon one and
save so what we're doing here is we're
just creating some default values that
we can use to write the code to generate
this page so this is just for
development when we're actually using
the website the cart will start off as
empty so so if we compare our data to
our page you might notice that there's a
few things that are missing such as the
product's image the name and the price
so how come we're not saving these into
our data and that's because we're using
a special technique we're just saving
the product's ID and then we can use
this ID to search for this product
inside the products array here so using
the ID we can find all the other details
of the product like the image the name
and the price so there's no need to save
this data twice inside the products
array and inside the cart array all we
have to do is save the ID of the product
that we want and then search for it so
this technique is called duplicating the
data or normalizing the data and this is
a very common technique in software
engineering okay so the one other thing
that we probably need to save in our
data is the delivery times and the
delivery options but we're going to
leave this for the next lesson because
it requires some more features that
we're going to
learn so for now we finished saving the
data that we need the next step is to
use this data to generate the
HTML so let's open checkout.
JS so I'm just going to drag it to the
bottom here so we can see it side by
side
so the first step we need to do is to
take the cart array and import it into
checkout. JS so we can use it so in here
let's import curly brackets the cart
array and we're going to import it from
single quotes and semicolon and we're
going to use a file path between the
quotes to locate cart. JS so let's open
our files again and to get from here to
here we need to go out of the scripts
folder so to do that we can type dot dot
and then slash to go to the outer folder
and then we're going to go to the data
folder so we'll type data slash to go
into this folder and we'll locate cart.
JS so cart. JS and save and next we're
going to Loop through this cart and
generate the HTML just like we did for
the
homepage so let's close this for now and
here we're going to create a loop over
the cart so we'll type cart. for each
brackets and a
function and then we'll give it a
parameter let's call it cart
item and then for each cart item here
we're going to generate this
HTML so in here let's create a template
string for the HTML using back ticks and
we'll create some new lines and then
here we're going to copy and paste the
HTML for one of these products so first
let's find the HTML for one of these
products and to do that we can
rightclick
inspect and then click this top left
icon and then click the element we want
to get the HTML
for so here's the HTML for one of these
products and we're going to search for
this class card item container and our
code so inside our
code let's open checkout.
HTML and we'll type control F or command
F to search for code and we'll search
for the class cart D item D
container which is this code right here
so if we collapse it and collapse this
this is the code for these two products
here so we're going to take this HTML
and we're going to move it into our
JavaScript so we can generate it with
JavaScript so we'll right click
copy and then in here right click and
paste and if we need to fix the
formatting we can select all of these
lines and then press shift tab to remove
some indents
and I'll add an indent here next when
we're generating this HTML we want to
replace this with the actual products
image and this with the actual products
name so we're going to take this card
item and use it to get the data that we
need so let's open card. JS to see what
each cart item looks like so we have the
product ID and the
quantity so first we need to use this
product ID to search for the product in
order to get the other details like the
image the name and the
price so to do that let's get the
product ID out of the cart item first so
we'll create a variable const product ID
equals the cart item do product
ID and now we need to use this to search
for the full product so the full product
if we open our files is INS inside
products.
JS which is this array right here so I'm
just going to move this up here so we
can see it side by
side so to search inside this array we
actually need to import products into
checkout. JS so let's use some module
features again at the top we'll import
curly
brackets the products array and we'll
import it from single quotes and
semicolon and then here we'll locate the
products. JS file so we'll type do dot
slash to go out of the scripts folder
and then we'll go into the data folder
data and then a slash to go into this
folder and we import from products. JS
so
products. JS and save so now we have
access to this products array here and
we'll search the array for the full
product details so down
here let's create a variable to save the
result so we'll type let and we'll name
it matching
product and then down here we'll Loop
through the products array so we'll type
products. for each brackets and a
function and then we'll give it a
parameter
product and now for each product here
we're going to check if the ID property
is equal to our product ID here so down
here we'll check if the
product. ID property is equal to our
product ID up here and then if they're
equal that means we found the matching
product and we're going to save it in
this variable so matching
product equals this product that We're
looping
through so now that we have the matching
product we have access to the image the
name as well as the price that we can
use to generate this HTML so this is a
good example of duplicating or
normalizing our data so now at the
bottom let's
console.log our matching product to see
if it works so matching
product and
save now if we go into our project and
we rightclick inspect and check our
console you can see that we were able to
get the full product details for each of
these products using the product ID so
now that we have the full product
details we can use this to generate all
this HTML
so down here instead of generating the
same image every time we're going to use
the image in the matching product so
let's get rid of this
code and here we're going to remove this
and we're going to substitute using
dollar curly
brackets the matching
product.
image and we'll scroll down and instead
of the same product name every time
we're going we're going to replace this
and we're going to substitute the
matching
product. name so each time we're going
to generate HTML with a different image
and a different name and down here the
same thing remove the price and we'll
replace it with matching product Dot and
then we'll just check here what the
property is it's called a price sense
and remember this is in
and to display it as dollars we have to
convert it by dividing by 100 and
save and lastly we're going to replace
the quantity here so if we scroll down
we can see that this is the quantity so
instead of two every time we'll
substitute and for the quantity remember
it's not part of a product it's part of
our cart so each cart item has a
property called called quantity so down
here we're going to substitute the cart
item.
quantity and
save so now we're generating all this
HTML by looping through our cart so the
next step is we're going to combine all
this HTML together and then put it on
the page so I'm just going to move this
up here so we can see more of the
code so to combine all this HTML
together let's create a variable up here
to store the result so we'll type let
and let's call it the cart summary
HTML equals an empty string and now each
time we Loop through the cart we're
going to add this HTML up here so that
we combine it so here we'll type cart
summary
HTML Plus
equals this HTML that we
generated and at the bottom I'll just
add a
semicolon and then let's console.log the
cart summary
HTML
console.log cart summary HTML to make
sure that it worked so we'll save and
then in here we'll check the console
right click
inspect the console
and now you can see that we generated
the HTML and each cart item is different
depending on the product that is being
displayed so that's how we generate all
the HTML for this section and the last
step is to take this and put it on the
page using the Dom so first we need an
element that we can put the HTML inside
of to find this element let's rightclick
inspect and click the top left left and
click one of these
products and let's find this order
summary element because this contains
both of our products here so we're going
to replace all the HTML inside here with
what we generated so let's search for
the class order summary in our code so
we'll go back to our code and let's open
checkout.
HTML and we'll type contrl f or command
F to search for code and we'll search
for the class
order-
summary and then it's right
here and we're going to add a class so
we can select it using the Dom so js-
order- summary and
save so now let's use the Dom and put
this element in our JavaScript so inside
here at the
[Music]
bottom we use
document. Query select VOR
brackets and the class we just
created js-
order-
summary and we'll use the property.
inner Capital
HTML and we'll change the HTML to cart
summary
HTML and we can remove this
line and now if we
save we're basically generating all this
h HTML with JavaScript and then putting
it on the page so now we can go back to
checkout.
HTML and we can actually remove the code
inside this order summary so we can
delete this
code and save and everything will still
work because this is now being generated
by
JavaScript so that's how we create the
cart section of this page with
JavaScript let's go into get and save
our changes so we'll open the git
section and then it will tell us that we
changed three files in checkout. HTML we
removed all the HTML that was written
manually and then at the bottom we
created a script tag to load our
JavaScript and then we also changed
cart. JS and added some default values
to work with and then we created
checkout. JS which loops through the
cart creates the HTML and puts it on the
page so let's create a message to
describe our
changes generate
HTML for the order summary and
commit next let's open our project
again and before we continue we actually
have two issues that we need to fix the
first issue is that the price is
displaying as one decimal here instead
of two and the second issue is that
these delivery options are actually
shared between the two products for
example if I click this delivery option
here it will actually unselect for the
second product so they're sort of shared
between the two
products but what we actually want is
for each product to be able to select
its own delivery options so we're going
to fix these two issues
next first let's focus on the price and
we want to display it in two
decimals so we actually learn how to fix
this on the homepage using the method to
fixed so we're going to use the same
code here let's go into our
code and we'll open our files and let's
open checkout. JS
again so here we're going to scroll down
to where we display the
price which is here price sense and to
show this in two decimal places we're
going to surround this with brackets to
make sure we calculate it
first and then use the method
do2 fixed brackets and then two to show
two decimal places if we save and then
open our
project now the price is displaying
correctly before we move on we're going
to learn how to better organize this
code so if we go
back so notice that we're using this
code inside the checkout page as well as
inside amazon. JS which is the homepage
so we can actually share this code
between the two files so we don't have
to repeat it and to do that we can use
modules so let's open checkout. JS again
and what we'll do is we're going to
create a function that does the same
thing as this code and then we can share
this function between the two files so
let's create a file that's going to
contain this shared function so we're
going to go to our scripts folder here
and inside we're going to create a new
folder this time and let's call this
folder
utils and press
enter so we're naming it utils because
this code is sort of like a useful
utility that we want to
share now inside this folder we're going
to have different types of utils so
let's create a new
file and let's name it money. JJs so
this file is going to contain utilities
that are related to money which is this
code right here so let's press
enter and I'm just going to move this to
the bottom so we can see it side by
side so now inside this UIL file we're
going to create a function that does the
same thing as here and then we can share
it between the two
files so here we'll create a function
and let's name it format currency
because that's what this code is doing
and then brackets and curly
brackets so this function is basically
going to do the same thing as here so
we're going to add a parameter here
price sense
because we want to use this function for
any amount of price
sents and then in here we're going to do
the same thing which is price sents
divided 100 and then we're going to
surround this with brackets to make sure
we calculate this
first and then display it in two decimal
places using dot 2 fixed brackets and
two and finally let's return this result
return and
save so what we just did is we created a
function that does the same thing as
this code here and now we're going to
share this function between checkout. JS
and amazon. JS so first in order to
share it we need to export this function
so at the front we're going to type
export and
save and now inside each of these files
we're going to to import this function
and use it so let's scroll to the
top and here we're going to import curly
brackets we're going to import the
function format
currency and we're going to import it
from single quotes and
semicolon and then inside here we're
going to locate the file money. JS so
here we're in the checkout. JS file
which is right here and to go here we're
first going to go into the UTS folder so
we're going to Type U toils and then a
slash to go into this folder and we're
going to locate the file money. JS so
money.
JS now for modules we have to do one
extra thing at the front of this file
path we need to type dot
slash so remember that dot dot
represents the folder outside the
current folder so for checkout. JS if we
go outside of this folder we're going to
go outside the scripts
folder now a single dot on the other
hand means the current folder so this
dot means we're going to go into the
current folder which is the scripts
folder and then we're going to go into
the utils folder and then we're going to
go and locate money.
JS so for modules if we want to start in
the current f folder our file paths have
to start with Slash so that's one extra
thing that we have to do so now that
we've imported the format currency
function let's use it in the rest of our
code so we're going to scroll
down to here and instead of writing this
all over again we're just going to use
the function format
currency and then brackets and we're
going to remove the rest of the code
here and and close bracket and
save so we're basically running the same
code except we're using this shared
function that's located in another file
so let's open our
project and we can see that the price is
still displaying
correctly so now let's go back into our
code and we're going to share this
function inside amazon. JS as well so
let's open amazon.
JS and then we'll scroll to where we
show the price which is here and we're
going to use this function again so
first we have to import it so we'll
scroll up to the top and import curly
brackets we'll import the function
format
currency and we'll import it from single
quotes semicolon and then here we'll
locate the file money. JS so remember
for module if we want to start in the
current folder we have to type slash and
then we're going to go to the UIL folder
so utils and then a slash to go inside
the folder and locate the
file money.
JS and now we're going to use this
function so let's scroll
down and we're going to replace this
code and use format currency and
brackets so we can remove the rest of
the code here and
save and now let's look at our
project and we'll click up here to go
back to the
homepage and you can see that the prices
are displaying as two decimal
places and that's it if we look at our
code again we're essentially taking this
function and sharing it across two files
using modules so using modules we can re
use a lot of our code and reduce
repetition next let's work on the second
issue that we saw earlier so we'll go
back to our project and click the top
right to go back to the checkout page
and then here the delivery options are
shared between the two products but we
want each product to choose its own
delivery
options so to fix that let's go back
into our code and just going to resize a
here so we can see it side by
side and we'll open checkout. JS again
and we can close this for
now so this is an HTML element called a
radial selector and here's the code for
a radial selector so the way that radial
selectors work is that if a set of radio
selectors have the same name then we can
only select one of them so for example
if these three radio selectors have the
same name attribute then we can only
select one of them now if the three at
the top have one name and the three at
the bottom have a different name then we
can select one from the first three as
well as one from the second
three now what's the problem with the
radial selectors here well let's take a
look at the code for these selectors to
do that we're going to rightclick one of
them and then
inspect and then click the top left and
click one of these selectors to get the
HTML code so here we have the code for
the radio selector and you can see that
the name of the selector is delivery
option one and now if we click the top
left again and find one of these bottom
selectors you'll notice that these also
have the name delivery option one so all
six of these have the same name at
attribute that's why we can only select
one of these six at a time so what we
actually want to do is we want the first
three selectors to have one name and the
second three selectors to have a
different name so let's figure out how
to give these a different name so inside
the console we can see the code for this
selector and we have a name attribute
delivery D
option-1 so let's actually find this
name in our code so we'll go to our code
editor and contrl F or command F to
search for code and we'll search for
delivery Das
option-1 and if we scroll
down you'll notice that every time we're
generating these radio selectors we're
always using the same name delivery
option one so every product is going to
have the same name for the radio
selectors and all of these are going to
be shared so what we actually want to do
is instead of using the name delivery
option one every time each product is
going to use a different name for these
three
selectors so one way we can do that is
instead of the number one every time we
can replace it with the product's ID
because the ID is always unique for each
product so let's substitute using dollar
and curly
brackets the product
ID and then down here as well instead of
using the name one every time we're
going to
substitute
product. and
actually we use the name matching
product so we'll scroll down and just
update this to matching
product and then down here matching
product and and as well down here
instead of one every
time substitute the matching product. ID
and
save so now these three radial selectors
will have a different name attribute
than these three radial selectors that
means we can select one out of these
three and we can select one out of these
three so that's how we fix that error
instead of using the same name delivery
option one every time we're going to
generate a name using the product's ID
so let's go into get and save our
changes so in amazon. JS we imported
this shared function and we used it to
format the price in two decimal places
and then in checkout. JS we also used
the shared function
here and we fix the radio selectors
and then in this file
moneyjar
function so let's create a message to
describe our changes fix price
formatting and radio
selectors and
commit the last step in our process is
to make it
interactive so I'm just going to close
these for now
and going to move it to the right again
so we can see our
project and for the order summary
there's a few things we can make
interactive for now we're going to start
with this delete link when we click this
link it should remove this product from
the cart so we're going to learn how to
build
this so let's go back to our code and
first let's add event listeners to all
of these delete links to do that we're
going to find the code for these delete
links so we'll rightclick
inspect and then in here this is the
code so we're going to search for this
class in our code editor delete quantity
dlink so in here let's open checkout. JS
and we're going to contrl f or command F
and search for delete - quantity
dlink which is right
here next we're going to add a class to
these elements so we can add event
listeners so at the end here let's add a
class
js- delete
daslink and
save and then at the bottom we're going
to scroll down and then out here we're
going to add the event
listeners so first we're going to select
all the delete links on the page using
document. query selector all brackets
and then a string and we're going to
select a class using Dot and the class
js- delete
daslink and then we're going to Loop
through all these links so dot for each
brackets and a
function and and in here it will give us
the link every time and then for each of
these links we're going to add an event
listener so
link.
addevent
listener
brackets and here we're going to give a
string and the event we want to listen
for which is a
click and then a function that we want
to run when we click these links so for
now let's just
console.log string delete to make sure
that it's working so we'll save
this and then in here we click these
delete links and then open the console
right click
inspect
console we can see that it's working now
so now let's go back to our
code so when we click delete we're going
to do two steps the first step is we're
going to remove the product from the
cart and the second step is we're also
going to update our HTML and remove the
product from the page so let's start
with the first step so when we click
delete how do we know which product we
need to remove from the
cart so we learned how to do this for
the added to cart button we can attach
the product's ID to the link element so
let's scroll up again to where the
delete link is which is right here and
we're going to attach the products ID to
this element using a data attribute so
at the end here we're going to add
data-
product-id equals double quotes and then
here we'll
substitute the matching
product. ID and
save and now that we attached the
product ID to this element we can get it
in our JavaScript below so let's scroll
down and then here we're going to delete
this line and using the link element we
can get that product ID using link. dat
set to access the data attributes and
we're going to access product
ID and let's save this in a variable so
we can use it later so const product ID
equals this
value and let's
console.log this to see if it
works and
save so now if we go to the project and
click the delete link for the first
product and then look at the console
inspect and console it will show us the
products
ID if we click the second products
delete link it will show us the second
products ID so now now we have the ID
that we need to remove from the cart so
now how do we actually do that so before
we begin figuring that out instead of
writing all the code down here let's
actually create a function inside C.J to
do this task the reason we're going to
do this is because cart. JS is supposed
to contain all the code that's related
to the cart so this will help us
organize our code better so let's open
our files again again and we're going to
open cart.
JS and we're going to scroll to the
bottom and we're going to create a
function for removing a product from the
cart so let's type function and let's
name it remove from cart brackets and
curly
brackets so this function we'll take a
product ID which we have and remove it
from the cart so here let's let's create
a parameter for the ID product ID and
now in here we're going to figure out
how to remove it so here's one way we
can do this first we can create a new
array and then we can Loop through our
cart and then add each product to the
new array except for this product ID so
now let's convert these steps into code
so inside this function here let's
create a new new array using const we'll
call it new cart equals an empty
array the next step is we're going to
Loop through our cart so we'll type
cart. for each brackets and a
function and we'll give it a parameter
cart item and the last step is that
we're going to add each card item to the
new array except if it has this product
ID so we can do that by checking if the
cart
item. product ID is not equal to the
product ID that we're looking for
product
ID so if it's not equal to the product
we're trying to remove we're going to
add it to the new cart so new cart. push
cart item
so the result of this Loop is it's going
to contain all the cart items that don't
match this product ID and that's the
same thing as removing this from the
cart so now the last step is we're going
to take our new cart and replace the
cart up here so we'll scroll
down and then here we'll make cart equal
to our new
cart because we're reassigning this
variable we have to scroll up and change
it from const to let and
save so now that we created this
function let's use it in our checkout
page first we're going to use the
modules feature and Export this function
and
save and then inside checkout. JS we're
going to import this function so I'm
just going to move this down to the
bottom so we can see it side by side
so here so in checkout. JS we're going
to scroll up and we're already importing
from cart. JS so we're just going to
import one additional Thing by typing
comma and we're going to import this
function remove from cart and
save and then we're going to use this
function at the bottom so we'll scroll
down and then here we're going to
remove from cart brackets and we're
going to give it the product ID we want
to remove so product
ID and lastly let's just console.log the
cart to make sure that this works so
console.log the card and
save so now let's go into our
project and we're going to click this
delete link for the first product so
delete and let's open the console right
click inspect the console and now it's
going to show us that we have one
product remaining in the cart and this
product has a quantity of one which is
the second product here so by clicking
that delete link We successfully removed
this product from the cart so now if we
refresh and tried clicking the second
delete
link and look at the
console and then EXP expand the cart it
will tell us that the remaining product
has a quantity of two which is this
product so we successfully removed the
second product from the cart when we
clicked
delete so now let's go into get and look
at our changes so we'll go into this
section well I can close this for now
and we'll open git and it will tell us
that in C.J we change it to let and we
created this new remove from cart
function and then in checkout. JS we
import that function and then at the
bottom when we click the delete link
we're going to remove this product from
the cart now finally we can remove this
console.log save and we're going to put
these changes into git so we'll type a
message to describe our
changes delete products from cart when
clicking
delete and
commit the second thing we have to do
when we click delete is to update our
HTML so if we go back to our
project when we click delete we want to
remove this product from the page so one
way we can do this is first we're going
to use the Dom to get the element we
want to remove and then we can use a
method called
remove so every element that we get from
the Dom has a method called remove which
removes it from the page so first of all
how do we know which element to get from
the page so let's actually look at the
HTML for one of these products we're
going to
rightclick
inspect and then click the top left and
then click one of these products
here and this will give us the HTML so
these two products are represented by
these two divs here with the class
cart--
container so one way to identify which
product this is for is to add a special
class to this element and this class
will contain the product
ID and then if we go back to our code
and we open checkout. JS and scroll to
the
bottom when we click delete we have the
product ID here so we can use this to
select that special class that we're
going to add so first let's add that
special class to each of these elements
so we're going to scroll up to the
HTML and we're going to go to the top
here to the div cart--
container and then here we'll add a
special class
js- cart Das item Das container Das and
then we'll substitute the product's ID
so we'll type the
matching
product.
ID and let's put this class on a
separate line so the line is not too
long now let's
save and now we're going to scroll to
the bottom and use our code to get this
class so we'll scroll to the
[Music]
bottom and here we're going to use the
Dom as well as this product ID to get
that special class that we just added
above so here we can type
document. query selector brackets and
then inside we'll type a string and
we'll select the class using a DOT js-
cart D item D container Dash and then
we're going to substitute the product ID
so because we want to insert something
in here we're going to switch this to a
template string using
backtick and now we can substitute this
product ID into this
string product
ID so by creating the string like this
we're able to select the specific
container that we need so now let's save
this in a variable so we can use it
later so const container equals this
result so for now let's let's actually
console.log this to see if it works
console.log
container and
save and then we'll go back to our
project so just move this
here and then in our project if we click
delete on the first product and then
check the console right click inspect
and the console you can see that we're
getting the correct element that we
should delete if we go out here and
click this delete link and check the
console you can see that this is also
getting us the correct element that we
want to
delete so now that we have the element
we want to delete the next step is to
use the do remove method so again every
element we get with the Dom has a method
called do remove which will remove it
from the page so if we go back into our
code down here all we have to do is type
out the element
container. remove and brackets and this
will remove it from the page if we
save and try it out so we'll go in here
we'll click delete on the first product
and it will remove it from the
page if we click delete on the second
product it will also remove it from the
page so that's it now let's refresh to
bring the products back
and that's how we make the delete link
interactive and remove the products from
the cart as well as from the
page so now let's save our changes into
git we'll go to the git
section and it will tell us that in
checkout. JS at the top we added that
special class which contains the product
ID and if we scroll down to the
bottom we created the string which will
get us these specific element that we
want to remove and then we use the do
remove method so now let's create a
message to describe our
changes delete products from
HTML when clicking delete and
commit the last thing we're going to do
in this lesson is we're going to add
local storage to our cart so if we go
back to our
project if we delete some products in
our cart and then
refresh notice that our cart goes back
to what it was before and that's because
right now if we look at our code and we
open cart.
JS our cart is just a variable and
variables are reset when we refresh the
page or when we go to a different page
so again if we go back to our project
and we go to a different Page by
clicking the top left so on this
homepage we can add as many products as
we want to our cart and if we go back to
the checkout page our cart will just get
reset to whatever it is here so that's a
problem with just using a variable to
save our cart it gets reset when we
refresh the page or we go to a different
page to solve this problem we're going
to use local storage to save our cart
so first let's create a function for
saving the cart to local storage because
we might want to reuse this code so down
here let's create a function we'll call
it save to storage brackets and curler
brackets and we're just going to save
the cart to local storage using local
storage do set item
brackets and set item takes two
strings the first string is the name of
whatever we want to save so we're going
to save our cart so we're just going to
call this the cart and then the second
string is the data that we want to save
so remember that local storage can only
save strings so to save our cart we need
to convert it into a string first and we
can do that using
json.
stringify brackets and then inside we're
going to give it the cart so this will
convert the cart into a string and now
we can save it in local storage so now
let's use this function whenever we
update the cart we need to save it to
local storage so it doesn't get reset
when we refresh the page so here when we
add it to the cart at the bottom after
we update the cart we're going to use
that function we created above save to
to storage and
brackets and also in the function remove
from cart so this function is also
updating the cart so after we update the
cart we're also going to save to storage
and brackets and
save so now whenever we update the cart
we're going to save it in local
storage the last thing we need to do is
at the top at the beginning of our code
we need to get the cart from local
storage instead of using this default
value so let's add some new lines here
to separate the code for a bit and here
we're going to get the cart from local
storage and we can do that using local
storage. get item and brackets so get
item takes one string and that is the
name of what we saved earlier which is
the cart so we're going to to give it
the string
cart so this will give us the cart that
we
saved however remember that local
storage can only save strings so it will
give us the string version of our cart
and we need to convert it back into an
array to convert it back to an array we
can use the code
json. pars and brackets and close
bracket the last thing we need to do is
when we first use the website we might
not have a cart in local storage so if
we don't have a cart saved local storage
will give us null so in this situation
if this value is null we want to give
the cart a default value which is this
value below so to give the cart a
default value if it's empty we can use
an if statement by typing if brackets
and curly brackets and then here we can
check if not
cart so if we don't have a cart in local
storage this will give us
null in this case not null will become
truthy and we're going to run the code
in this if
statement so if the cart is empty we're
going to make the cart equal this
default value below so let's just select
this code and we'll right click cut and
then in here right click and
paste and remove the extra line and
save so now if the cart is empty we just
give it a default value if we go back to
our project and try out our code so
let's delete the first product and
refresh the page notice that the cart
gets saved and the first product remains
deleted if we go to the homepage and we
add some new products
and then go to our
cart notice that our cart is saved
between pages so by using local storage
we can save our cart even when we
refresh the page or go between different
pages so that's all we're going to build
in this lesson so to clean up let's
delete all these products in the
cart and then go to the
homepage and we'll add back two socks
and one basketball which which is the
default value of the
cart let's go back to the checkout
page and now we're done with this part
of the page so finally let's save our
changes into git we'll go to the git
section and it will tell us that inside
cart. JS we're now loading the cart from
local storage when we open the page if
the cart doesn't exist we're going to
give it a default value and we created a
function to save the cart into local
store
stage so now let's add a message to
describe our
changes save cart in local storage and
commit and that's the end of this lesson
in this lesson we learned about modules
which is a better way to organize our
code we created the checkout page in our
final project we learned about HTML link
elements and radio selectors we made the
delete link interactive and we saved the
cart in local
storage here are some exercises to help
you practice what we learned in this
lesson e
in this lesson we're going to learn
about external libraries and we're going
to finish the checkout page in our final
project an external library is basically
just code that is outside of our
project so far we've only been using
Code that is inside our project like
these
files well a lot of developers write
JavaScript code and then put their code
on the internet and we can actually load
their code from the internet into our
project and use it we call this code an
external library because it's code that
is outside of our project Let's do an
example and load our first external
Library we're going to go to the video
description and we're going to click
this
link for the hello external Library
and it will open up a page that contains
JavaScript code so I actually wrote this
code myself and you'll notice that this
is just normal JavaScript code we create
a function called hello and it just
console.log hello so this is called an
external Library it's code that is
outside of our project so the cool thing
is we can actually load this code from
the internet into our project so let's
give that a try we're going to go to our
project and we're going to open
checkout.
HTML and we're going to scroll to the
bottom and above the script tag we're
going to add another script tag to load
some code so
script and we'll give it a source
attribute and then in here instead of
using a fth like we've done before we're
going to give this a a URL of a website
that contains JavaScript code so if we
go back to our
browser and here the URL of this page is
up here so we're just going to copy this
right click copy and then paste it into
our
code right click and
paste so now the computer will get all
the JavaScript code from this URL or
from this
page so it's going to get all the code
from this page and load it into our
project like normal code so let's save
and let's give this a
try so this code creates a function
called hello so let's try running this
hello function in our project we'll go
to checkout. JS and then scroll to the
top and then here let's just run the
function hello so hello and brackets and
Save
now if we go back to our
project go to the checkout page and
check the console right click inspect
and the console you'll see that it
displayed the message
hello so that's how an external Library
works it's just code that is outside of
our project and we can load this code
using a script tag like this we just
give it the URL of where this code is
located
so there's two things you might be
wondering about how come we put the
script tag at the top so generally we
load external libraries first and then
we can use the library in our own code
below and the second thing is how do you
put code on the internet like this to
learn this you can check out my video on
how to put a website on the internet
it'll show you how to put any file like
HTML CSS and JavaScript files onto a
website like this
this next let's talk about why we use
external libraries external libraries
let us share code instead of writing all
the code ourselves we can use code that
other people wrote and this helps us
save time and avoid duplicating work
right now we're loading a very simple
Library so let's load a more complex
library to show how we can save a lot of
time and work let's go back to our
project and go to the checkout
page here we have a section for choosing
a delivery option for this product and
you'll notice that each option has a
date so this is the date that the
product should be delivered by so the
way this works is that the cheapest
option here takes 7 days to deliver the
$4.99 option takes 3 days to deliver and
the
$9.99 option takes one day to deliver so
to get these dates here we need to do
three things first we need to somehow
get today's date in our JavaScript
number two we need to do calculations
with the date such as ADD seven days or
add 3 days and number three we need to
display the date in an easyto read
format like
this now we could try to figure out how
to do this ourselves by writing our own
code but this is going to be a lot of
work instead we can use an external
Library to help us work with dates so in
this project we're going to use an
external Library called DJs this is a
popular library that helps us work with
dates so first let's load DJs into our
project we're going to go to the video
description and we'll click this
link for the DJs external Library
and when the page opens you'll see a
bunch of random code here now you might
think that this is some special code but
this is actually just regular JavaScript
code that has been compressed so
basically all the extra spaces have been
removed and the variable names have been
shortened to one
letter we can press JavaScript code like
this because we need to load this code
from the internet into our project by
compressing it it makes this code
smaller so it will load into our project
faster so this compression process is
called minification or we Minify the
code okay so this is the code for the
external Library DJs now let's load this
code into our project we'll go back to
our
code and then go to checkout.
HTML and then here we're going to add
another script tag less than script and
the source
attribute and then here we're going to
give it the URL of the code we want to
load so let's go back to the code for
DJs and then up here we're going to
rightclick and copy this
URL and then inside our code in the
source attribute we're going to
rightclick and paste the
URL and
save so again this will take all the
code that's located on this page and
then load it into our
project now let's give it a try the DJs
external Library creates a function
called
DJs so we'll go to checkout. JS and then
at the top we're going to run the JJs
function and
brackets now make sure this is all
lowercase cuz that's the name that the
library used so now let's actually
console.log the result of this function
console.log
and
save and we'll go back to our project in
the checkout page we're going to check
our
console and you'll see that the DJs
function gives us an object and this
object represents the current date and
time so we know that DJs is working and
that's it we successfully loaded the DJs
external Library into our
project now let's learn how to use
DJs external libraries usually have a
documentation page that shows us how to
use the library we can find the
documentation Page by searching on
Google the library name like DJs and
then documentation or we can ask an AI
tool how to use the library to make
things easier in this video I'm going to
show you the features that we need and
you can go through the documentation
later if you want so earlier we said we
needed to do three things with the date
first we want to get today's date number
two we want to do calculations with the
date and number three we want to display
the date in an easyto read format DJs
helps us do all of these things so first
let's use DJs to get today's date
according to the documentation to get
the current date and time we can just
use the DJs function like
this so if we go back to our code
and that's what we have here we call DJs
and it gives us an object that
represents the current date and time the
second thing we need to do is to do
calculations with the date so for the
delivery options here we need to
calculate today's date plus 7 days or
today's date plus 3 days so again the
DJs Library can help us do
this so let's go back to our
console and look at the object that we
get back from DJs so this object
represents today's date and time and
this object also has a method called add
which adds a certain amount of time to
this date so this is what we need for
the project to calculate these dates
here let's go to our
code and first let's save this result in
a variable so we're going to remove this
and create a variable const today
equals
DJs and then down here we're going to
use the add method so we'll type
today. add and
brackets now the add method takes two
parameters the first one is the number
of time that we want to add so if we
want to add seven days we're going to
type seven and then the second parameter
is the length of time that we want to
add so if we want to add seven days
we're going to give it a string days so
this will add seven days to today's
date so let's save this result in a
variable const delivery date equals this
result and we'll console.log it to make
sure it's working correctly
console.log the delivery date and
save now if we go back to our project
and open the
console it will give us an object that
represents 7 days after to date or 7
days after when you're watching this
video so that's how we use DJs to do
calculations with the date it gives us
methods like add to add a certain amount
of time to the date finally we're going
to use DJs to display this date in an
easyto read format like
this so according to the document
this date object has another method
called format which will display the
date in an easyto read format so let's
go back to our
code and we'll remove the
console.log and we'll type delivery
date.
format and then inside these brackets
we're going to give this method a string
so this string tells DJs what kind kind
of format we want for the date so in the
documentation it has a table showing us
some special characters we can put into
this string for example if we want to
show the day of the week like Monday or
Tuesday we can type four D's into the
string and this will give us a string
where this text is replaced by the
actual day of the
week if we want to add a comma and a
space to this format we can just add a
comma and space and this will show up
directly in the result now let's say
that after this we want to show the
month according to the documentation to
show the month we can type for Capital
M's and it will replace this with the
month and finally we'll type a space and
according to the documentation if we
want to insert the day of the month into
the string we can type a capital D
so this method takes this date and
converts it into a string with this
format so now let's console.log this to
see what it looks like well
console.log and
brackets and
save and then go into our project and
open the
console and now you should see the date
7 days after today but displayed in an
easyto read format
so that's how we use the DJs external
library to help us work with dates and
as you can see it saves us a lot of time
and work we don't have to figure out how
to work with dates ourselves we can just
use someone else's code to solve this
problem so a best practice in
programming is when we need to do
something complicated try to find an
external Library first before writing
the code
ourselves to find external libraries we
can you can search in Google JavaScript
and then what kind of Library we're
looking for like date
Library we can also use an AI tool to
help us find external
libraries next we're going to learn how
to use external libraries and JavaScript
modules together right now if we look at
our code and go to checkout.
HTML we're loading these libraries using
script tags the problem with script tags
is that it runs this code directly on
the page and this might cause naming
conflicts for example the hello Library
creates a function called hello so if
something else is called hello in any of
our other code it might cause a naming
conflict a better way to load external
libraries is to use JavaScript modules
because a module will contain this code
inside a file and any variables that are
created inside inside the file will not
conflict with anything outside of the
file to use external libraries and
JavaScript modules together we're going
to use a special version of the library
called an esm version esm stands for
ecmascript modules ecmascript is just
another name for JavaScript so the esm
version of a library is just a version
that works with JavaScript
modules so let's do an example we're
going to go to the video description and
we're going to open the esm version of
hello.js so you can see that it's the
exact same code as before we're creating
a function called hello except this time
I just added the word export in front of
function so this turns the library into
an esm version and now it will work with
JavaScript modules so let's use the esm
version in our code we're going to go
back to our
code and we're not going to use script
tags to load this anymore so let's
delete
this and
save and then in checkout. JS at the top
we're going to use an import to import
this function into our code so we'll
type import curly brackets we'll import
the function
hello and we're going to import it from
a string and then this time instead of
giving it a file path like before we're
going to give it a URL that contains our
code so on the web page we're going to
rightclick and copy the URL at the top
and then inside our code in here we're
going to rightclick and
paste so this import works the same way
as before before except now the codee is
coming from the internet rather than one
of our files so let's
save and then go back to our project and
check the
console and you can see that everything
is still
working so that's how we use external
libraries and JavaScript modules
together we just load the esm version of
the library and we use import as normal
except this time we're importing from
code that is on the
internet next let's use DJs with
JavaScript modules to do that we're
going to load the esm version of DJs so
we're going to go to the video
description and click this link for the
DJs esm
version and now we're going to load this
code into our project so let's go back
into our codee and first let's open
checkout.
HTML and we're going to remove this
script tag because we're going to load
this with JavaScript modules so let's
save and then go into checkout. JS and
then at the top we're going to import
from the DJs esm version so we'll
import and we're going to use a slightly
different syntax we're just going to
type
DJs without the curly brackets and then
we'll type from a
string and we're going to give it the
URL that contains the code so we'll go
to our
browser and then click the URL at the
top we're going to right click
copy and then in our code inside these
quotes rightclick and
paste and
save so now let's open our project and
take a look at the the console to make
sure it works so we'll right click
inspect the
console and everything is still working
so that's how we use the DJs external
library with JavaScript modules so
before we continue we're going to learn
about this new syntax that we used here
so this syntax is called a default
export a default export is another way
of exporting something from a file we
can use it when we only want to export
one thing from a file and it makes the
syntax a little bit cleaner because we
don't have to type the curly brackets so
let's do an example of a default export
to see how it works we're going to open
the utils folder and open money.
JS and at the bottom we're going to
create a default export by typing
export default and then whatever we want
to export so let's say we want to export
this function here so we just type the
name of the function format
currency and
save and now when we import this we can
just import the name without the curly
brackets so the syntax is a little bit
cleaner now each file can only have one
default export so if we only want to
export one thing from a file this is
another syntax that we can
use so some people like using default
exports because they feel that exporting
only one thing from a file makes the
code cleaner however in your own code
it's up to you which version of export
you want to
use let's go back to checkout.
JS and then here the DJs Library only
exports one thing which is the DJs
function so they chose to use a default
export instead of a normal export that
we were using before
by the way the syntax up here with the
curly brackets is called a named
export so when we use external libraries
in the future some libraries will use
named exports like this and other
libraries will use a default export like
this so it's useful to know both
syntaxes so that's how we use external
libraries and JavaScript modules
together we just import from the esm
version of the library now keep in mind
that not every library has an esm
version so for some libraries we still
have to use a script
tag okay now that we learned external
libraries let's do some practical
examples we're going to go back to the
checkout page and we're going to use DJs
to create the delivery options here so
the way this works is that we can select
one of three delivery options when we
click an option it should change the
delivery date up here and it should
change the prices on the right side so
let's get started as always we're going
to do three steps first we're going to
save the data and then we're going to
generate the HTML and finally we're
going to make it interactive so first
what data do we need to save for this
section well each delivery option has a
delivery time like 7 days or 3 days and
each option also has a
price so right now here's what our cart
looks like now we could save the
delivery option details inside the cart
like this however notice that this data
gets duplicated for each product in the
cart instead we're going to save the
delivery options
separately and then just save an ID that
points to the delivery
option as a reminder this technique is
called normalizing the data we save the
delivery options separately and then we
just save an ID
that points to the full delivery
option so let's create the data for the
delivery options we'll go into our code
and then in the data folder let's create
a new file for this and we're going to
name this file delivery options. JS and
press
enter and in here we'll create a list of
delivery options that we can pick from
we'll create a variable const delivery
options equals and array because we want
a list and then each delivery option is
going to have multiple values like the
time to deliver as well as the price so
we're going to make each of them an
object to group these values together so
I'm going to rearrange my windows here
so that we can see the data that we're
trying to save and we can actually close
these tabs for now
so here let's save the data for the
first delivery
option first let's give it an ID
property because as we mentioned we're
going to save the ID in the cart and
then we're going to use that ID to get
the full delivery option here so to keep
things simple let's just give it a
string and an ID of
one and then we're going to give it
another property and we're going to save
the delivery time so for the first
option it's going to take seven days to
deliver so let's create a property
delivery days colon 7 and comma and
we're also going to save the price so
this one is free so we're going to save
the price cents and zero remember that a
best practice when calculating money is
to save it in
cents and next let's save the data for
the second delivery option here we'll
type a comma and another object and
let's give it an ID of two this time and
this one is going to take three days to
deliver so we'll type delivery days
colon 3 and we'll give it a price cents
and this one is
$4.99 so
$4.99 and then finally we're going to
save the data for the third delivery
option comma another object ID of three
and this one is going to take one day to
deliver so we'll type delivery days
colon 1 comma and the price sense is
$9.99 so price sense 999 and
save so now that we've created our
delivery options for each product in the
cart we're going to save the ID of the
delivery option that's selected so for
example here we selected the first First
Option we're going to save an ID of one
in our cart so let's go back into our
code and we're going to open the
cart so here in the default cart we're
going to save the delivery option ID
colon and let's say that the first
product selected the first delivery
option so we're going to save the ID one
and then for the second product we're
also going to save a delivery option ID
colon and then let's say that for the
second product we chose the second
delivery option here so here we're going
to give it an ID of
two next when we add a product to the
cart we also need to give it a delivery
option ID so if we scroll down to the
add to cart function here we're adding a
product to the cart so when we add a new
product we also want to give it a
delivery option ID so we'll type
delivery option ID colon and for new
products let's give it a default
delivery option of one so for new
products to select the first one and now
let's
save and lastly we might have a cart
that is saved in local storage so we'll
need to add the delivery option ID to
local storage as well but to keep things
simple let's just do a shortcut we're
going to delete the cart in local
storage and then it will go back to
using this default value which has the
delivery option
IDs so to delete the cart from local
storage we're going to go into our page
and open the console right click
inspect the
console and we're going to type local
storage. remove item brackets and the
cart and press
enter so this will erase the cart from
local storage and it will use those
default values so now let's go to our
page and
refresh and it should be using the
default cart so that's how we save the
data for the delivery
options by the way in the rest of this
course if you get an error in your
project but your code looks correct you
may have some bad data saved in local
storage to fix this you can try running
local storage. CLE in your console to
remove everything from local
storage and then refresh the
page the next step is to generate the
HTML first let's find the HTML for the
delivery options here to do that we can
rightclick this part of the page and
inspect
and this will give us the HTML for this
part so we're going to find the element
that represents this part of the page
and that's this one right here it's a
div with the class delivery Das options
and to find this in our code we're going
to search for this class so let's go
back to our
code and then we're going to open
checkout. JS which is right
here and we'll press crlf or command F
to find code and we're going to look for
the class delivery Das
options and it will give us this code
right here so this is the HTML for the
delivery
options so now instead of writing this
HTML directly we're going to generate
this with
JavaScript to keep our code organized
let's create a function for generating
this
HTML we'll scroll to the
bottom and then here we'll create a
function and let's call it delivery
options
HTML brackets and curly
brackets and now inside here we're going
to do three steps first we're going to
Loop through the delivery options we
created earlier and then for each option
we're going to generate some HTML and
then finally we're going to combine all
the HTML together so first let's import
the delivery options at the top so we'll
scroll up and we're going to
import curly brackets from quotes and
we're going to locate the delivery
options file which is inside the data
folder so first we need to get out of
the scripts folder we'll type dot do
slash and then go into the data folder
slash delivery options. JS and we're
going to import the delivery
options now one thing I forgot to do is
that inside these delivery options we
need to make sure that we export this
variable so we're going to type export
and
save and we'll go back to checkout. JS
and then here we're going to Loop
through the delivery options below so
we'll scroll back
down to this new
function and type delivery options. for
each brackets and a function
inside and we'll name the parameter
delivery
option so for each delivery option we're
going to generate some HTML so let's use
a template string to save the
HTML and then we're going to scroll up
and we're going to find the class
delivery Das option so this is the HTML
for one delivery option so we're just
going to copy this HTML into our Java
JavaScript below so we'll right click
copy and then down here inside the
string give some new lines and
rightclick and
paste and if we need to reformat we can
select these lines and press
tab okay now when we're generating the
HTML instead of using the same date
every time we're going to calculate the
date using DJs and then insert it into
here to calculate the date we're going
to get today's date first using
DJs so up here let's create a variable
const today
equals and according to the
documentation to get today's date we can
just call the DJs function so we'll type
DJs and
brackets next
each delivery option takes a certain
amount of days to deliver so we need to
add that to today's date to do that we
have a method called add So Below this
let's create a variable to save the
result const delivery date
equals
today. add
brackets and we're going to give it two
parameters the first parameter is how
many dat days we want to add and this is
saved in the delivery option so here
we'll give it the delivery option dot
delivery days
comma and then we'll give it the length
of time we want to add which is a string
days now that we calculated the correct
delivery date we need to display it in
an easyto read format and again DJs has
a method called format that Let's us do
this so below let's create a variable
const and we'll call it date string and
make it equal to delivery
date.
format brackets and will give it a
string so the format we want is we want
to insert the day of the week so
according to the documentation we can
use
4ds and then a comma and a space and
then we want to insert the month and
according to the documentation that's 4
Capital
M's and finally we're going to insert
the day of month which is capital
D so now that we calculated this date
string we're going to insert it into the
HTML instead of using the same date
every time so we'll remove this and then
insert the date
string next let's insert the price
because it's going to be different
prices every time so at the
top let's create a variable const and
we'll call it price string and make it
equals and remember each delivery option
has a property price sense so if the
price ense is zero we want to display
the text free if the price sense is not
zero we want to display the price as
dollars with a
dash so to do that let's practice using
a Turner operator so first we'll check
if the price sense is zero so we'll type
delivery option. price sense is triple
equals to
Z and then we'll type a new line and
question mark and also a new line and
colon so remember the way that a Turner
operator works is that if the first part
returns true the value is whatever is
after this question Mark if the first
part is false then the value is whatever
is after the colon so it's sort of like
an if statement except we can save the
result in a
variable so if the price sense is zero
that means it's free so we want to
display the text free so we'll create a
string
free and if the price sense is not zero
we want to display the price as dollars
so here we're going to type a template
string a dollar sign and we're going to
insert the price sents as
dollars so here we'll type delivery
option. price sense and to display this
as dollars we already have a function
for this called format currency so at
the front we're just going to type
format
currency Open Bracket and close
bracket and then at the end let's add a
dash so here we'll add space and dash
and
semicolon so that's how we create the
price string for each delivery option so
now let's substitute this into the HTML
so we'll remove this and substitute the
price string and
save so now instead of using these same
values every time we're substituting the
values in into the
HTML finally let's combine all this HTML
together so we're going to scroll up to
the top and outside of this loop we're
going to create a variable to save the
result so let HTML equals empty string
to start and then every time we Loop
through we're going to add this HTML to
this result so here we're going to type
HTML plus
equals and finally after we've created
this HTML we're going to return it from
this function so at the bottom we're
just going to return the
HTML and
save now that we generated the HTML for
the delivery options let's insert this
into the HTML
above so instead of creating this HTML
directly we're going to delete it
and then here we're going to insert and
we're going to run this function to
generate it so here we're going to type
delivery options HTML and
brackets now before we save one thing
that we're missing in this function is
that if we scroll down here we're using
a variable called matching product but
this variable is not accessible inside
this function so let's actually pass the
matching product into here so at the top
we're going to add a parameter matching
product and then when we call this
function up here we're going to pass in
the matching product so matching product
so now let's
save and check our page and now we're
generating the HTML for these delivery
options and you'll notice that your
delivery dates here will be based on
today's date or when you're watching
this video so this will be 7 days after
today or 7 days after when you're
watching this video this will be 3 days
after today or 3 days after when you're
watching this video and this will be one
day after
today now one thing we need to fix here
is that these selectors are empty
however we want the delivery option that
is saved in the cart to be checked to do
that let's go back to our
code and in order to make one of these
selectors selected we're going to scroll
down to the input
element and we're going to add an
attribute called
checked and this attribute makes a
selector
checked however we don't want all of
these delivery options to be checked we
only want it to be checked if it matches
the delivery option ID that is saved in
the cart so let's write some code up
here to figure out which delivery option
should be checked we're going to create
a variable const is
checked
equals and we only want it to be checked
if this delivery options ID matches the
delivery option ID in the cart so we'll
test if delivery option. ID is equal to
the cart item
do delivery option
ID now inside this function we actually
don't have access to cart item so let's
actually pass it in as a parameter cart
item up here and then when we call the
function this outer function has access
to the cart item so we're going to give
it the cart item so we're going to put
it into this function and then we can
use it down here
so now that we have this
variable instead of being checked all
the time we're going to remove this and
insert and we're going to use a tary
operator here is
checked question mark and colon so we
can also use a ternary operator when
we're inserting into a string so again
if this is true it's going to get the
value after the question mark So if it
is checked we're going to give it the
value
checked if this is false we're going to
give it the value of empty string so
it's the same thing as if this attribute
didn't exist so now if we
save you'll notice that the correct
delivery option is checked for each
product the first product we saved
delivery option one and the second
product we say delivery option
two finally let's replace this date at
the top with the delivery date that we
selected
here we'll go back to our
code and we'll scroll to the
top until we see this date in our code
here so now we're going to calculate
this date using the delivery option that
we picked so remember that inside the
cart we only saved the delivery option
ID so let's use this to get the full
delivery
option so at the top here let's get the
delivery option ID out of the cart const
delivery option ID equals cart item.
delivery option
ID next we're going to use this ID to
find the full delivery option now we did
something similar with the product ID we
Loop through the products found a
matching ID and then saved it in a
variable up here so we'll do the same
let's create a variable to store the
result let
delivery option and then we're going to
Loop through the delivery options so
delivery options. for each brackets and
a
function and let's name the parameter
option because we use the name delivery
option up here so in here we're going to
look for a matching ID so if this option
ID is equal to the delivery option ID
here we're going to save this inside
this variable so delivery option equals
option so now we have the full delivery
option in our code and we can use it to
get the delivery days property and then
calculate the day that we need
here to calculate this state we already
wrote some code for this at the bottom
if we scroll down in our
code when we created the delivery
options we calculated the date for each
delivery option so we can reuse this
code above so let's select this code and
then right
click
copy and then at the
top after we get the delivery option
we're just going to rightclick and paste
that code again
and if we need to we can reformat by
selecting these lines and press shift
tab so this code will take the delivery
option that we selected and calculate
the delivery date that we need to show
down here and now instead of using the
same date every time we're going to
remove this and insert the date string
that we created Above So date string and
save so now this date string up here
will match the delivery date that we
chose on the right side so that's how we
generate the HTML for the delivery
options using the DJs external Library
so now let's take a look at our changes
in git we'll go to our code and open the
git
section and here it'll tell us in cart.
JS we added delivery option IDs to the
cart
as well as when we add to the
cart and then in this file we created
the list of delivery
options and in checkout. JS instead of
writing this HTML directly we generated
it and then in money. JS we learned
about default exports so let's type a
message to describe our changes save
data and generate HTML for for delivery
options and
commit the last step is to make it
interactive so when we click a delivery
option we need to do two things first we
need to update the delivery option ID in
the cart array and number two we need to
update the page so we need to update
this date here to match the date that we
select
let's start with the first step let's
create a function for updating the
delivery option in the cart we're going
to go to our
code and we're going to open the file
called cart.
JS so because we're modifying the cart a
best practice is to put the code inside
this file this file should contain all
the code that manages the cart so we're
going to scroll down to the bottom and
we're going to add a new function so
let's type function and let's name it
update
delivery option brackets and curly
brackets so when we update a delivery
option we need to know the product that
we want to update as well as the
delivery option that we chose so we're
going to need two things for this
function the product ID and the delivery
option
ID so the steps to do this is first
we're going to Loop through the cart and
find the product and then we're going to
update the delivery option ID of that
product so to find the product using the
product ID we already have some code for
this if we scroll up to the add to cart
function we have this code which takes a
product ID and finds the matching
product in the cart so let's just make a
copy of this code we're going to select
it right click
copy and then paste it into our new
function so down here right click and
paste so this will give us the card item
that matches this product ID and save it
in this
variable next each card item has a
property called delivery option ID so
we're just going to update that property
so down here we can just type the code
matching item. delivery op option ID and
make it equal to the delivery option ID
that we give to this function so
delivery option
ID and lastly because we updated the
cart we should save it to local
storage so we can use this function we
created earlier save to
storage and brackets now let's
save now that we have this function
let's use it on the checkout page so
first let's export it so we can use this
in another file we're going to export
this
function and
save and then open checkout.
JS and then in our project we need to
add event listeners to each of these
delivery options so we run some code
when we click them so inside our code
here we're going to scroll to the HTML
for each delivery option which is right
here and then we're going to add a class
so we can select it using the Dom js-
delivery D option and then we'll add an
event listener to these so we'll scroll
down and down here we'll add the event
listener using
document. query selector all brackets
and a string will'll select that class
we just created using dot js- delivery D
option
and then dot for each brackets and a
function so for each option we're going
to add an event listener and listen for
clicks so let's just call each of the
options an
element so for each of these elements
we're going to element.
addevent listener brackets and we're
going to listen for clicks comma and
we're going to run this function when we
click
it so as we said the first thing we'll
do is to update the delivery option ID
in the cart so now let's import that
function that we created earlier we're
going to scroll to the
top and we're already importing from the
cart so to import something else we're
going to add a comma and we're going to
import that function update delivery
option so now let's scroll back down and
use use it in our
code so here when we click a delivery
option we're going to update delivery
option brackets now we said we need to
give this function two things the
product ID that we want to updated for
as well as the delivery option ID that
we picked but how do we get these two
values and the answer is if we scroll
up here here we have access to the
product ID and we also have access to
the delivery option
ID so we can use data attributes to
attach it to this element
here so let's create a data attribute
data-
product-id equals double quotes and
insert the product ID which is matching
product. ID and we're also going to use
a data attribute for the delivery option
data- delivery D option- ID equals
double
quotes and we're going to insert the
delivery option here so delivery
option. and
save next let's scroll back
down and then here we're going to get
those values out of the the data
attributes by using const and let's use
the shorthand property here for practice
curly brackets equals the element. data
set and then out of the data attributes
we're going to get the product ID comma
as well as the delivery option
ID as a reminder this is a shorthand
property it does the same thing as the
code down here but it's just a
shortcut now let's
save and try out the project we'll go
back and here if we click the second
delivery option and then refresh the
page you'll notice that now this one is
checked and the date here is
correct so that's how we make the
section interactive we just update the
cart and then when we refresh the page
it will regenerate the HTML based on the
new cart
now let's save our code into git we'll
go back and open the git
section and then it will tell us in
cart. JS we added this function for
updating the delivery
option and in checkout. JS we imported
that function and then at the bottom we
added some event listeners and data
attributes and we use that function to
update the
card now let's add a message describe
describing our changes make delivery
options
interactive and
commit next when we select a delivery
option we need to update the
page so right now in our project when we
click a delivery option we need to
refresh the page for the text to be
updated so what we're going to work on
now is when we click this we want the
page to update
immediately so far in this course the
way we solve this problem is once we
click this we're going to use a Dom to
get this element here and then update
the text
directly however the problem with this
approach is that we need to update the
page one by one and later there might be
lots of places on the page that we need
to update for example when we change a
delivery option we also need to change
the numbers here on the right so there's
potentially a lot of things that we need
to update one by one and it's easy to
make a mistake or forget something so
now we're going to learn a better way to
update the page we'll go back to our
code and let's open checkout. JS
again and notice if we scroll
up here we already have all of this code
that takes our data and generates the
HTML so another way to update the page
is after we update our data we just need
to rerun all this code and regenerate
all this HTML so let's give this a try
first we're going to put all of this
code inside a function so we can rerun
it we're going to scroll to the
top and let's put this in a function by
typing function and let's call call it
render order summary brackets and curly
brackets so the word render just means
to display on the
page and we're going to call this
section the order
summary so this function should display
the order summary on the page next we're
going to put all of this code inside our
new function so let's just remove this
curly bracket
here and let's actually select all of
this code and we're just going to
reformat it by pressing Tab and adding
an indent and then at the end we're
going to add back that closed curly
bracket to finish the
function so all we did was we put all of
our code inside a
function and then at the bottom let's
run this function because we still need
to run all this code at the start of our
page so we're going to type render the
order summary
and brackets so this shouldn't change
anything because we're just running the
same code but now it's just in a
function let's save and
check and everything's still working so
that's good so now let's go back into
our
code and this time to update the page
instead of using the Dom to update the
page directly like we did up here we're
just going to rerun all of this code and
regenerate all the HTML
so after we update the data we're going
to rerun the code using render order
summary and
brackets now let's
save and try it
out so here let's say we start off with
the first delivery option if we click
the third delivery option you'll notice
that the date up here updates
automatically if we click the second
delivery option it updates automatically
as well
so that's a better way to keep the page
up to dat instead of using the Dom and
changing the HTML directly one by one we
just update the data and then regenerate
all of this
HTML so let's go back into our code and
there's two things that I want to point
out here so notice that we put our event
listeners into this big function and
that's because when we're regenerating
all the HTML we're essentially deleting
the previous HTML and replacing it so we
need to add the event listeners again
and the second thing I want to point out
is that inside the render order summary
function we can call render order
summary
again so a function can actually call
itself or rerun itself and this feature
is called recursion it's useful when a
function needs to rerun all of its code
so now let's save our changes into git
we'll open the git section and it will
tell us in checkout. JS we basically
moved all of our code into this function
and then at the bottom we call the
function at the start of the page and we
also call the function when we select a
delivery option so now let's add a
message describing our
changes
regenerate
HTML when updating
delivery option and
commit so the technique we just used
where we update the data and then
regenerate all the HTML this technique
is called
MVC MVC stands for model view controller
and is a popular technique in software
engineering in MVC we split our code
into three parts the first part is the
model this is all the code that saves
and manages the
data so in our project all the code in
this data folder is called the model
because this code saves and manages our
data the second part of MVC is the view
this is code that takes the data and
displays it on the page so in our
project if we open checkout. JS and
scroll to the top here we have code that
takes our data and then generates all
the HTML so this code is called the
view the last part of MVC is the
controller so this runs some code when
we interact with the
page so in our project at the
bottom these event listeners here would
be called the controller because they do
something when we interact with the page
or with the
view so in MVC we divide our code Lo
into these three parts and then they
interact with each other in a
loop first we use the model to generate
the
view so in our code that's what we did
here we took the model or the data which
is our cart and then we generated the
HTML or the view then when we interact
with the view it will run the
controller so that's what we did at the
bottom here
when we interact with the page we run
some
code then the controller will update the
model so that's what we did here inside
the controller we just updated our data
using this
function and finally we use the updated
model to regenerate The
View so that's what this code does it
takes the updated data and then
regenerates all the HTM ml or
regenerates The
View so that's how MVC Works instead of
updating the page directly with the Dom
we just update our data and then
regenerate all the
HTML so we use MVC because doing this
makes sure that the page always matches
the
data so MVC is known as a design pattern
it's a way to organize and design our
code in the future you might use a
technology called a JavaScript framework
to build websites many JavaScript
Frameworks are based on MVC so it's
useful to know how it
works okay now that we learned the MVC
design pattern let's do some practical
examples using
MBC we're going to open our project
again to the checkout page and we're
going to create this payment section on
the right now before we start if we look
at our code in this checkout. JS file
you'll notice that we already have a lot
of code
here instead of adding even more code to
this file let's actually split this up
into two different
files so one file will be responsible
for this left section and then one file
will be responsible for this right
section we're doing this to keep our
code more organized and so that we don't
have too much code in one file
so let's go back and let's create two
new files for the checkout page so up
here we'll create a file and let's call
this one the order summary. JS and press
enter and let's create another file for
the right section and let's call this
one the payment
summary. JS and press
enter now both of these files are
related to the checkout page so let's
create a folder and group them together
we'll create a new folder up here and
let's call it checkout and press enter
and we're going to move these two files
into this new folder so we move that and
we'll move
that next let's open checkout. JS and
let's move all of this code into the
order summary so we'll press control a
or command a to select all the code and
then
rightclick
cut and then in here we're going to
rightclick and
paste now there's a few things that we
need to fix here so first our checkout.
HTML file is still loading checkout. JS
so we actually need to run this function
inside checkout. JS instead of inside
here so let's actually remove
this and save and we're going to scroll
to the
top and let's export this function so we
can run it inside here so we'll type
export and save and then inside checkout
we're going to import curly brackets the
render order summary
function from a string and to locate
this file we're going to type A do slir
that means to start from the current
folder and we'll go into the checkout
folder checkout SL orderers
summary.
JS and finally we're going to run this
function when we load the page so render
order summary and brackets and
save another thing we need to fix is if
we open order summary .js we moved this
file into a folder so now all of these
file paths need to be updated do do
slash is now inside the scripts folder
and we can't find a data folder anymore
so this is going to cause an error so to
find the data folder we need to get out
of the checkout folder and then we need
to get out of the scripts folder so we
need to get out of two folders so we'll
just add an additional do dot slash and
then same thing for this we'll add
another dot dot slash and for the utils
now we need to get out of the checkout
folder and then into the utils folder so
we'll change this to do/
utils and then for here we're going to
go out an additional folder so another
dot dot slash and
save so now let's check if this still
works we'll go to our project and
refresh and try it
out and the p still works because we're
still running all of the same code but
we just organized it into its own file
so now let's open git and save our
changes so it's going to tell us that in
here we removed all this code and then
we separated it into the order summary
file and the payment summary file which
we're going to work on next so let's
type a message describing our changes
move order
summary into its own own file and
commit now let's start creating the
payment summary on the right side so in
our code let's open payment summary.
JS and just like the order summary let's
put all our code in a function so we can
regenerate the HTML if we need to so
we'll type function and let's call it
render payment summary brackets and
curly
brackets and let's just
console.log string payment summary just
to make sure it's working so we'll save
and let's export this function and then
run it inside checkout. JS so export
save and then in checkout. JS at the top
we're going to import curly brackets the
render payment summary function from a
string the current folder go into the
checkout folder and the payment summary.
JS file and then at the bottom we're
going to run the function so render
payment summary brackets and
save let's go back to our project and
open the console rightclick inspect the
console and we'll see the message
payment summary so now we know that our
code here is working and the export is
working
correctly now let's remove this code and
actually build the payment
summary as always we're going to do
three steps save the data generate the
HTML and make it interactive so let's
start with saving the data in MVC this
is called the
model so if we go to our
project for this section the data that
we need is just to calculate these
numbers
here so let's start by calculating this
first number here which is the cost of
the products to calculate this we can
Loop through the cart and for each
product in the cart we can multiply the
products price times the quantity and
then add everything together now let's
convert these steps into code we'll go
to our project and inside the payment
summary
file first we need to get the cart so
let's import it import curly brackets
the
cart from the string and we'll locate
cart.
JS so first we'll go out of the checkout
folder do do slash and then go out of
the scripts folder do do slash and then
into the data folder
data.js and
save and now we're going to Loop through
the cart so we can type cart. for each
brackets and a
function and let's name the parameter
cart item so for each cart item we have
the product ID and the quantity so we
need to multiply the product's price
times the quantity so first we need to
use the product ID and get the full
product details and we already have some
code for this inside orders summary. JS
if we scroll down here we have some code
that takes a product ID and finds the
matching
product now instead of copy and pasting
this code let's actually put this into a
function so we can reuse this and we'll
practice some modules so let's select
this code and rightclick and copy it
first and then let's go into the
products. JS
file and at the top we're going to
create a function so we can reuse that
code so let's type function and let's
name it get product brackets and curer
brackets and we're going to give this
function the product ID that we're
looking for and then let's paste the
code we copied earlier right click and
paste so this finds the matching product
using the product ID and then at the end
of the function let's return the
matching product so we can use this
outside of the function so now let's
export this function so we can share it
across files so export and
save first we'll go to the order summary
and at the top let's import that
function so we're already importing from
product .js we're going to import
something else using a comma the get
product function and then down
here instead of all this
code we're going to run that function so
we make this equal to get product and
run the function and we need to give the
function the product ID so let's just
give that here product
ID and because we're no longer updating
this variable we can change from let to
const and
save let's go to our project to make
sure everything's still working so that
looks
good and now let's use this function
inside payment summary. JS so the same
thing we will import curly brackets the
get product function from a
string and we'll go to the data folder
do SL do do SL data SL
and products.
JS and let's run that function to get
the full product so get product brackets
and then each cart item has the product
ID so we're going to give it to the
function cart item. product
ID and let's save this product in a
variable so we can use it for our
calculations con product equals get
product so now now as we said we're
going to multiply the product's price by
the quantity so down here we can do
product and it has a property
called price sense and we're going to
multiply it by the cart item and this
has a property do
quantity and the last step is to add all
of these
together so outside of the loop let's
create a variable to save the result of
adding them together let's type let and
we'll name it product price sense equals
and we'll make it zero to start and then
every time we Loop through the cart
we're going to add this to this variable
so we'll type product price sense plus
equals this value
here and that's how we calculate the
cost of the products so at the bottom
let's
console.log the product price sense just
to make sure that this is working we'll
save and in our project we're going to
check the
console and it will give us this number
here and this number should match the
number on the page except it's in sense
and assuming you also have two socks and
one basketball in your
cart okay so that's how we calculate
this first number here now let's
calculate the second number which is the
cost of shipping so to calculate this
we're going to Loop through the cart and
add all the shipping costs
together so let's go into our
code and here we're already looping
through the cart so instead of creating
another loop let's just calculate the
shipping cost in the same Loop so let's
create some new
lines and each card item has a property
delivery option ID so we need to use
this ID to get the full delivery option
which has the price so in the order
summary we also have this code that
takes the delivery option ID and finds
the full delivery option so again let's
create a function to share and reuse
this
code so first let's select this code and
we'll write click and
copy and let's go to the delivery
options. Js
file and then at the bottom we'll create
a
function let's call it get delivery
option brackets and curly brackets and
we'll give this function the delivery
option
ID and inside here we'll rightclick and
paste the code that we copied earlier so
this will take this ID and get the
delivery option from this array and
let's return return this delivery
option so we can use it outside of this
function and just to be safe let's also
give this a default value if we don't
find a delivery option so we'll use the
default operator
or and let's make the default value the
first delivery option so delivery
options square bracket 0
so now let's export this and
save and then inside order summary we'll
use this function so at the
top we're already importing from
delivery options so we'll type a comma
and get delivery
option and then down here instead of
running all this code we'll select it
and make this equal and run the function
get delivery option
brackets and we'll give it this delivery
option ID delivery option
ID and we can change from let to const
since we're not changing this variable
so now let's save and let's use this
function inside payment summary as well
so in here at the top we'll import curly
brackets the get delivery option
function from
quotes the data folder do do slash do
data slash and the delivery options. JS
file and now we'll run this function get
delivery option and
brackets and each cart item has a
delivery option ID so we'll put that
into the function cart item. delivery
option
ID and let's save this in a
variable con delivery option
equals and now we can get the price for
the delivery option using delivery
option price sense
property and finally we're going to add
all these together so at the top let's
create a variable to save the result let
we'll call it ship
shipping price cents equals zero and
when we Loop through the cart we're
going to
do shipping price sents plus equals this
delivery options
price and let's also console.log this to
make sure it's working so shipping price
cents and Save
now let's go to our project and check
the
console and this value
here should be the same as adding these
two numbers together in
sense so that's how we calculate the
second number the shipping price so note
that this
$4.99 number is just a practice number
right now the actual shipping price
should be the total of adding all these
sh shipping prices
together the next number we need to
calculate is the total before tax so let
just adding these two numbers together
inside our
code let's remove these console. logs
and we'll create const total before tax
sense and make it equal and we'll add
these two together product price sense
Plus shipping price
sense and the next number is the tax so
we're going to calculate a 10% tax on
this number here to calculate 10% of
something we can multiply this by 10 /
100 that's what percent means so 10 ID
100 is also equal to
0.1 so we can also multiply this number
by
0.1 let's go into code and we'll create
a variable const tax sense make it equal
to the total before tax sense times 0.1
or
10% finally to calculate the total we're
going to add these two numbers together
so const total sense equals the total
before tax sense Plus the tax
sense so that's how we calculate all the
numbers in the payment summary and now
we have all the data that we need next
we're going to generate the HTML in MVC
this is called The
View so at the bottom here let's create
a variable to store the
HTML const payment summary
HTML and we'll make make it equal to a
template
string and then inside here we're going
to copy and paste the
HTML so let's open checkout.
HTML and we're going to scroll up until
we find the class payment D summary so
we're going to generate all the HTML
inside here so let's actually select
this HTML and move it into our
JavaScript so we'll select it up until
this button and then we we can
rightclick
cut and remove the new line save and
then inside the payment summary inside
the screen we'll rightclick and paste
the
HTML and if we need to reformat we can
select these
lines and press tab a few times to
reformat
it and and
save next instead of using these same
numbers every time we're going to take
the numbers we calculated up here and
insert it into this HTML string so
instead of 42.75 every time we're going
to insert the product price
sense and let's give it some new lines
to make it a little easier to
read now remember that this number is in
sense and we want to display it as
dollars to do that we already have a
function for this so in the utils money.
JS file we have a function format
currency that displays it in dollars so
let's use this function inside payment
summary so at the top let's import the
function
first import curly brackets the format
currency function from a Str
and to locate this folder we'll go out
of the checkout folder do do/ the UIL
folder SL money.jpg
numbers here so this one is the shipping
price so we can
insert format currency brackets the
shipping price sents and let's give it
some new lines to make it a little
easier to
read next let's insert the total before
tax so we'll remove this number and
insert format currency bracket gets the
total before tax
sents and new
lines and next is the tax we'll remove
this and
insert format currency brackets the tax
sents and we'll enter some new lines and
finally the total so we remove this
insert
format currency brackets total sense and
add some new
lines and
save now before we continue I actually
learned of a small issue with the format
currency function so let's open the
money. JS
file and I recently learned that this
two fixed method has a small issue with
rounding so for some numbers that end in
five it won't round the number
properly one way to fix this issue is to
round the price sense first so that this
method doesn't have to do any rounding
so at the front here let's just type
math.round Open Bracket and close
bracket so this is just a tricky issue
that I discovered with the help of AI
recently we just need to add a little
bit of code here to fix it
so now let's save this
file and go back to payment
summary so now that we generated all
this HTML and inserted our numbers into
it let's put this HTML on the page so
inside checkout.
HTML let's give this payment summary
another class
js- payment Das summary and then we'll
select this using the Dom so now let's
save this
file inside payment summary at the
bottom after we create the HTML we're
going to document. query selector
brackets and a string and we'll select
js- payment D summary to get that
element and we'll change the HTML inside
that element using do inner Capital H
HTML and we'll make it equal to the
payment summary
HTML that we just created so now let's
save and check our
project and now these numbers on the
right should match what we have in the
cart and the delivery options that we
selected so that's how we generate the
HTML for this section
here now let's save our changes into git
we'll open
git and it will tell us in checkout.
HTML we removed the HTML we created
manually in delivery options. JS we
created this shared function for finding
the full delivery option and the same
thing in products. JS for finding the
full
product inside checkout. JS we're now
running all the code inside payment
summary in order summary we're just
using those shared functions that we
created and then in payment summary we
calculated the numbers and generated all
the
HTML and finally in money. JS we fixed a
small bug related to rounding let's type
a message to describe our changes save
data and generate
HTML for payment
summary and commit
the last step is to make it interactive
in MVC this is called the
controller let's go to our
project and one thing we can make
interactive in this section is the place
order button however we haven't figured
out how orders work yet so we'll work on
this in the next lesson another thing we
can make interactive however is when we
change the cart on the left these prices
should also update so let's make this
interactive first when we delete a
product the prices here should update so
let's actually practice using MVC to
create this
functionality according to MVC when we
click delete we should update the data
and then regenerate all of this
HTML so let's get started and go to the
code for the delete link so this is in
the order summary section so in our code
let's open the orders summary. JS
file and we'll scroll down and find the
event listener for the delete link which
is right
here when we click delete first we're
going to update the
data so we already update the data using
this function remove from cart
and now the next step according to MBC
is to just regenerate all the
HTML so to regenerate the HTML for the
payment summary we created this function
at the top render payment
summary so this will recalculate all the
numbers and then regenerate the
HTML so let's import this
function in order summary. JS we'll
scroll to the top
and down here we can import curly
brackets the render payment summary
function from a string and we'll locate
the payment summary file so it's in the
same folder so we're going to start with
a slash which is the current folder the
payment summary. JS file and now let's
use this function in the event listener
so let's scroll
down when we click delete we're going to
update the data and then regenerate all
the HTML using render payment summary
brackets now let's save and go to our
project focus on the numbers on the
right here and now let's click
delete and you'll notice that all of
these numbers updated to match our new
so that's another example of using MVC
when we click delete instead of using
the Dom to change these numbers one by
one we just update the data and then
regenerate all of the
HTML MVC makes sure that the HTML always
matches the data or that the view always
matches the
model let's do one last example of NBC
for this lesson when we change the
delivery options here we also want these
numbers on the right to update so let's
find the code for the delivery options
again this is in the order summary
section so in our code we'll open orders
summary. JS scroll down and then here we
updated the data and then we're just
going to regenerate the HTML for the
payment summary using render payment
summary and and
brackets now let's
save and then look at our project and
let's try changing the delivery option
here and you'll notice the numbers on
the right update automatically to match
the cart and that's it we finished the
checkout page so now let's save our code
into git we'll go into the git
section here and inside order summary we
basically imported the render payment
summary function
and then at the
bottom we used MVC so when we click
delete we update the data or the model
and then we regenerate all the HTML or
regenerate The View down here same thing
when we click a delivery option we
update the data and then regenerate all
the
HTML the last thing we're going to do is
at the top of this file
we're going to remove this practice code
that we use to learn external libraries
so let's open orders summary.
JS and at the top we're going to remove
this
code and
save now let's go back into
get and that looks good finally let's
type a message describing our
changes make
payment
summary
interactive and
commit and that's the end of this lesson
in this lesson we learned about external
libraries which is code that is outside
of our project we learned about the DJs
external Library which helps us work
with dates we also learned how to use
external libraries with JavaScript
modules together as well as the default
export syntax we created the delivery
section of the checkout page we learned
MBC which is a better way to design our
code and we created the payment section
of the checkout
page thanks for watching this course so
far if you want to support this channel
you can check out the premium version of
my courses just like this one where you
can get a certificate of completion and
a Better Learning platform if you're
interested in extra videos from me more
in-depth videos and behind the scenes
content you can check out these links
here you can also support the channel by
liking the video subscribing and sharing
this video with others thanks again and
let's continue with the
course here are some exercises to help
you practice what we learned in this
lesson e
in the rest of this course if you get an
error in your project but your code
looks correct you may have some bad data
saved in local storage to fix this you
can try running local storage. CLE in
your console to remove everything from
local
storage and then refresh the
page if you see an error like this
object object that means that you saved
something directly into local storage
but you have to json.stringify it first
so check your code to make sure that
you're always stringifying before saving
to local storage and then clear your
local storage and refresh the
page in this lesson we're going to learn
how to test our code so when we're
writing code it's important to test our
code to see if it's working correctly
and if you're working at a company in
the future you'll also be expected to
test your code so let's learn how to do
that in this
lesson the easiest way to test our code
is to just open the website and try out
the code for example in our code here
let's open the file utils money.jpg
server so on this website we have a
couple of prices here as well as here
and we created these prices using the
function format
currency so if we just look at the
website we can see that these prices
look correct and this tells us that the
function format currency is working
correctly so that's one way to test that
function we just open the website and
try it out so this is called manual
testing when we manually open the
website and try our code so manual
testing is really useful for quickly
checking to see if everything is
working so now let's talk about the
disadvantages of manual testing one
disadvantage is it's hard to test every
situation for example here we just
happen to have the number
295 and we test with that however what
if we want to test with different
numbers like the number zero or a number
that requires rounding like
2.5 in order to test all these
situations we have to manually set up
our website so that our code runs with
those numbers so here we ran with 2095
as well as zero so we covered those
situations however we did not cover
2.5 so we have to do a bunch of setup in
order to test that situation
so as you can see it takes a lot of time
and effort to test different situations
in our code the second disadvantage of
manual testing is that it's hard to
retest the code for example if we change
some of our code how do we retest format
currency and make sure that it's still
working
correctly well we would have to open the
website and set up all the situations
again and retest all those situations
manually so this takes too much time and
effort to retest the
code to solve these two problems we're
going to learn another way to test our
code called automated
testing automated testing basically
means using code to test code instead of
manually opening the website and
clicking around to try our code we're
going to tell the computer to do these
tests for us and this will save a lot of
time and effort so let's go ahead and
create our first automated test we're
going to go back to our
code and again let's test this format
currency function to create an automated
test we're just going to write some code
to test this function so first let's
create a folder to group all of our test
code together we're going to click this
icon to create a folder and let's just
name this tests and press enter
and we're going to move this folder so
we'll drag it to the top level here
beside the HTML
files so we want the test folder to be
beside the scripts
folder next let's click on the test
folder and we're going to create our
first test file we'll click
this and we're going to test format
currency which is inside the money.jpg
money
test.js so we know that this file
contains tests for money. JS so let's
press
enter and inside this file we're going
to write some code to test format
currency so first let's import format
currency so we can test it at the top
we'll type import curly brackets format
currency
from a string and from here we're going
to locate money. JS so we start out in
money test.js and we need to get out of
the test folder so we'll type do do
slash to get out of this folder and then
we'll go into the scripts folder scripts
slash and then into the utils folder
utils slash and locat
money. Js
so as a reminder format currency takes a
number in cents like 295 cents and then
converts it into Dollars like
$20.95 so first let's test this function
using that number 2095 as an example
we're going to run the function format
currency brackets and give it
295 and now we're going to check if the
result of this function is correct to do
that we can just use an if statement so
we'll type if Open Bracket close
bracket and we said we expect format
currency
295 to give us the string
20959 and curly brackets and and if
these two are equal that means the code
is working correctly so we're going to
console. log the string
passed to say that this test has passed
now if it is not equal to
20.95%
failed and
save and that's it this is our first
automated test it checks if the result
of this function is correct if it is
correct we're going to display past and
if it's not correct we're going to
display
failed now let's run this test code so
remember we can't run JavaScript files
directly we need to load this Javascript
file using an HTML file so let's create
an HTML file to run this test inside the
test folder we're going to create a new
file by clicking up
here and let's name this file
tests.
HTML and press
enter and in here we're going to start
by creating a basic HTML structure so as
a reminder at the top we'll type less
than exclamation
dock type space HTML greater than and
we'll create an HTML
element and then inside we'll create a
head
element as well as a body
element and then inside the body we're
going to create a script tag to run
JavaScript
code and we're going to give the script
tag an attribute called SRC or source
equals double quotes and we're going to
give it this JavaScript file to
run money
test.js and also because this file uses
import we also need to add an attribute
called type equals modules to give this
file access to JavaScript module
features like
import so now let's
save and we're going to run this file in
live server so we're going to click it
and then
rightclick open with live
server and then we're going to check the
console by right
clicking
inspect and open the
console and our code display the text
passed so if we look at our
code and open money
test.js it's telling us that the result
of this function matched what we
expected
and this test
passed so that's how we run an automated
test we just load it like normal
JavaScript so as you can see automated
tests are pretty straightforward we're
just using code to test
code okay so I mentioned earlier that a
disadvantage of manual testing is it's
hard to test every
situation now let's solve this problem
using automated
tests so inside money
test.js if we want to test format
currency in different situations or with
different numbers we can just add some
more tests at the bottom so at the
bottom let's create some new lines and
we'll just add another test using IF
brackets and curly
brackets and inside here let's test
format currency with the number zero so
we'll type format
currency brackets 0 and we expect this
result to be the string 0.0 0 so we'll
check if this triple equals the string
0. if this result matches we're going to
console.log the string
passed and if this result does not match
we're going to type else curly brackets
and
console.log the string
failed so that's how we test format
currency in a different situation with
the number zero so now let's
save and then go back to our test page
which is here and then open the console
right click
inspect the
console and it will tell us that both of
our automated tests
passed so as you can see automated tests
help us test our code in different
situations very easily this is a lot
faster than manually opening our website
and setting it up to test with different
numbers so let's go back to our
code and by the way another name for a
situation that we're testing is called a
test case so here instead of saying
we're testing two different situations
we usually say we're testing two test
cases okay now let's get more practice
and add another test case at the bottom
of this file we're going to create
another if statement if brackets and
curly
brackets and this time let's test format
currency brackets and we'll give it a
number that requires some rounding
so when we calculate the 10% tax on our
website the result could be a decimal
like the number
2000.5 if we use the number
2.5 this will convert into $20 and
0.5 however we can't have
0.5 so we're going to round this up to 1
cent so we're going to have $20 And1
so let's check if this result triple
equals the string
20.1 and if it is equal we're going to
console.log
past and if it is not equal else curly
brackets
console.log
failed and
save and open our test page and open the
con
and you can see that all three of our
test cases passed and that's it we just
created three test cases for format
currency using automated
tests now let's go back to our
code and currently we have three test
cases and you might be wondering how
many test cases should we have generally
we create two types of test cases basic
test cases and edge
cases a basic test case just tests if
the code is working or not so here our
first test case is a basic test case we
use a normal number like
2095 and we see if format currency is
working
correctly the second type of test cases
that we should have are edge cases this
means we test a code with values that
are a little bit bit tricky they're on
the edge of what our code can handle for
example in our test here the last two
test cases are edge cases zero is sort
of a special number that's not positive
or negative and
2.5 is a number that requires some
rounding so these numbers are acceptable
we can use them with format currency but
they're a little bit tricky and on the
edge of what our code can handle
so when creating test cases make sure to
create basic test cases as well as edge
cases if there are any edge
cases now we could have added another
basic test case like format currency
1095 however this is very similar to
2095 it's basically testing the same
thing so we don't need another test case
like this generally we should try to
test something different in each test
case for example an edge case that we
have not tested is a number
200.4 so this would check if the code
rounds down correctly to $20
and0 however I'll leave creating this
test case as an
exercise now let's move on and talk
about the second disadvantage of manual
tests which is it's hard to retest the
code automated test also solve this
problem for example let's say that we
Chang the format currency function so
inside UIL money.jpg
we would have to open up the website set
up everything manually and then click
around to see if it's
working however with automated testing
all we need to do is to rerun all of
this test code and it will instantly
retest all of these cases so let's go
back to money. JS and save this
code and then go into our test
page and check our console right click
inspect the
console and you can see that it
instantly reruns all the test cases and
it tells us that the last test case
failed so automated tests make it really
easy to retest our code after we make
any
changes okay now we have another problem
here we can see that the test Cas is
passed passed and failed but it's not
clear which ones passed and which ones
failed we don't really have a name for
these tests so we don't know what
they're doing so that's what we're going
to add next we're going to give each of
these tests a name so let's go back to
our
code and open money
test.js and now we're going to give each
of these test cases a name so above the
first test
case let's just
console.
log a string and we're going to give
this test a name so the name should
describe what this test is doing so in
here let's just use the name converts
cents into
dollars and that's how we give a test
case a name let's do the same thing with
the other two test cases so down here
we're going to console.
log brackets and a string and we give
the second test case a name so this one
tests the number zero so let's use the
name works with zero so again the name
just describes what the test is
doing and let's do the same thing for
the third test case we
console.log a string and here we're
testing if the function rounds up to the
nearest scent so let's use the name
rounds up to the nearest
scent and
save if you're wondering how I came up
with these names a naming convention
that we use is to describe what the code
is doing for example the code works with
zero or the code rounds up to the
nearest scent and then we remove the
code some people also like to use the
word it instead of the
code so now each of these test cases has
a name above it if we open up our test
page and open the
console now we can see exactly which
test case passed and which test case
failed so this failed test case tells us
we have a rounding problem in our code
so now we can go back to our code into
money. JS and investigate the rounding
problem so of course we removed
math.round as an example we're just
going to add it back to fix that failing
test capital m
math.round Open Bracket and close
bracket and
save and then open the console for our
test which is here and now all of our
test cases
passed next another thing we do when
naming our tests is to group related
tests together for example these three
test cases are for the format currency
function so we're going to group these
tests together and give this group a
name by the way a group of related tests
is called a test
Suite so let's go back to our code and
open Money test.js
and at the top let's give this group of
tests or this test Suite A Name by
typing
console.log brackets and a string we're
going to name it test Suite colon format
currency and
save so now let's open the console for
our
tests and now at the top it will show us
test site format currency so this makes
it clear that this group of tests here
are for the format currency
function in the future if we are testing
some other code for example a calculated
tax function we can create another group
of tests or another test Suite like this
and this makes it clear that the second
group of tests is for the calculate tax
function so this is how we name our
tests and group our tests together
together to make it more clear what is
being tested and which tests have passed
or
failed and now we created our first set
of automated tests as you can see
automated tests are basically using code
to test code and they make it really
easy to check if our code is working
correctly so now let's save this into
git we're going to open the git
section and our first change in money
test.js we created the tests for format
currency and then we created an HTML
file to load our test
code so let's create a message
describing these
changes create automated tests for
format
currency and
commit next we're going to learn how to
use a testing framework to write
automated tests so what is a testing
framework in the previous lesson we
learned about external libraries which
is code that is outside of our project
that someone else wrote and we can load
external libraries into our project and
use
them so a testing framework is an
external library that helps us write
tests
easier let's go back to our code and
we're going to open the money test.js
file and notice that in our tests we
need to do several things first we
create a test suite and we give it a
name and then we create some tests and
for each test we give it a name and then
we compare the values and display the
result in the console so a testing
framework helps us do all of these
things automatically and gives us many
other features so now let's learn our
first testing
framework in this course we're going to
use a popular testing framework called
Jasmine now if you're working at a
company in the future you'll definitely
be using a testing framework but it
might not always be Jasmine and that's
okay because most testing Frameworks are
pretty similar so by learning Jasmine
you'll be able to easily use other
testing Frameworks in the
future to load Jasmine into our project
we're going to go into the video
description and we're going to click
this link to download
Jasmine so once that link opens we're
going to be on this page and we're going
to scroll down and we're going to click
this Jasmine DST standalone. zip file to
download it
now once that's finished downloading
we're going to open our downloads
folder and if you're on Windows we're
going to rightclick the zip file and
click extract
all and click
extract now if you don't have that
extract all option you can also create a
folder with this name and then double
click the zip file and drag everything
into that folder
if you're using a Mac you can just
doubleclick the zip
file so this folder contains the code
for Jasmine and we're going to drag this
folder into our project so let's open
the code for our
project and then we're just going to
drag this folder down
here and click copy
folder so just make sure that this fold
folder is beside the scripts and images
folder next we're going to rename this
folder so we'll right click
rename and let's rename it to
test- Jasmine to make it clear this
folder contains test created with
Jasmine so now let's press
enter and now we have Jasmine inside our
project so inside the lip folder we have
some JavaScript files here and this is
the code for the Jasmine testing
framework so this is another way to load
an external Library into our project we
can just download all the code and put
it into our project and this is useful
if an external library has lots of
different files like
this before we continue let's save the
changes into git so if we make any
changes later it will be easier to see
them we'll open the git section
and then we just added all the code for
Jasmine so at the top let's type the
message add Jasmin testing
framework and
commit now that we loaded Jasmine into
our project let's learn how to use it so
Jasmine has a documentation page that
shows you how to use the testing
framework however to save time I'm just
going to show you the features that we
need and you can read the documentation
later if you want so first let's learn
how to run tests using
Jasmine I'm going to close this for now
and then in our code we're going to open
the test- Jasmin folder and at the
bottom we're going to open this spec
runner. HTML
file so this file loads all of the
tests so this does the same thing as our
test.html file from before and by the
way in Jasmine spec is another name for
test so spec Runner just means test
Runner this file runs all the
tests so let's actually rename this file
to test.html so we can match what we had
before and compare the two so here we're
going to right click and
rename
tests. HTML and press
enter and now let's open this file and
take a look at the code that's
inside so here at the top this is the
code for the Jasmine testing framework
so we're just loading the framework up
here below that here we have the code
that we want to test so this code is
sort of like the money JS file that we
were testing
earlier and then at the bottom these
files contain the tests so these files
are sort of like the money test.js file
that we had earlier and you'll notice
that these are in a spec folder so as a
reminder in Jasmine spec is another name
for test so this is basically the test
folder this folder contains all of our
tests so now let's run these tests and
to do that we just need to open this
HTML file in live server just like we
did before
so for this file we're going to right
click and open with live
server and I'm just going to make this a
little bigger by pressing control equals
so it's easier to see in the
video so this is what Jasmine tests look
like up here we have five Green Dots
this means we have five tests that we
ran and the green color means that all
of them passed so that here each test
has a Green Dot and you'll notice that
each test also has a name next to it
which tells us what the test does and
don't worry if this is in a different
order for you Jasmine randomizes the
order of the
tests also notice that some of these
tests are grouped together into a test
suite and up here we have the name of
the test Suite so as you can see a
testing framework helps us do all of the
things we were doing before and it also
provides a nice looking website where we
can see the test results so a testing
framework is just an external library
that helps us write tests
easier now that we know what Jasmine and
a testing framework is let's learn how
to write our tests using
Jasmine first we're going to go back to
our
code and we're going to remove the
example code provided by
Jasmine so down here we'll remove these
four script
texts and let's also remove the source
folder so we'll right click
delete as well as the spec folder right
click
delete but make sure we keep this lib
folder because this contains a code for
Jasmine and now inside test Jasmin we're
going to create a new file for our test
so we'll create a new
file and let's say that we're testing
money. JS again so let's name it the
same thing here money
test.js and press
enter and now let's create the same test
we had before by using Jasmine this time
so to make it easier for the video I'm
just going to take this file and drag it
to the top here so we can see these two
side by
side so like before we're going to
create tests for format currency first
we'll need to import this function at
the top so let's just actually select
this and right click
copy and then down here right click and
paste and just make sure that this file
path still works so our money test.js
file has to be inside test- Jasmin and
this folder should be beside the
previous test
folder next we're going to create a test
suite and name the test Suite so in
Jasmine to create a test Suite we're
going to use a function called
describe so this describe function is
provided by Jasmine and it creates a
test
Suite next we're going to give a name to
the test Suite so to name a test Suite
in Jasmine we're going to give describe
a string and this string is the name of
the test Suite so let's name it the same
thing as before test Suite colon format
currency next we're going to add some
tests inside the test Suite to do that
we're going to give describe a second
parameter which is a function brackets
arrow and curly
brackets and inside here we're going to
create a test and give the test a name
to create a test in Jasmine we're going
to use another function called it and
brackets so it is a another function
provided by Jasmine and this creates a
test next let's give a name to our test
so that we know what it's doing to name
a test we're going to give it a string
and this is going to be the test name so
let's name it the same thing we had
before
converts sense into
dollars and now we're going to add some
code into our tests to do that in
Jasmine we're going to give it a second
parameter which is another function
brackets arrow and curly
brackets so this is the code inside the
test and in this test we need to compare
these two values and display the result
in Jasmine instead of creating an if
statement and displaying the result
ourselves Jasmine provides us another
function to do all of this
and that function is called expect and
brackets so expect lets us compare a
value to another value for example let's
give expect the first value that we want
to compare which is format currency
2095 so we'll type format
currency brackets
295 and now to compare this value to
another value expect gives us an
object and this object has many methods
we can use to do
comparisons so one of the methods we can
use in this object is dot 2 equal
brackets and then inside these brackets
we'll put another value that we want to
compare this to so we want to compare
this to the string 2095
and that's it this checks if this value
is equal to this value and then displays
the result on the page so it does
everything that we did before except
with one line of code and you'll also
notice that jasmin's code is designed so
that it reads like English for example
we expect format currency
2095 to equal this string and this makes
a test code easier to read
so we just created our first test suite
and our first test using
Jasmine now let's run this test to do
that we just need to run this Javascript
file inside test.html
so first let's save this
file and then inside test.html we're
going to load this file so in here at
the bottom we're going to create a
script tag
and we'll give it a source attribute SRC
equals double
quotes and we're going to load money
test.js
test.js and remember our test file uses
import so we also need to give it the
attribute type equals module so this
file has access to JavaScript module
features so now let's save
and we'll open this file in our browser
so we should have it open from before if
you don't you can write click and open
with live
server so we'll open the test page and
now you can see that we have our one
test that we created here and it's
passing so it's green you can see here
that we created a test Suite with a name
and we also created a test with this
name so we just created the first test
that we had before except using Jasmine
this time and you can see that Jasmine
also creates a nice website for us to
see the test
results okay now that we learned how to
use Jasmine to create a test let's get
some practice and create the rest of our
tests from before we'll go back to our
code and open money
test.js and here we're going to create
the other two tests that we had here so
at the bottom inside the same test Suite
we're going to create another test using
the function it brackets and we'll give
it a string which is the test name and
let's name it the same as
before works with zero comma brackets
arrow and curly
brackets and now we can put something
inside this test so in the second test
we're going to compare these two values
to compare values we're going to use the
function expect
brackets and the first value is going to
be format
currency brackets
zero and then expect gives us an
object and this object has a method
called dot to equal which lets us
compare this value to another value
so we'll call this method using brackets
and compare to the string the string 0 0
0 and now let's
save and live server will update our web
page automatically so we'll open the
test page and now we have two tests and
they both passed so that's how we create
the second test using Jasmine and again
don't worry if this is in a different
order for you Jasmine randomizes the
order of the
tests finally let's create that third
test that we had before we'll go back to
our code and then in our old money test
file we're going to create this third
test feel free to pause the video if you
want to give it a try
yourself so we'll scroll down and we'll
create another test inside this test
Suite using the function it brackets and
a string and we'll give it the same test
name as before
rounds up to the
nearest set comma brackets arrow and
curly
brackets and we're going to compare
these two values so we use exp brackets
and give it the first value format
currency brackets
2000.5 and to compare it we'll use the
method
do2 equal brackets and compare it to
20.01 and
save and let's go back to our test page
and now we have three tests and all
three of them passed so we recreated the
tests that we had
before now let's try making one of these
tests fail to see what it looks like in
Jasmine we'll open our
code and and let's open the file utils
money.jpg
test so it tells us the test Suite name
and the test name that failed and it
will also tell us the two values that
are not equal to each other and here it
will tell us where this test failed so
it tell us that it failed in money
test.js at line
13 so if we go back to our
code and we open the Jasmine money
test.js line 13 is right here so just
telling us that this line failed the
test
here we can see the full list of tests
and it will tell us that we have three
tests two of them passed and one of them
failed so Jasmine gives us a lot of
details on where a test failed to help
us fix the
issue now let's add back math.round to
make everything pass again we'll open
our code and open UTS money.jpg
math.round Open Bracket and close
bracket and
save and if we check our test page
everything passes
again so this is how we use a testing
framework like Jasmine to create tests
the testing framework gives us a bunch
of functions such as describe it and
expect and then we use these functions
to create our test so so these functions
have a lot of features inside them they
do all of the setup for us and they also
display the test on a nice web page for
us now there's one more thing I want to
mention which is we can use describe
inside describe this helps us organize
our tests
further so now let's save our changes
into git we'll open the git
section and let's close this file at the
top for
now so inside money test.js we created
all the tests that we had before for
format currency by using Jasmine this
time and for spec Runner we rename this
file to test.html and finally we deleted
all the test code that came with Jasmine
so now let's add a message to describe
our
changes
remove default tests and add
money tests and
commit now let's test a different
function using Jasmine and along the way
we're going to learn some more features
of testing
Frameworks let's go back to our
code and we're going to scroll to the
top and open the data/ cart. JS
file so inside this file we have a
function called add to cart so we're
going to create tests for the add to
cart
function first since this function is in
a different file we're going to create a
new test file so we're going to scroll
down and let's close the test folder so
we don't get confused and then inside
test- Jasmine we're going to click in
this folder and then create a new file
and let's name it cart
test.js and press
enter so we name it the original file
name which is cart and then just add
test at the
end and to better organize our test
files we usually try to match the folder
structure of the code so for example in
our code money. JS is inside this UIL
folder so inside our tests we should
also create a utils folder and put this
file inside so we'll create a new folder
by clicking up here and let's name it
utils and press
enter and then move the money test.js
file
inside if it asks you if you want to
update Imports automatically you can
click
yes if you check your code scroll to the
top make sure that your file path starts
with do do slash do do slash because now
we're inside another
folder VSS code sometimes updates the
file paths for us automatically but if
it doesn't we can just add an extra dot
do slash in front
ourselves and we're also going to open
money test.js and save this
file next if we scroll up cart. JS is in
inside a data folder so inside our tests
we're also going to create a data folder
let's click cart
test.js we'll create a new folder and
let's name this the data folder and
press
enter and then move card test.js inside
here now you'll notice that this folder
structure doesn't perfectly match the
folder structure that we have up here
because utils is inside the scripts
folder but usually this data folder
should also be inside the scripts folder
I just made a mistake when structuring
the
project so let's just use this folder
structure in our
tests okay so now let's open cart
test.js and now we're ready to test the
add to cart
function so first let's import add to
cart at the top we'll import
curly brackets add to
cart from a
string and we're going to locate cart.
JS so first we need to get out of the
data folder using do slash and then get
out of the test djine folder do do slash
and we'll go into this data folder data
SL cart.
JS next let's create a test suite for
this function so we'll create some new
lines and to create a test Suite in
Jasmine we'll use the function
describe
brackets and we'll give this test Suite
A Name by giving it a
string so let's use the name test Suite
colon add to
cart and we'll give it a second
parameter which is a function brackets
arrow and curly
brackets and now inside this test Suite
we're going to add some tests so let's
look at the code for add to cart to see
what kind of tests we should
add so we'll open data/ cart.
JS and then inside add to cart you'll
notice that this function uses an if
statement a best practice in testing is
to test each condition of the if
statement
this is known as test coverage test
coverage means how much of the code is
being tested and a best practice is we
try to maximize test
coverage so for this if statement we'll
create a test for the first condition
which is when the product is already in
the cart and we'll create a test for the
else condition when the product is not
in the
cart let's go back to cart
test.js and inside this test Suite we're
going to create a test using the
function it brackets and we'll give it a
string and this will be the test name so
for the video I'm just going to scroll
up and take this cart. JS file and put
it at the top here so we can see our
code and our test side by side so I'm
going to scroll down to the add to card
function and we mentioned that we're
going to test each condition of this if
statement so the first test is going to
be when the product is already in the
cart so that here let's name it ads and
existing product to the cart comma
brackets arrow and curly
brackets and let's add another test for
when the product is not in the cart so
this else condition so down here we'll
create another test using it brackets
and a string and the test name adds a
new product to the cart comma and a
function brackets arrow and curly
brackets so these are the two tests that
we need for the two conditions of this
if
statement let's actually start with
adding a new product to the cart since
it's a little easier to
test now unlike the format currency
function add to cart doesn't return a
value so we can't really compare it to
another value using
expect instead we're going to call add
to cart to modify the cart and then
check if this cart looks correct to do
that inside here let's call the function
add to cart
brackets and this function takes one
string which is the product
ID so inside here let's give it a string
and to find a product ID that we can
test with we're going to go to the left
and scroll up and we're going to open
the data/ products. JS
file and inside here we have a list of
products so let's just take the first
product ID and use it in our test we're
going to select this ID and right click
copy and then inside cart
test.js in this string we're going to
rightclick and
paste so this will add this product ID
to the cart and now to check if this
code is working correctly we're going to
check what the cart look looks like so
first we need to import the cart we're
going to scroll up and since we're
already importing from cart. JS to UT
the cart we can type a comma
cart and then at the bottom here we're
going to create a new
line and first let's check if the card.
length is correct so if we assume that
we start with an empty cart when we add
a product the cart. length should should
be one so we can compare these two
values cart. length and one so to
compare values we're going to use the
function expect brackets and we'll
compare the
cart.
length and then here we'll use the
method2 equal brackets
1 so now let's save this
file and we're going to run these tests
to run them we're just going to load
this file inside test.html so we'll open
this and then at the bottom we'll create
a script
tag give it a source attribute double
quotes and we're going to load this file
so this file is inside the data folder
so we need to type data SL to go into
the folder and then load cart test.js
and this file also uses import so we're
going to give it the attribute type
equals module to enable JavaScript
module
features and one thing that I forgot to
do is we moved money test into the util
folder so we need to update the source
attribute to add the utils folder and
then slash to go into the folder and
then locate money
test.js so now let's save this HTML file
and open this test page in our
browser and now we should have two
additional tests and the test that we
just created should fail if it doesn't
fail for you you can go into your
console and run local storage. CLE and
then refresh the page and it should
fail so this tells us that the failure
happened in the test suite at Dart in
the test adds a new product to the cart
which is the one we just
created so it's telling us that the
cart. length is not equal to one it's
equal to a different number so why is
this happening let's go back to our
test open cart
test.js and in here remember that we
assumed the cart starts as empty and if
we add a product the card dot length
would be one however the cart doesn't
actually start as
empty in cart. JS at the top here we're
loading the cart from local storage if
there's nothing in local storage we use
this default cart so our starting cart
depends on what's inside local storage
and this is a big problem when testing
because local storage can change if
there's an empty card saved in local
storage our test will pass but if
there's not an empty cart in local
storage then this test will fail this is
known as a flaky test a test that
sometimes passes and sometimes fails
even if we don't change the
code now to solve this problem we're
going to use a feature of Jasmine called
mocks a mock lets us replace a method
with a fake version and then we can make
the fake version do anything we want for
example
when we load the cart from local storage
we're using local storage. getet item so
we can use a mock to create a fake
version of get item and then we can make
this fake version do anything we want
like return an empty
array so let's go ahead and create our
first
mock we'll go back to cart
test.js and at the top of this test
we're going to create a mock using
another function of Jasmine called spy
on and
brackets and we'll give spy on two
parameters the first parameter is the
object that we want to mock in our case
it's local storage so we'll type local
storage comma and then we'll give it a
string and this string will be the
method that we want to Mark in our case
we want to Mark the get item method so
here we'll type get item and make sure I
is uppercase so that we exactly match
the method
name so now this will replace local
storage. getet item with a fake version
and we can make this fake version do
anything we want to do that spy on gives
us an object and this object has a
property we can
use so at the end we'll type Dot
and the property called
an and this result is also an object and
this object has a method called dot call
fake brackets so don't worry about all
the Dots here Jasmine just organizes its
code so that it reads like English so
we're spying on local storage. getet
item and call fake so next we're going
to give call fake a function brackets
arrow and curly
brackets and this function is what we
want get item to do so we're essentially
overwriting the original get item with
whatever is inside this
function so earlier we said we wanted
get item to return the empty array for
this test so inside this fake function
let's make get item return the empty
array
now remember that local storage only
supports strings so we need to return
this as a string to do that we're going
to use the code Json all uppercase do
stringify Open Bracket and close bracket
so this will convert whatever is in the
brackets to a Json string and that's
what we need for local
storage so now let's test out this mock
to see if it works
below this we're going to
console.log
brackets and run local
storage doget capital I item brackets
the string
cart let's save this file and then open
the test page in our
browser and we're going to open the
console so
rightclick inspect
and the
console and you'll see that Here Local
storage. getet item is no longer loading
from the actual local storage it's
giving us an empty array every
time so now we have mocked the get item
method however you'll also notice that
our test is still failing so how come it
still
fails to understand what's happening
let's take a closer look at our code
we'll go back to our
code and inside our tests here we're
mocking local storage. getet item but
notice that above this if we scroll up
we import the cart at the top so the
order of this code matters first we load
the cart from local storage and after
we're mocking local storage. getet item
so the card is already loaded at this
point and this code doesn't have the
effect that we
want so one way to solve this problem is
after we mock local storage here we
should reload the cart so inside cart.
JS just going to give it a little more
space to reload this cart after we mock
we just need to rerun all of this code
so let's create a function so we can
rerun this code at the bottom here we'll
create a
function and we'll call it load from
Storage brackets and curly
brackets and we're just going to move
all of this code inside the function so
let's select all the code up to cart
equals we'll
rightclick
cut and then in the function we'll
rightclick and paste
and at the top let's create the cart
variable again let cart and
semicolon and lastly when we load this
file we need to run this function so
that we run this code at least
once so down here we'll just run this
function load from storage and
brackets so let's
save so we're basically running the
exact same code as before except this
code is now inside a
function and now in our
test after we mock local storage. getet
item we're going to reload the cart
using this function so first let's
export it so we can use it in our test
we'll type
export and save this file and Insider
test let's scroll up to the top we're
already importing from cart. Js so we'll
type a comma and we'll import load from
storage and then we'll scroll down back
to our test and here after we mock local
storage. getet item we're going to load
from Storage brackets and
save so this time we mock local storage.
getet item first to return an empty
array and then when we reload the cart
this is going to be an empty array and
the cart will be empty and now in our
test when we add a product to an empty
cart the cart length will be equal to
one so this test will pass so we can
actually remove the console.log here and
save and check our test
page and now this test should be
passing next let's go back to our code
Cod and if we look at the add to cart
function in cart.
JS so in here at the bottom of this
function you'll notice that we're saving
the cart to local storage so this is
going to call local storage. set
item however we don't actually want to
save to local storage because this is
just test code we don't want our test
code to be modifying local storage or
affecting our real code
to prevent this we're also going to mock
local storage. set
item so down here we're going to create
some new lines at the top of the test
and we're going to mock local storage.
set item using the function spy on
brackets and we'll give it local
storage comma a string and the method we
want to mock which is set
item and
save and remember the order of the code
matters so we want to mock local
storage. set item first and then we call
add to cart so now set item will be
replaced with a fake version and this
will no longer save to local
storage next spyon has another useful
feature which is it records every time a
method is used for example what if we
want to make sure that add to cart saves
the cart to local storage at the end in
our tests set item is mocked so we can't
really check what's inside the local
storage instead we can just check if add
to cart calls set item at some
point to check if set item was called at
the bottom we can use the function
expect
brackets and we're going to give this
the method that we loed which is local
storage. set
item and remember that expect gives us
an object and this object has many
useful methods to check stuff like dot
to
equal so another method we get from
expect is dot 2 have been called times
brackets
so make sure that you write this method
in cam case two is lowercase and every
word after starts with a
capital so this method checks how many
times local storage. set item was called
in the code above so we expect it to be
called once inside add to cart so we're
going to give it the number
one so keep in mind that this only works
if this method has been mocked with spy
on so now let's
save and open our test
page and you can see that all of our
tests passed and local storage. set item
was called
once so after we mock a method we can
check how many times this method was
called and we can even check what values
this method received but I'll leave that
as an
exercise another thing you'll notice
here is that each test can have multiple
expectations
and the test will only pass if all of
its expectations
pass now let's add a few more
expectations to this test for practice
so one thing we can check is we can
check the first product in the cart and
make sure that its product ID matches
this string here so below this let's use
another expect brackets and we're going
to check the first product in the cart
using cart square bracket
0 so this is going to be an object and
this object is going to have a property
called product ID so that here we'll get
the dot product
ID and we're going to check if this
product ID is equal to this string so to
do that we'll use the dot 2 equal method
brackets and we'll give it this string
here so let's just select this and
rightclick
copy and here right click and
paste another thing that we can check is
the quantity when we add a new product
to the cart the quantity should start
out as one so down here we're going to
add another
expect
brackets and we're going to check the
first product
cart square bracket
0.
quantity. 2 equal brackets one and
save now let's open our test
page and you can see that all of those
expectations
passed now let's move on and create the
test for adding an existing product to
the cart so we'll go back to our code
and scroll up to the first test
here so first we need to set up the cart
so that it already contains the product
that we want to add to do that we're
going to Mark local storage. getet item
again so down here we can just reuse
this code so we're going to select this
code and right
click
copy and then in the first test here
rightclick and
paste and this time do set up the test
we're going to put a product into the
cart at the beginning and then we're
going to add the same product to the
cart so inside this cart array let's add
an
object and each product has a property
called product ID so we're going to add
this property product ID colon
and let's just give the same product ID
that we used down here so we'll select
this and then right click
copy and then up here we're going to
right click and
paste
comma and each product also has a
quantity so we'll give it a quantity
colon and let's just give it one comma
and also a delivery option so delivery
option ID colon and let's just give it
the string
one and
save so now when we do local storage.
getet item it will give back this array
as the starting cart and then we need to
make sure that we reload the cart from
Storage next let's scroll down and let's
copy the rest of the tests because it's
going to be very similar so we're going
to select this code and
rightclick
copy and then up here create some new
lines and right click and
paste and also one thing I forgot to
copy over is to mock local storage. set
item so at the
top let's
also spy on brackets
local
storage comma a string set
item so a mock only lasts for one test
once that test is finished the method is
no longer mocked so that's why in this
test we also have to mock local storage.
set
item and now in this test we're just
going to modify these expectations so
that they make sense for this test
if we add an existing product to the
cart the cart. length will still equal
one because these product IDs match and
we're just increasing the
quantity we're still going to call local
storage. set item once so this is
correct
still the first item in the cart is
going to have this product ID and the
only thing we're going to change is that
the quantity is now going to increase by
one so it's going to go from one to two
this
time so everything is the same except if
we add an existing product we're just
increasing the quantity now let's
save and check the test
page and now the existing product test
is
passing and that's it we created tests
for the add to cart
function so now let's do some cleanup
and we're actually going to remove
everything from local storage since we
were modifying it earlier in the test
and we might have messed it up so on
this page we're going to
rightclick
inspect and open the console and to
remove everything from local storage
we're going to type the code local
capital S
storage. clear and brackets and press
enter and then we'll refresh the
page now finally let's go into get and
save our changes so we'll open our code
and we can close this one for
now and we'll open the get
Section so in cart. JS at the top we
basically put all the code that loads
the cart into a function so we can use
it in our
tests and then here we moved money
test.js into a utils folder in test.html
we're loading the new cart test.js file
and then inside cart test.js we added
some tests for the add to cart function
so now let's create a message describing
these
changes
create
automated tests for add to cart and
commit
the last thing we're going to learn in
this lesson is how to create more
complicated
tests so far we've only been testing a
single function for example we tested
the add to card function as well as the
format currency function so these are
called Unit tests because we're only
testing one unit or one piece of the
code now what if we want to test t a
whole page or part of a page and this
requires a more complicated test called
an integration
test an integration test tests many
units of code or pieces of code working
together for example in our code we're
going to go to scripts checkout thee
orders summary. JS
file and we're going to test this render
order summary function so this function
creates a whole section on the checkout
page and it uses many different
functions and libraries to create the
page so testing this function will be
considered an integration test because
it uses many different pieces of code or
units of code together so let's start by
creating a test file for this function
so this is in the orders summary. JS
file inside our test here let's match
the file structure that we have here
here so we're going to click test-
Jasmin and first we're going to create a
checkout folder so we'll click here to
create a
folder and we're going to name it
checkout and press
enter and then inside the checkout
folder we're going to create a new file
so we'll click this to create a new
file and we'll name it the same as above
order summary and ADD test
.js and press
enter so by matching the file structure
it's clear that this test file is going
to test ORD summary.
JS and again for the video I'm just
going to drag this file to the top here
so we can see this and the test side by
side and now we're going to test this
render order summary function so first
we're going to import this function into
to our test file at the top we'll import
curly brackets the render order summary
function from a string and we're going
to locate this file so first we need to
get out of the checkout folder and out
of the test Jasmine folder so we'll use
two do do slash do do slash and then
we're going to go into the scripts
folder and into the checkout folder
Scripts slash checkout slash and we'll
load order
summary.jpg
[Music]
order summary
a comma and a function brackets arrow
and curler
brackets and now what test cases should
we create render order summary creates a
part of the page so when we're testing a
page the two things we need to test is
how the page looks and how the page
behaves let's start by testing how the
page looks inside our test Suite we're
going to create a test using it brackets
and we'll name this test with a
string and this will just be a basic
test case so we'll describe what this
function does which is
displays the
cart comma and we'll give it a function
brackets arrow and curly brackets and
now we're ready to create the
test so render order summary usually
displays the cart on the page however in
our tests where does this cart get
displayed so if we look at the code in
this
function and we scroll down here we
generate the HTML for the
cart and then after we generate the
HTML we put the HTML inside an element
with the class js- order-
summary however we don't have this
element in our tests so to fix this
we're just going to create an element
with the class js- order-
summary to do this we're going to scroll
down and we're going to open the
test.html
file and then at the bottom we're going
to go to the body and then inside here
we're going to create a div so less than
div and greater
than so remember how we said we need to
create create an element with the class
js- order- summary we're going to create
that element and put it inside this div
so this div is going to act like a
container the reason we use a container
is that when we create elements in our
test we don't want to be modifying the
entire body because the body might
contain our test results from jasine so
we put everything inside a
container so now let's give this div a
class so we can use it in our JavaScript
we're going to give it a class equals
double quotes and we're going to call
this the js- test-
container to make it clear this is a
container for all of our test
code and
save and now let's get this container
into our tests we can do that using
document. query
selector brackets and a string and we'll
select the class using using a js- test-
container and then inside this container
we're going to create an element with
the class js- order- summary so to put
something inside this element we're
going to use the property do inner
Capital
HTML equals a template
string and inside this template
let's create a div element less than div
greater than less than SL div greater
than and as we mentioned we'll give this
element a class equals double quotes of
js- order-
summary so this basically takes this
HTML and puts it inside our test
container so it will put it inside here
and now we have the element that we need
for render order summary so when we call
this function it's going to create the
cart and display it in this element
here next if we look at the code for
render order summary and we scroll to
the
top you'll notice that it takes the cart
and then displays it on the page but
remember that by default we load this
cart from local storage and this can
cause problems in our test depending on
what is inside local storage so to fix
this we're going to mock local storage.
getet item again to control exactly
what's inside this cart so let's
actually open the cart test that we had
before and we're just going to copy
paste this mock that we created so we're
going to start from here this function
and we're going to select the code up to
spy on get item and then
rightclick copy
and then down here we're going to
rightclick and
paste and one other thing we need to do
here is we don't have access to load
from Storage right now so we need to
import it at the
top let's also copy the import that we
had here so we're going to select this
and then right click
copy and then down here we're going to
rightclick and paste the
import and we just need to make sure
that this file path locates cart. JS so
do/ do slash it's going to go outside
checkout and outside test- Jasmin and
then it will go inside the data folder
and then locate card. JS so this file
path is correct and currently we're not
using these two values so we can just
remove
them and now let's set up this cart for
this test so we could just use this cart
here however to make our test a little
more detailed let's open the cart. JS
file and at the top here we're going to
use this default card instead because it
has two products with different
quantities so we can test more things so
we're just going to select this card
here and then right click
copy and then down here open order
summary
test and we're going to select this card
and remove
it and inside these brackets we're going
to right click and paste that default
cart and now that the HTML and the cart
is set up for this function at the
bottom we can call the function render
order summary and
brackets and Save
so now let's run this test file we're
going to open test.html
and then beneath these tests we're going
to add another script Tech less than
script Source equals and we'll load the
checkout slash order summary test.js
file and we need to give it the
attribute type Ty
equals module because we used
Imports and let's save so we run this
test so we'll open our test
page and you can see that the cart was
rendered onto this test page and we
still have our Jasmine results at the
bottom here so you notice that when we
render this it didn't load any CSS or
images and this is okay because we can't
really use code to check if the page
visually looks correct however we can
use this to check the contents of the
page like if the products and the
quantities are
correct so first our cart has two
products in it so we can check if there
were two products that were rendered on
the page let's go back to our
tests and let's take a look at the
orderers summary. JS file
and when we render the order summary we
scroll down for each product in the cart
we create an element with the class
cart--
container since we have two products in
the cart let's check that we created two
of these elements on the page so we're
going to open the order summary test.js
file and then in the first test at the
bottom of this test we're going to add
some lines and we're going to check if
we have two of these elements to do that
we can use the Dom using
document. query selector all brackets
and a string and we could select the
class card- item D container however
this class is used for CSS so remember
if we're going to use a class in
JavaScript we start with js-
let's add a new class to this element
that we can use for the test we'll add
js- cart D item D
container so now we're going to select
all the elements with this class
using js- card- item D
container and let's save the ORD
summary. JS
file and then down here we're going to
check if we have two of these elements
on the page so again to check something
in our tests we're going to use the
function expect Open Bracket and let's
create a new line to make it a little
cleaner and at the end we'll give a Clos
bracket like
this and this code gives us an array of
elements so here we're going to check if
the dot length of this is equal to to
two so expect gives us an object which
has a method called dot 2 equal brackets
and two so this checks if we have two of
these elements on the page so let's
save and then check the test
page and scroll to the bottom and you'll
see that this test
passed so that's how we check if we
render the page correctly
next let's do another check of what we
rendered on the page so another thing we
can test is If the product quantities
are correct so first we need to get this
quantity element into our tests so we'll
go back to our
code and then inside the HTML of the
order summary we're going to scroll
down until we see a div with the class
product- quantity and we're displaying
the Quant
here so now we're going to take this
element put it into our test and check
that the quantity here is
correct so to do that let's give another
class to this element so we can select
it using JavaScript so here we'll add
another class
js-
product-
quantity and we want to check the
quantity for each product so we need to
identify which product this is for we
can do that by adding a dash to this
class and then inserting using dollar
and curly brackets the products ID which
is the matching product matching
product. ID and
save and now let's get this element into
our test so down here we're going to
document. query
selector
brackets and we'll give it a template
string because we're going to insert a
product ID so we're going to select this
class using a js- product- quantity Dash
and then insert the product ID so in our
cart we have two products and let's
start with the first product ID now to
make this easier let's put this string
inside a variable so we can reuse it
below so above the this let's create a
variable with const call it product
id1 equals and we're going to select
this ID and then right click
cut and then up here rightclick and
paste and then we're just going to use
this variable down here product
id1 and then when we're getting this
element into our our code we're also
going to insert the product ID which is
product
id1 but now we're going to check if the
text inside is correct so for the first
product we have a quantity of two so the
text inside this element should say
Quantity colon
2 so to check this at the bottom of our
test as usual we're going to use the
function
expect Open Bracket and a new line and
then here we can remove the semicolon
and close
bracket and we're going to get the text
inside this element now we're not going
to usein HTML because this element
contains a bunch of HTML inside but we
only want the text to get just the text
we're going to use the property do inner
text so we expect the text inside this
element to contain quantity colon
2 however this element also has some
other text like update and
delete so we just want to check if
quantity 2 is somewhere inside this
element so how do we check that to do
that we're going to use a different
method of expect called dot to
contain and
brackets and we're going to give it the
string that we want to check for which
is capital Q quantity colon
2 so the two contain method checks if
this value contains this string so they
don't have to be an exact match like
with two
equal as long as quantity colon 2 is
somewhere in this element then this
expectation will pass and this is
exactly what we need when this El has
some extra text that we don't really
need to
check so now let's click our test file
and
save and open the test
page and scroll to the bottom and you'll
notice that the test passed so for the
first product we're displaying the
quantity of two
correctly let's also check the quantity
of the second product we'll go back to
our
tests and and just like before let's
create a variable to store this ID so
we'll create a variable with const
product
id2 equals and we'll select this
ID and right click
copy and then here right click and
paste and then we'll remove
this and use the variable product
id2 and then at the bottom we're going
to get the quantity element for Product
2 so let's just copy this code because
it's very similar we'll select it right
click copy and then down
here right click and
paste so this time we're going to get
the quantity element for product ID
2 and in our cart product two has a
quantity of one so down here we're going
to check if the text contains quantity
colon 1 and
save and let's open our test
page and scroll to the
bottom and this test passed so we're
displaying the quantity of both products
correctly on the
page the second thing we can test in an
integration test is how the page behaves
for for example on this page we can
click the delete link to remove a
product from the page so let's create a
new test to make sure that the delete
link behaves
correctly we'll open our test
code and at the bottom we're going to
create a new test using the function it
and
brackets we'll give it a name and let's
describe what the behavior should be
which is removes a
product comma and a function brackets
arrow and curler
brackets now let's do the same setup as
the first test so we start with two
products in the cart so we can select
from load from storage and we'll select
all of this code up here and then
rightclick
copy and at the bottom
we're going to right click and
paste so this will set up the HTML
element that we need for the order
summary as well as the
cart and after this let's render the
order summary using the function render
order summary and
brackets so once we've displayed this on
the page we're going to get the delete
link and click it so first let's get the
delete link into our code so we'll go to
the orders summary. JS file and inside
the HTML we're going to scroll down a
bit till we see the delete quantity link
and let's test the delete link for the
first product in the
cart so first we need to add a class to
this element so we know which product
this is for so here we're going to add a
class JF s- delete
dink Dash and insert the product ID
which is the matching
product
doid and I'll add a new line to make the
code a little bit cleaner and now we can
save and then down here we're going to
get the delete link for the first
product ID so at the bottom we use
document do query
selector
brackets and we'll give it a template
string because we're going to insert the
product ID and we'll select this class
using js- delete
dlink D and then insert dollar curly
brackets product
id1 and now we need to click this delete
link to remove the first product from
the page and from the cart to click an
element using Code we can just get it
using the Dom and then use the method
dot click and
brackets so this will click delete on
the first product and remove it so let's
save and take a look at our test
page and unfortunately this test failed
so let's take a look at the details of
the failure to figure out how to fix it
so it's telling us that we cannot set
properties of null this means that a
value in our code is null and we're
trying to give it a
property and here it will tell us which
line we got this error from so this
error happened in our test file and the
line that created this error was in Ord
summary. js on line
132 or whatever line that you see here
on your page
so inside our code we're going to open
orders summary.
JS and I'm going to scroll down to line
132 and you can scroll down to the line
that you got on your
page so this line of code is actually
part of the code that we run when we
click delete so remember that when we
click delete we also update the payment
summary on the right side of the page
and that's what this line does now the
reason this is not working is if we open
the payment summary JS file and we look
at what this does at the bottom after we
generate the HTML we try to put the HTML
in an element with a class js- payment D
summary and this element does not exist
in our tests so one way to fix this is
to add this element to our
test so let's open our test again
we'll open the order summary
test.js and then we'll scroll
up and then here when we create the
order summary element we're also going
to create the payment summary
element so we'll create a less than div
greater than less than SL div greater
than and here we'll give it a class
equals double quotes and we'll give the
class that the payment summary needs
which is
js- payment D
summary and
save so now that the payment summary
element is set up we can open our test
page and our test should no longer have
a failure so you also notice that the
payment summary got rendered or
displayed on the
page okay so in our tests we only
clicked the delete link for the first
product but we didn't actually check if
the page looks
correct and that's what it shows here
with this yellow dot this test has no
expectations
yet so let's go back to our test and add
some expectations at the bottom so we'll
scroll down and down
here after we click delete for the first
product we expect that there's only one
element left on the page for the
cart so in our first test we actually
had a check for this so we can scroll up
and here we check if we have two cart
item containers on the page so let's
just reuse this check because it's very
similar we'll select it right click
copy and then down
here we're going to right click and
paste and this time we only expect one
cart item container to be left on the
page so so we'll change this to one so
we'll
save open the test page scroll down and
now this test
passed let's also do a more detailed
check so we're going to check that the
first product is no longer on the page
we'll go back to our
tests and then down here we're going to
get the card item container for the
first product we use
document. query selector
brackets and to get the element for the
first product we're going to open orders
summary. JS and then scroll up in the
HTML until we find the cart item
container
element and we're going to look for this
class right here which tells us which
product this element is for so in here
we'll give it a template string because
we'll in insert the product ID and we'll
look for this class using a
js-- item Das container Dash and insert
the first product so product
id1 and because we removed this product
from the page we expect this result to
be null so we'll use the function expect
open bracket and a new line and then
down here a close bracket and we'll use
the method
do2 equal brackets and we expect this to
be null and
save let's also check that the second
product is still on the page because we
didn't delete
it so let's just make a copy of this
check we'll select it right click copy
and then
here right click and
paste and we'll get the element for
product ID 2 this time and we want to
make sure that this exists so that it is
not equal to null in Jasmine to check if
something is not equal
to expect gives us another property we
can use called dot
not so if we use theot property it will
check the opposite of whatever is next
so this will check if this value is not
equal to null so remember the code for
Jasmine is designed to read like
English let's save and check the test
page and scroll
down and this test passed so we're
displaying the correct products on the
page after
deleting now there's one more thing that
we need to check here which is after
deleting is the cart array itself
updated so we'll go back to our code and
add that
check so first we need to import the
cart so we can use it in this test we're
going to scroll up to the
top and we're already importing from
cart. JS so we'll add a comma and import
the
cart and then at the
bottom we're going to check if the card
is correct
so the cart started out with two
products inside after removing the first
product the card should have a length of
one and the remaining product should
have product id2 so let's add both of
these checks at the bottom so we'll
scroll back
down and we'll use expect
brackets and we'll check if cart. length
do 2 equal brackets
1 and we'll also expect brackets and
we'll check the first product in the
cart which is cart square bracket 0 and
we'll check its product ID do2
equal and it should equal product ID 2
so product id2
and
save so let's open our test
page and scroll to the bottom and this
test still passed so once we click
delete the card array is also
correct so that's how we create an
integration test it tests many units of
code or pieces of code working together
and it lets us test how our page looks
and how our page behaves
now there's one thing that I forgot to
do when we created these tests if we
look at our
code and I'm going to open orders
summary.
JS when we click delete at the bottom
here it uses a function called remove
from
cart and if I look at the code for this
function which is right here remove from
cart this function actually saves the
cart to local storage and and calls
local storage. set
item however it's recommended not to
modify local storage in our test so
inside the order summary test file we
should also mock local storage. set item
in this test so we'll scroll to the
top and at the start of the test let's
mock set item using spy on
brackets local
storage comma the string set
item and
save and we'll open the test page and
make sure that the test still passes and
we might have messed up our local
storage because of that mistake so let's
reset local storage again we'll right
click on this page
inspect open the
console and we'll type the code local
storage. CLE brackets and press
enter and refresh the page just to be
safe now another thing that we might
want to add is that when we render the
order summary on the page it's taking up
a lot of space and it pushes the test
results to the bottom so what we can do
is after our test we can actually remove
all of this
HTML so let's go back to our code
in the order summary test file at the
end of the first test we'll create some
new lines and remove the HTML that we
created to do that we can scroll up to
this code so to remove the HTML we can
just set this element inner HTML to the
empty string so we'll select this code
right click
copy and then down here right click and
and
paste so in our test all the HTML we
created was placed inside this test
container and we're just going to remove
all that
HTML by setting the inner HTML to the
empty string and we'll do the same thing
for the second test so we'll select this
code rightclick
copy and then down here at the
bottom we'll right click and
paste so this is just some cleanup we
can do at the end of each test let's
save and look at our test
page and now all the HTML that we
generated is gone and we can see the
test results more
clearly lastly we're going to learn a
shortcut we can use in Jasmine called
hooks a hook lets us run some code for
each test for example
if we go back to our code notice that
before each of our tests we do a bunch
of setup here so we can actually share
all of this code between our two tests
using a hook so to create a hook we're
going to scroll up to outside of both of
these
tests and at the top of the test Suite
we're going to use another function
provided by Jasmine called before
capital E
each brackets and we'll give this a
function brackets arrow and curler
brackets so this is called a before each
hook and it will run this function
before each of our
tests so inside this function we can put
our setup code so that we run the setup
code before each of our
tests let's actually take the setup code
for the second test because it's a
little more
detailed so down here we're going to
select the code starting from render
order summary all the way up to mocking
local storage. set item and we'll
rightclick and cut this
code and remove these new
lines and then at the top inside before
each we're going to rightclick and paste
so now before each of our tests it's
going to run this function and it's
going to run all of our setup code so
this is a great way to share code
between our tests and remove
duplication so now that we're running
this inside before each if we scroll
down to the first test we don't have to
run this code again so we can actually
remove
it and we'll remove this Mock and we'll
remove the render order summary as
W and all we're left with are the
expectations for our
test now before we save we need to fix
one thing with this code here so right
now these two variables are inside this
function and because of scope these will
be contained inside this function and we
can't use it down here in our
tests so to fix this we can just move
these variables outside of this function
up here so we're going to select these
lines and then right click
cut and up
here we're going to right click and
paste so now any code inside this outer
function can use these two variables
including our
tests so now let's
save and check the test
page and everything is still still
passing so that's how we use a hook to
run some code before each test now
before each is not the only hook that we
can use Jasmine provides several hooks
that we can use in our
tests another common Hook is after each
which lets us run a function after each
test so this is really useful for
cleanup code like we have down here when
we remove the
HTML all leave using after each as an
exercise now let's go into git and save
our changes and I can close these three
files at the top for
now so we'll open the git
section and then inside orders summary.
JS we added some classes that we're
going to use in our
tests inside test.html we are loading
our order summary test file and we also
created a test container where we're
going to put our HTML that we
generate and then for the order summary
test file this contains the test that we
created for the order
summary now let's create a message
describing our
changes create automated tests for order
summary and commit
now that we've created all these tests
for our project when we make some
changes to our code we can just open the
testing page and it will rerun all of
our
tests so here's the process that we do
when we write code first we make changes
to our code and then we rerun the tests
to make sure that everything still works
and finally we save our changes into
git now before we end the lesson we're
going to do one more cleanup we'll go
back to our
code and we'll open our
files and here we usually organize all
of our tests into a folder called tests
however in this lesson we named this
folder test- Jasmin because we wanted to
compare this folder to tests that were
created without a testing framework but
now that the lesson's over we're going
to rename test- Jasmine to just test to
make it more
standard first we need to rename this
folder up here so we'll right
click
rename and let's rename it to test-
simple because this folder contains
tests that were created without a
framework let's press enter
and now we can rename test- Jasmine to
test by right clicking
rename and rename it to tests and press
enter another thing we can do is we're
going to drag test- simple into the test
folder so that all of our tests are
contained in one
folder so if it asks you to update the
Imports you can click yes
and we also need to open money test.js
in the test- simple folder because it
updated the Imports and then save this
file finally we're going to run all of
our tests again to make sure everything
still works after we move things around
so because test.html is inside a
different folder now we need to reopen
this with live server
so we'll rightclick and click open with
live
server and it'll show us that all the
tests are still passing so our code is
still
correct so now we can close some of
these extra tabs
here and save our changes into git we'll
open the git
section and all of these changes are
related to renaming the folders
so we'll give a message at the
top rename test- Jasmine
folder to
tests and
commit and that's the end of this lesson
in this lesson we learned how to test
our code using manual and automated
tests we learned how to organize our
test using test cases and test Suites we
learned how to use a testing framework
like Jasmine to help us write tests
easier we learned how to Mock and spy on
methods we learned how to test web pages
using integration tests and we learned
about hooks which lets us share code
between our
tests here are some exercises to help
you practice what we learned in this
lesson e
in the rest of this course if you get an
error in your project but your code
looks correct you may have some bad data
saved in local storage to fix this you
can try running local storage. CLE in
your console to remove everything from
local
storage and then refresh the
page if you see an error like this
object object that means that you saved
something directly into local storage
but you have to jason. stringify it
first so check your code to make sure
that you're always stringifying before
saving to local storage and then clear
your local storage and refresh the page
in this lesson we're going to learn
objectoriented
programming objectoriented programming
or oop is another style of programming
so it's another way that we write our
code it's useful to know because many
programming languages use
oop now how do we use objectoriented
programming object-oriented programming
is basically organizing our code into
into
objects let's look at an
example we're going to go to our
code and we're going to scroll up and
open data/ cart.
JS inside this file we have the code for
our cart and you'll notice that for the
cart we have some data at the top and
then we have a bunch of functions at the
bottom that modify the cart and these
are separate from each other the data
and the functions so this style of
programming that we've been using
throughout this course is called
procedural programming procedure means a
set of step-by-step
instructions and this is basically a
function so in procedural programming we
organize our code into separate
functions like we did
here on the other hand in objectoriented
programming we organize all of this code
into an object so we put everything
together into an
object so let's do an example and
convert this cart code into
objectoriented
programming we're going to click cart.
JS and inside this folder we're going to
create a new file by clicking
here and let's name this file
C- oop or objectoriented
programming. JS and press
enter and now we're going to copy all of
the code in cart into this new file so
let's open this and we'll click in this
file and then we'll type control a or
command a to select all the code and
then right click
copy and inside C- oop we're going to
rightclick and paste
and let's scroll back up to the
top and now to convert this code into
objectoriented programming we're going
to group all the data and the functions
together into an object first at the top
let's create an object that we can put
all of these inside
of so we'll create a variable const
let's call it cart equals and object
and now we're going to group our data
and all of our functions into this
object so let's do it step by step and
we'll start with this cart
variable as a reminder cart semicolon is
actually a shortcut for cart equals
undefined to make things easier to
understand let's actually write this out
in full instead of using the shortcut so
we'll type cart equals undefined
and now we're going to move this into
the object so we'll select this
line and then
rightclick
cut and then inside the object we're
going to rightclick and
paste now inside an object we can't use
the word export or
let so to move a variable into an object
we're going to convert it into a
property and a value so we'll remove
these
words and then type cart and colon
undefined and remove the semicolon and
replace it with a
comma so this is the same thing as cart
equals undefined but we move that value
into an
object now one problem here is that if
we access this cart property we're going
to do cart. cart which can be a bit
confusing so let's actually rename this
property to cart capital I items instead
to make it a bit more clear that this
contains the items in the cart or the
products that are in the
cart next we're going to group all of
our functions into this object as well
so let's create some new
lines and we're going to move this
function inside here so let's select
this
function and then
rightclick
cut and inside the
object we're going to
rightclick and
paste and again we can't use the word
export inside an object so we're going
to convert this into a property and
value as
well so let's remove these words
and let's make the property name load
from storage and then we'll type a colon
and we'll make the value a
function brackets and curly
brackets so that's how we move a
function into this object now make sure
that you use a regular function syntax
here and not an arrow function and I'll
explain why later in this
lesson now as a reminder when we have a
function inside an object
we call this a
method also JavaScript has a shortcut
for methods called the shorthand method
syntax so instead of typing colon and
function we can actually just remove
this
code and just type brackets and curly
brackets after the function name and
this is a shortcut for the code that we
had
before now the code inside this function
doesn't actually work anymore because
cart was actually renamed to cart items
so we have to rename this variable so
instead of cart we're going to do cart
dot cart
items to access this value and same
thing here cart do cart
items and here cart
doart
items so so this code Works however we
have a small problem here if we change
the name of the object up here this code
will no longer
work to solve this problem JavaScript
has a feature called this this gives us
the object that contains this function
so it gives us this outer object up here
so to improve our code we're going to
change from using a variable named cart
to this and here as well this. cart
items and this Dot card
items so this will give us the outer
object and now this code will always
work and it doesn't matter what the
variable name
is the last thing we're going to change
in this function is we're currently
loading from local storage
cart however our original cart was also
loading from local storage cart so let's
actually change this to C- oop so that
we don't affect our original
cart let's move on and we're going to
move the other functions into this
object so let's go down to the next
function which is save to storage we're
going to select this and then
rightclick
cut and then inside this object at the
end we're going to add a comma and some
new
lines and we're going to rightclick and
paste and we can't use the word function
at the front here so let's remove this
word and just use the shorthand method
syntax so this is a shortcut for colon
function and here we're saving to local
storage cart
so let's also change this to C- oop so
we don't affect our original cart so
we'll change it to card-
oop another thing we need to change is
that the cart was renamed to cart
items so here we're going to change from
cart to this which gives us the outer
object and then dot cart items
which is this property so it should do
the same thing as before except this
function is now inside an
object let's continue and move another
function into the object so we're going
to do add to cart this time so let's
select this
code and then
rightclick
cut and inside the object we're going to
add a comma and some new lines and then
rightclick and
paste so again instead of using export
function we're just going to remove this
code and use the shorthand method syntax
which is a shortcut for this
code and now let's update the code
inside this function as well so instead
of the cart we rename this to this. cart
items so we'll change it to this do cart
items
and then down here we're going to change
from cart to this. cart
items and also the function save to
storage was moved inside the object so
now to access this function we're going
to get the outer object again using this
and then dot save to storage so down
here we'll add this dot in front to
access the function inside the
object and now let's move on and move
the next function into the object so
we'll select this
code and then
rightclick
cut inside the object add a comma and
some new lines and right click and
paste we'll remove export
function and use the shorthand method
syntax and again we'll change from cart
to this. cart
items we're going to change cart here to
this.c cart
items and change save to storage to this
do save to
storage so we access save to storage
inside this
object next let's move this last
function into the object so we'll select
the code and then rightclick
cut and inside the object we're going to
type a comma and some new lines right
click and
paste we'll remove export function and
use the shorthand method
syntax and update the code in this
method so we'll change cart to this do
cart
items and save to storage to this Dove
to
storage now let's remove the extra
lines and the last thing we need to
update is that load from Storage was
moved inside the cart object so to
access this function at the front we're
going to type
cart. load from storage and save this
file and that's it this is the basic
idea behind objectoriented programming
we organize our code into objects so we
group the data and the functions
together into an object like
this now let's talk about why do we use
objectoriented
programming objectoriented programming
tries to represent the real
world in the real world a cart is a
physical object object so in
objectoriented programming we represent
this physical object as a digital object
or in this case a JavaScript
object a physical cart can have products
inside so our JavaScript object can also
have products
inside a physical cart also has actions
we can take to modify the cart like we
can add a product or remove a product
our JavaScript object also has actions
we can take to modify the cart like the
add to cart function or the remove from
cart
function so as you can see
objectoriented programming tries to
represent the real world we take a
physical object like a cart and
represent it as a digital object like a
JavaScript
object and some people feel feel that
this makes the code more intuitive or
easier to
understand now let's try out the code in
this object to make sure it actually
works we're going to scroll down to the
bottom and
here we're just going to type
console.log the
cart and save this
file and now let's load this code into
the project to do that we're going to
open the scripts folder and open the
file checkout.
JS and at the top below the Imports
we're going to import our new file so
let's type
import and we're going to use a slightly
different syntax we're just going to
type a
string and give it the file that we want
to load so we need to load C- oop. Js
so first we need to get out of the
scripts folder using do slash and then
go into the data folder data slash and
load C-
oop.
JS so this is another syntax we can use
for imports this just runs all the code
inside this file without importing
anything which is what we need in this
situation so let's save this file
and then open this page in the browser
so if you don't have this page open you
can scroll down to checkout. HTML and
then right click and open with live
server I already have this page open so
I'm just going to open that
Tab and if the page is too big we can
zoom out by pressing control minus or
command minus a few
times and now let's check the console to
see what the cart looks like on this
page we're going to
rightclick and click
inspect and then open the
console and in the console we'll see
this cart object so inside this object
we have the data as well as all the
functions for our cart but it's grouped
inside an object and you'll see that the
code still works the same as before cart
items has a the two default
products if we look at our code and open
card-
o at the beginning we run cart. load
from storage and then inside this
function if we scroll up it will give
the cart items this default cart with
two products inside and that's what we
see in the console
here so we know that the code inside
this object still works works the same
way as
before so now let's try another method
to make sure that it's working so let's
try using the add to cart method to add
a product to the cart items up here so
we'll scroll
down to the bottom and then above
console.log cart we're going to call add
to cart now add to cart was saved inside
this cart object so to access it we're
going to type
cart. add to cart and
brackets now add to cart takes one
parameter which is a string and this is
the product ID that we want to add so to
find a product ID we can go to the data
folder and products. JS and then inside
here we have this list of products so
let's actually scroll down to the third
product which is right here so this
t-shirt product and we're going to add
this product ID to the cart so let's
select this ID we're going to
rightclick
copy and then inside C-
oop inside the string we're going to
rightclick and paste that product
ID and let's
save and let's check the console
so I'll open the console
Here and Now inside the cart object if
we expand it cart items now has three
products because we just added a new
product to the cart so this shows that
all of the code is working the exact
same way as before we just organized it
into an object and that's objectoriented
programming now that we're done with
this example let's remove these two
lines of
code and
save next another reason we use
objectoriented programming is it's easy
to create multiple objects for example
the real amazon.com has a feature called
Amazon business where you can have a
separate cart for your business
purchases so how do we create two
separate carts in our code with
objectoriented programming this is easy
we can just make a copy of the cart
object so we can scroll up in this
code and I'm just going to click this
Arrow here beside the card variable to
collapse this code and to create a
separate cart for business purchases
we're just going to select this code and
then right click
copy and at the
bottom right click and
paste and now we have two separate cards
so let's scroll up to the top of the
second cart which is right here and we
said that we wanted this card for
business purchases so let's rename this
to
business Capital C
cart and when we load from Storage let's
load it from cart Das business instead
so that it doesn't conflict with the
cart up
here and if we scroll down same thing in
save to storage let's save this cart to
cart Das
business and finally let's scroll down
to the
bottom and here instead of cart. load
from Storage we're going to change this
to business cart. load from Storage
and that's it we just created a
completely separate cart simply by
copying this object so object-oriented
programming makes it easy to create
multiple
objects so now let's console.log both of
these cards to see what they look like
we're going to scroll to the
bottom and here we're going to
console.log the
cart and
console.log the business cart and
save and if we open the console for the
checkout
page it will show us that we have two
carts the regular cart has three
products inside and the business cart
has two products inside and these are
just the default products that we get
when we first load the cart
so you can see that these two cards are
completely separate from each
other in the real world we can have two
physical cards that are completely
separate from each other and in
programming we can also have two cards
that are completely separate from each
other by simply making a copy of the
object so again object-oriented
programming tries to represent the real
world
now currently there's an obvious problem
with how we're creating multiple objects
which is we're copy pasting a lot of
code and this can make our code messy
and hard to manage so now we're going to
make our code cleaner by using a
function to create multiple
objects so first let's delete this
business card that we copy pasted so
we're going to select this
object and then up to here the business
card we're going to remove
it and now instead of copy pasting this
object we're going to use a function to
generate these objects so at the top of
this file let's create a new
function and we'll name it capital c
cart brackets and curly
brackets so by the way in objectoriented
programming a naming convention is to
use Pascal case for things that create
or generate objects in Pascal case we
start every word with a capital
including the first word so that's why
we started cart with a Capital
C now inside this function we're going
to create cart
objects so let's actually move this
object into the function so we can
create it using the function so we're
going to select this object to here and
then we'll right
click and cut
and then move it into the function by
clicking in the function and then
rightclick and
paste so now every time we run this
function it will generate a new cart
object and we don't have to copy paste
this code over and over to create
multiple
objects so at the bottom I'm going to
click this Arrow to collapse this object
for now and at the bottom of this
function we're going to return this C
object so we can use it outside the
function okay now let's give this a try
and we'll use this function to generate
cart objects so first let's create the
normal cart using const cart make it
equal and we'll run this function to
generate an object Capital C cart and
brackets and let's generate another
object using the function using const
and we'll name it business
cart equals Capital C cart and
brackets and we'll still load from
storage for both of these and then
console log both of
these so basically instead of copy
pasting all the time we're going to use
a function to generate
objects so now let's
save and then open the
console and and now we have two cart
objects
again however now both of these carts
have three products
inside but before the regular card had
three products and the business card had
two
products so what
happened if we go back to our code and
look inside this cart
object you'll notice that we're loading
from the same key in local storage which
is C- o that means every cart that we
generate will be getting its data from
the same place in local
storage so to fix this we're going to
replace C- oop with a parameter so
different carts can use a different key
in local storage so at the top let's
create a parameter called local storage
key and then instead of using the same
string every time we're going to use the
parameter local storage
key and the same thing for save to
storage instead of saving to the same
key every time we're going to replace
this with the parameter local storage
key and finally when we run this
function at the bottom
here we need to give the function a
local storage key so for our regular
cart let's use the string cart C-
oop and for the business cart we can use
a different key like the string cart Das
business so now these two carts will
load from different keys in local
storage and they can have different data
so let's save and then check the
console and now our regular card has
three products and our business card has
two products like
before so let's go back to our code and
this is a better way to create multiple
objects instead of copy pasting a bunch
of code every time we can create a
function that generates
objects so now let's save this example
into git we'll go into our git
section and then at the top here we
created a function to generate these
objects and in checkout. JS we are
loading that c - oop practice file so
we'll type a message to describe these
changes create oop or objectoriented
programming version of cart and
commit next we're going to learn an even
better way to generate objects
object-oriented programming has a
feature called a Class A Class is
specifically designed for generating
objects a class is basically an object
generator So currently if we open our
code and then open C-
oop we learn how to use a function to
generate objects in objectoriented
programming so now we're going to switch
this to using a class to generate these
objects instead because classes are
cleaner and have more features than
using a function so first let's create a
new file for learning
classes inside the data folder we're
going to click C- oop and then create a
new
file and we'll name this file cart DCL
class. JS and press enter
so first let's copy over all the code so
we can compare it we're going to open C-
oop click this file and then press
contrl a or command a to select the code
and right
click
copy and in
C-Class we're going to right click and
paste and we'll scroll to the
top and at the top we're going to create
our first class class using the word
class and now we're going to give a name
to this class so let's name it the same
as here Capital C cart and then curly
brackets as a reminder a naming
convention is to use Pascal case for
things that generate objects so that's
why we start this cart with a Capital
C so this is a class A Class is
basically an object
generator so now inside the class we're
going to put the properties and methods
that we want for each object that we
generate so here we have our properties
and methods we're just going to move
them into the
class so first let's select the card
items
property we're going to right click
cut and then move it into the class by
clicking in here and then right click
and
paste and classes use a slightly
different syntax than objects so to
create a property called cart items
we're going to type the property name
and instead of a colon we're just going
to make it equal to undefined and
instead of a comma at the end we're
going to put a
semicolon so that's how we add a
property to a class and now every object
that we generate will have this property
just like we did
before next let's move the methods into
the class so we'll delete these lines
for now and we'll move load from Storage
so we'll select this method and then
rightclick and
cut and inside the class we're going to
move it by right clicking and
paste and classes use a slightly
different syntax to create methods as
well so instead of having a comma at the
end we can just remove it and every
object that we generate will now have
this
method so now let's move the rest of the
methods into this class we're going to
scroll down and we'll move save to
storage so we'll select the method and
right click
cut and at the bottom of the class we're
going to right click and paste
and remove the comma at the
end same with add to cut we'll select
this
method and then right
click
cut and inside the bottom of the class
we're going to rightclick and
paste and remove the comma at the
end as well as remove from cart so we'll
select this
method right click
cut and at the bottom of the class right
click and
paste and remove the comma at the
end and finally we'll move the last
method update delivery
option and right click
cut inside this class we're going to
right click and
paste so this method did not have a
comma at the end so this looks
good so that's how we create a class we
basically give it some properties and
methods and now when we generate objects
using this class every object that we
generate will have these properties and
methods now one thing we need to fix
here is that local storage key doesn't
exist anymore to fix this we're going to
save this in a property instead so at
the top
we're going to give a new property to
every object that we generate called
local storage key and make it equal to
undefined to
start and then inside the methods we're
going to switch this to this. local
storage key so this is going to point to
the object that we generate just like
before and then local storage key will
access this property
and another place we need to fix this is
inside save to storage so instead of
using a variable local storage key we're
going to use the property this. local
storage
key and that's it so if we scroll
down we basically converted this whole
function into a class so now we can
remove it
and the final step here is now that we
have this class let's use it to generate
these two objects
again to do that instead of this code
we're going to type the word new and
then type the class name which is
capital c cart and
brackets so you see that a class uses a
similar syntax as a function except we
use the word new in front of
it so this generates a new object using
our
class and this new object will have all
the properties and methods that we added
above so let's do the same thing for the
business card we'll use the class to
generate it we'll remove this
code and then we'll type new and the
class name Capital C cart and brackets
to generate another object using this
class now there's one thing we need to
fix here each of these objects has a
property called local storage key and
they're currently undefined so we need
to set this
property so at the bottom here we're
going to type
cart. local storage key and we'll make
it
equal and we'll use the same string as
before which is C-
oop and we'll do the same thing for the
business cart we'll type the
business
cart. local storage
key and make it equal the same string
that we had before which is cart Das
business and then we'll load the cart
from Storage as well as the business C
from storage and we'll console.log
them so we have the same code as before
except we converted it from a function
to a
class so now let's
save and we're going to run this code So
currently if we go into our code and
open checkout.
JS we're still loading C-
oop so we're just going to update this
and load
C-Class instead and
save and we'll open cart Das class
again and now if we open the
console you can see that we created two
cart objects just like we did
before and the regular card has three
products inside and the business card
has two products
inside and if we click this Arrow beside
prototype we can see the methods that
each of these objects have
so we're basically creating the same
objects that we had before except this
time we used a
class by the way each object that we
generate from a class is called an
instance of the
class we can also check if an object is
an instance of a class using the code
business cart and then instance of and
then the class name name Capital C
cart so this will check if this object
was generated from this class so we can
console.log this result
console.log and close bracket and
save and then check the
console and it will tell us that this is
true so business card was generated from
this
class okay don't worry if class are a
bit confusing at first just remember
that objectoriented programming means
organizing our code into objects because
this tries to represent the real
world and then classes are a feature
that help us generate these objects so
they make it easier to create these
objects a class is basically an object
generator
now that we learned how classes work
let's talk about the benefits of
classes if we scroll
up when we generate an object it's going
to have these properties and these
methods and you'll notice that a class
actually looks like the object that we
generate and this is cleaner than using
a function like we had before
another benefit of classes is that they
have extra features for object-oriented
programming the first feature is called
a Constructor which lets us run some
setup code after creating an
object so if we scroll down in our
code you'll notice that after we create
these objects we run some setup code a
Constructor lets us put the setup code
inside the class and this makes our code
cleaner because we can group everything
together inside the
class to create a Constructor we're
going to scroll up in the
class and Below these properties we're
going to create a new method called
Constructor brackets and curly
brackets so the Constructor method works
like a normal method we can put code
inside and it will run the
code but the special thing about the
Constructor is that when we generate an
object it will run this Constructor
automatically so this is a great place
to put our setup
code so let's scroll down to the
bottom and here instead of running the
setup code outside the class we're just
going to move this into the class and
into the Constructor so we'll select
this code
and then right click
cut and scroll to the
top and inside the Constructor we're
going to rightclick and
paste so now after we create an object
it will run the code in the Constructor
and set up the
object so there's a few things that we
need to fix here the first thing is each
object object that we create is going to
run the Constructor so we only need one
of each of these lines so let's remove
the setup for the business
card so now the setup code has two steps
we set the local storage key and then we
load from Storage the next problem is
that the object that we create is not
going to be called cart every time
to solve this we can replace cart with
this and here as well this. load from
Storage so as a reminder this points to
the object that we generate so whatever
object that we generate we're going to
get its local storage key and set it and
we're going to get its load from Storage
method and run that
method now the second problem here is
that we don't want local storage key to
be card- oop every
time to fix this the Constructor can
also have parameters let's give the
Constructor a parameter and we'll name
it
local storage key and instead of the
same string every time we're going to
use local storage
key now the last thing is how do we save
a value into this parameter
so if we scroll down to the
bottom when we call the class between
these brackets we can put the parameters
for the Constructor so for the cart we
want the local storage key to be the
string C- oop and for the business cart
we want the local storage key to be the
string cart Das
business so the values inside here are
saved in the parameters in the
Constructor so C- oop will be saved
inside local storage key and then we use
it and then the same thing for cart D
business so now let's save this
code and then open the
console and you'll see that the cart
objects are correct so after we
generated each object we also ran this
setup code so that's how the Constructor
works every time we generate an object
it will run the code inside here so this
is a great place to put setup code and
make our code
cleaner so here are a few more details
about the
Constructor the method has to be named
Constructor we can't just use any name
that we want we also should not return
anything from a
Constructor so last ly a shortcut that
we can use in a class is when we have a
property and it's equal undefined we can
actually remove equal undefined and just
use a semicolon so this is the same
thing as the code before and same thing
here we can remove equal undefined and
just use a semicolon and
save so we finished converting our code
from using a function to using a class
and as you can see a class is just a
better way to generate objects in
objectoriented
programming so now let's save our code
into git we'll open the git section
inside cart Das class we created our
cart class and inside checkout. JS we're
basically loading the cart Das class
file so we'll type a message to describe
this change create
class
version of cart and
commit next we're going to learn an
important feature of classes called
private properties and
methods so let's open our code again and
open
C-Class and you'll see that this class
has a property called local storage
key so this property is useful inside
the class but it's not really meant to
be used outside the class for example at
the bottom
here we could take this
object cart and then change the local
storage key using dot local storage key
equals something
else now this is a problem because it
will mess up how this object works and
it will start saving to a different
local storage key so this is a common
problem in programming where if you're
working on a team somebody might
accidentally change properties that
they're not supposed to to prevent this
classes let us make a property or a
method private which means it can only
be accessed inside the
class so let's remove this line
and scroll
up and to make local storage key private
we're just going to add a number sign in
front or a
hash and also whenever we access this
property inside the class we're going to
add the hash in front so we'll type
this. has local storage key this.h local
storage key and inside save to storage
this.h local storage
key so this is called a private property
this means it can only be used inside
this class or inside these curly
brackets it cannot be used outside the
class a property without a hash in front
is called a public property meaning it
can be accessed
anywhere so now let's
save and open the console
and the code still
works so we made this property private
and we're able to access it inside the
class so now let's try accessing this
property outside the class to see what
happens we're going to scroll
down and we're going to try to access
cart. hash local storage key
and change it to something else like
test and
save and if we open our
console you'll see that when we try to
access a private property here it will
give us a syntax error saying this is a
private field and by the way a field is
the same thing as a
property so that's how a private
property works it prevents us from
accessing this property
outside the object and messing it
up we can also have private
methods so let's remove this
line and scroll
up and the method load from Storage
should also only be used inside this
class there's really no reason for code
outside to be calling load from Storage
so to make our code safer we're going to
make this a private
method to make a method private we're
going to do the same thing in front of
the method we're going to add a number
sign or a hash and we're going to update
the rest of our code so we're going to
do this dot hash load from
storage and now we can
save and check the console to make sure
that everything is still working so
everything still looks good
because we're only using this private
method inside this
class so a class Let's us create private
properties and methods and this is
useful on a bigger project where people
might not be sure which properties and
methods they're supposed to use outside
the class and which ones to
avoid so now let's save our changes into
git we'll go into the git section and
inside here we we made local storage key
and load from Storage
private we'll create a message to
describe these changes make local
storage key and load from Storage
private and
commit now that we learned
objectoriented programming and and
classes we're going to use it in our
project so one thing we could do is to
take this card class and replace
everywhere we use cart in our project
however we use cart in a lot of places
and this would take too much time so I'm
going to leave replacing the cart as a
challenge
exercise instead we're going to work on
the
homepage so first let's go back to our
code and we're going to open checkout.
JS and we're just going to comment out
this import because we're just using
this file for practice so let's save
this and then let's open the checkout
page so I already have it open if you
don't have it open you can rightclick
checkout. HTML and open with live
server on the checkout page we're going
to click this icon in the top left to go
to the
homepage on this page we have a list of
products
here and the code for these products is
if we go back to vs
code and on the left side we're going to
open
dataproducts
DJs so here is the code or the data for
all the products on the homepage and
you'll notice that each product is an
object we're going to learn a technique
called converting an object into a
class so what this means is instead of
using regular objects in this array
we're going to use a class to generate
these objects so Above This array let's
create a new class using the word class
and let's call it capital P product and
curly brackets
because this class is meant to generate
products so now each of our products is
going to have some properties like the
ID image and the name so let's add these
to the class We'll add the ID property
and a semicolon so that it starts off as
undefined and then an image property and
a name
property and each product will also have
a rating and the price sets rating and
price
set and you'll notice each object here
also has a property called keywords now
we're not currently using this in our
project so we're going to leave it out
of the class for now and if we need to
use it later we can always add it back
in so now we have all the properties
that we want for each product so now
let's test this by generating a product
using this class so that here
let's create a variable const product
one equals and to generate an object
we're going to use the word new and then
the class name capital P product and
brackets and let's console.log this to
see if it worked
console.log product one and
save so now we're going to open the web
page and then open the console so right
click and
inspect and open the
console and inside here you'll see that
we created a product object using the
class so right now all of these
properties are undefined so now let's
set the values of these properties we'll
go back to our
code don't follow along here but one way
to set set these prop properties is to
access them outside the
class for example product
1. equals something and then do product
1. image equals something and then
product one. name and so
on so this is not a good way to set
these properties because we have to do
this for each product that we create so
it makes our code repetitive and messy
instead notice that when we create a
product this is kind of like the setup
code we create a product and then set
all of its
properties and remember classes have a
specific feature for setup code called
The
Constructor and now you can follow
along so inside this class we're going
to create a
Constructor brackets and curly brackets
so whenever we generate an object it's
going to automatically run this
Constructor so this Constructor is where
we should put our setup
code so let's remove this
code and then do all of that inside the
Constructor so first we want to set the
ID property we're going to do this do ID
and make it equal and now what value do
we set the ID to so the value of the ID
is inside each of these
objects so when we create a product up
here we're going to put this object
inside these
brackets and then that's going to go
into the Constructor in here so in the
Constructor let's create a parameter to
save this data so we'll name it product
details and now to save something inside
ins this parameter we're going to put it
between these
brackets so let's actually give this
entire object to the
Constructor so we're going to right
click and
copy and then between these brackets
we're going to rightclick and
paste so whenever we create a new
product we're going to give it this
object with all the details
it's going to get saved in here and now
we can set the
properties so this. ID is going to be
equal to the product details. ID
property so product
details.
ID and for the image we're going to do
this. image equals the product details
which is this object that we passed in
dot the image
property same thing for the name so this
do name equals product
details. name which is this property
here same thing for the rating this.
rating equals product details.
rating and finally the price
sense this. price sense equals the
product
details. Price
sets so this is called converting an
object into a class what we're doing is
we're basically taking a regular object
like this we put it inside a class and
then we copy over the
properties you can also visualize it
like this we have a regular object and
we're basically wrapping it inside a
class and the reason we do this is that
classes have extra features we can use
like we can add methods and we can also
have private properties and private
methods so we basically have these same
object as before except we have an
enhanced version of that object it has
some extra features from
classes so for now let's save this code
and then down here we console.log
product one so let's take a look at it
in our console so we'll open the
console and now we can see that we
created a product object so it's the
same object as before except now it's
enhanced it has some extra features from
classes so next we're going to take this
technique and apply it to this entire
array so instead of having an array of
regular objects we're going to convert
each of these objects into the product
class now one way we could do this is
that in front of the object we can just
type new product Open Bracket and then
close bracket at the
bottom and this will essentially convert
this regular object into the product
class however we're going to have to
repeat this code for every object in the
array and it's going to be a lot of work
and
repetition so instead let's just Loop
through this array and then use code to
convert each of these objects so instead
of typing this out manually we're going
to remove this and remove the round
bracket at the end and then I'm going to
click this Arrow beside the array to
collapse
it and at the end of the array we're
going to use an array method called do
map and
brackets so map basically Loops through
an array and for each value it runs a
function so we're going to give this a
function that we want to run for each
value so arrow and curly
brackets and this inner function is
going to get a
parameter so this parameter is basically
each value in the
array so it's going to take the first
value and then save it inside this
parameter run the function and then take
the second value save it in here run the
function third value save it and run the
function so let's name this parameter
the product
details because each object in this
array contains product details so now
it's going to take each object save it
in the parameter and run the function
and here we're going to convert the
object into a class to do that we're
going to use the code new capital P
product
brackets and we're going to give it this
regular object which is the product
details and now there's a second part to
how Map works so map creates a new array
and whatever we return from this inner
function is going to go inside that new
array so here we're going to return this
class so this result is going to be put
inside a new array so you can think of
map as we take each value in an array we
run this function on it and we transform
it and then put it inside a new
array so here we're essentially
transforming each of these products or
these regular objects into a
class so at the bottom let's
console.log the products array to
confirm this so we'll
save and open the
console and now you can see we have an
array and each of the values is a
product class instead of just a regular
object
so we converted all of our products from
regular objects into this product class
and now let's open the web page to make
sure that everything still
works so if we open the
page you notice that everything is still
working
correctly and that's because we have the
exact same objects as before except
they're now just sort of enhanced
objects next let's use those extra
features of classes to simplify our code
for this page we'll go back to our
code and on the left side let's open
amazon.
JS so this is the code that creates the
homepage so in here we're going to
scroll down until we see the rating
section where we calculate the stars and
the rating
account so notice that inside our HTML
we're constru in this URL here for the
number of stars a product
has and we're also creating the price
that we want to display on the
page now instead of doing this all in
the HTML our code would be cleaner if we
moved this logic into our class because
we want to group this related code
together so let's use the features of
classes to make this code a little bit
cleaner we'll open products. Js
and we'll scroll up to the product class
and inside here let's add some methods
for calculating the stars and the
price so we're going to add a method and
call it get Stars URL brackets and curly
brackets and let's create another method
called get price brackets and curly
brackets
and now we're going to move the code
from our HTML into this class so we'll
open amazon.
JS and then here we're creating the URL
of the Stars so let's actually select
all this
code and
rightclick
copy and inside products.
JS inside get Stars URL we're going to
rightclick and paste
and this is going to be a string so at
the front let's add a back tick so we're
going to use a template string because
we're going to insert a value inside and
at the end we'll add another back
tick so now that we created the string
we're going to return it from this
method so
return and semicolon at the
end and one thing we need to fix is that
product is not defined anywhere so to
get the rating property of whatever
object this is we're going to use this.
ratings.
Stars so now each product is able to
construct its own Stars URL here so
let's save this
file and then inside amazon.
JS instead of doing this calculation
directly inside the HTML
we're going to delete it and we're going
to insert the
product. getet Stars URL method and
brackets so you'll notice that we have
the same product object as before but
now it's sort of an enhanced product we
can add methods to group related code
together and make our code
cleaner let's do the same thing with the
price down here we're going to calculate
this using the method instead of
directly in the
HTML so we're going to select this code
and then right click
copy inside products.
JS inside the get price method we're
going to
rightclick and
paste and again we want to return the
price as a string so at the front we'll
create a template string because we're
inserting a
value and at the back a template string
or a back tick and we're going to return
this from the
method and another thing we need to fix
is that product is undefined so to get
the price sets property we're going to
use this Price
sets now one extra thing we need to do
here is that we're using the format
currency function but we didn't import
it so we're going to scroll to the
top and import format
currency import curly brackets the
format currency function from a
string and here we're going to locate
this function so we're inside the data
folder we need to get out of the data
folder using do slash and then go into
the scripts folder into the UTS folder
and load money. JS so scripts SL
utils
money.jpg
and instead of calculating the price
inside the HTML we're going to remove
this and then insert the
product. getet price method and
brackets so now let's
save and let's open the homepage to make
sure that it's
working so now you see that everything
is still working including the stars and
the
prices so we'll go back to our
code and now that we have these methods
let's use them in our other page which
is the checkout page so we'll open
scripts
checkout.
JS and this basically displays the
products on the checkout
page if we scroll to the HTML and find
the delivery date the product image and
the product name we're going to see that
here we're also calculating the
product's price directly in the
HTML so instead of doing this let's use
the method we just created so select
this code and remove it and insert the
matching product this time so
matching
product and remember we converted all of
our products into classes so this is not
a regular object anymore it's more of an
enhanced object it's a product
class and that means this will have the
method. get price and brackets and Save
so now let's open the checkout page to
see if this works we'll open the web
page and then at the top right we're
going to click the
cart and now you can see that on the
checkout page the price is still
displayed
correctly and that's it if we go back to
our
code you'll see that by converting our
objects into classes we're able to use
extra features of classes like methods
to make our code
cleaner so now let's make sure that all
of our tests are passing we'll go to the
left and scroll down and we're going to
open test.html in the browser so if you
don't have it open you can right click
and open with live server but for me I
already have it open so I'm going to
open the test page and all of our tests
are still passing so our code is still
correct and now now let's save our
changes into git we'll open the git
section and in products. JS we created
the products class and at the bottom we
converted all of our objects into the
products
class so actually one thing I forgot to
do is to clean up these console. logs so
let's do that right now we're going to
open our code and go into products.
JS and we'll scroll down right after the
product class and let's remove this
product one because it was just an
example and we'll also remove the
console.log products at the
end and
save so now if we go back into git and
open products. JS we just have the code
where we convert our objects into a
class in amazon.
JS we use the feature of classes called
Methods to make our code cleaner in
checkout. JS we stop loading our cart
class practice file and in orders
summary. JS we also use a method to make
our code
cleaner so now let's create a message to
describe these
changes
convert products into classes and commit
next we're going to learn an important
feature of object-oriented programming
called
inheritance inheritance lets us reuse
code between
classes so first let's learn the concept
of
inheritance to do that we're going to
open our
project so we'll open this page here to
our checkout page
and we're going to go to the homepage by
clicking the top
left and on this page we have a bunch of
products but you also notice that we
have different types of products for
example we have clothing like this
t-shirt and we have appliances like this
toaster so clothing and appliances are
still products they have a name a price
and a rating but they are a more
specific type of product for example
clothing can have all the properties of
a regular product but it can also have
specific properties like a size
chart so how do we represent this kind
of relationship in our code we have a
product and then we have a more specific
type of
product one way to represent this is to
create a new class called clothing and
this class will have all the properties
of a regular product but also more
specific
properties however there's a problem
with this which is we're duplicating a
lot of
code instead objectoriented programming
has a feature called inheritance that
allows one class to get all the
properties and methods from another
class so we don't have to copy paste
this
code for example we can make a clothing
class and then use inheritance to get
all the properties and methods from the
product
class this is similar to how a child
inherits things from their parents like
their hair color or the shape of their
eyes in fact we call the product class
the parent class and we call the
clothing class the child
class so now let's learn how to use
inheritance in our code we're going to
open VSS
code and open our code on the left and
then open products.
JS and we're going to scroll to the
product class and then below this class
we're going to create a more specific
type of product called
class and capital c
clothing and curly
brackets so we said that clothing is is
just a specific type of product so that
means clothing should have all the
properties and methods of a
product so first let's inherit all these
properties and methods into the clothing
class to use inheritance after the class
name we're going to use the word
extends and then we're going to give it
the class that we want to inherit from
which is the product class
Above So this means that clothing will
get all the properties and methods of
this class or it will inherit all the
properties and
methods to demonstrate this let's leave
this empty and create a new clothing
object so down
here let's create a variable first using
const and we'll name it a
t-shirt make it equal
and we'll generate a new clothing object
to do that we'll use the word New
Capital C clothing and
brackets and next we're going to expand
the products array and we're going to
give the product details to this class
so we're going to scroll down to the
third product which is the
t-shirt and we're going to select this
object
and then right
click
copy and scroll
up and now between these brackets we're
going to right click and
paste so now we created a new closing
class we gave it all the data that it
needs and let's console.log it to see
what it looks like so down here we're
going to
console.log brackets and the variable
name which is t-shirt so here
t-shirt and
save and now let's open the console so
we'll open our web page and then on this
page we're going to right
click
inspect and open the
console and you'll see that we created a
new clothing
object and if we open it you'll see that
this has the same properties as the
product class
so this inherited all the properties
from
product so let's see if we inherited the
methods as well we'll go to our
code and let's try the method get price
so we'll
console.log
t-shirt. getet price and
brackets and
save and now if we open the console
again you'll see that get price also
works so clothing inherited the methods
from product as well so even though this
is empty this class gets or inherits all
the properties and methods of
product so we use inheritance when we
have one class which is a more specific
type of another class for example
clothing is a more specific type of
product we want all the properties and
methods of the product still but we just
don't want to copy paste all this code
down here so inheritance lets us reuse
code between
classes so now that we have this
clothing class we can add properties and
methods that are more specific to
clothing for example clothing can have a
size
chart so for con convenience inside this
t-shirt object I've actually added a
size chart link so let's add this to our
clothing class so up here we're going to
add a
property size chart
link and now to set this value we're
going to use the Constructor like we did
before so down here we're going to use a
Constructor brackets and curly brackets
and we're going to give this a parameter
called Product
details so when we create the clothing
we save this object into product details
and then we can use it to set the
properties up here so we're going to do
this do size chart link and make it
equal to the product details
which is this object and we're going to
get the size chart link
property dot size chart
link now one problem we have here is
that clothing inherits all the
properties from the product so we also
need to set the ID the image the name
and so on so if we scroll down we could
do something like this . ID equals
product details.
ID however instead of doing this one by
one all over again inheritance gives us
a shortcut we can actually just use the
Constructor in the parent class up
here so to call the parents Constructor
we're going to use a special feature of
classes called super and brackets
so super basically calls the Constructor
of the parent class which is the product
so this will call the Constructor up
here and we also need to give this the
product details so down here we're going
to call Super and give it the product
details so this will call the
Constructor of the parent class which is
product and that will set the ID the
name and the rating
so now let's save
this and check our console
again and open up the clothing object
and you'll see that now we have a size
chart link
property so that's how inheritance Works
a class can get or inherit all the
properties and methods of another class
and reuse that code and this class can
also have more specific properties and
methods like a size chart
link one last thing to know is that if
we don't create a Constructor by default
it will run the parents Constructor so
that's why when this class was empty the
code still
worked now that we have this clothing
class we're going to use it in our
project so right now if we scroll down
to our products array we can converted
all of these into a product
class however we're going to convert
some of them like the t-shirt into a
clothing class instead to make it more
specific so how do we know which objects
to convert into a product and which ones
to convert into clothing to help us do
that I included a property called type
so type tells us which class we should
use when we're converting this into a
class this is sometimes called a
discriminator property it tells us which
class we should convert this
to so we're going to go down to the
bottom of this code so I'm going to do a
trick here I'm going to scroll up to the
products array and click this Arrow to
collapse it and then at the bottom we're
going to use that type property to
decide which class to use so inside this
function we're going to use an if
statement bracket ET and curler
brackets and inside we're going to check
the type
property product
details.
type and we'll check if it is equal to
the string
clothing if it is equal to clothing
we're going to convert this object into
a clothing class instead so let's
return new Capital C clothing and
brackets and we're going to give the
Constructor product
details so now our array will contain a
mix of regular products and
clothing next for each of our clothing
we're going to display the size chart
link on the
page but first let's make sure that we
have this image here the closing size
chart so if we go into our images
folder you might see the image here
called clothing siiz
chart.png but currently I don't have
this so I need to download this first to
do that we're going to click this link
in the
description which will open the size
chart
and then on this image we're going to
right click save image
as and then find the folder that
contains all our code so for me it's on
the
desktop inside a JavaScript Amazon
Project and inside the images
folder and we'll save it
here and if we go back to our code we
should have the closing size chart image
inside the images
folder now let's display the size chart
on the
page so if I go to the
homepage whenever we have a clothing
product like this t-shirt we're going to
display a size chart
underneath let's go back to our
code and open amazon. JS which creates
the homepage
which is right
here and we're going to scroll down the
HTML below the product price and the
quantity selector here and underneath
this if we have a clothing product we're
going to display a size chart link under
the quantity selector like
this so one way we can do this is to use
something like an if statement or a
turnery like a this if it's a clothing
then display some HTML if it's not a
clothing then just display
nothing however we're going to learn a
different way to do this using
inheritance so first we're going to
create a new method on the clothing
class that's going to generate the HTML
that we need here so we're going to go
to our code and scroll up and open
products. Js
and we're going to scroll up to the
clothing
class and at the bottom we're going to
create a new method and let's call it
extra
info
HTML brackets and Cur
brackets so this method will generate
some HTML that contains some extra
information about this product like the
size
chart so here we're going to return some
HTML and we use a template string
because we're going to insert some
values inside and inside here let's
create some HTML for a
link to create a link we're going to use
the code less than a greater than less
than SL a greater than so this HTML
element creates a link when we click
this link it will open another page
page inside this link let's put the text
size chart so this is what's going to
show up on the
page and Link elements have two
attributes the first attribute is called
hre Equals double
quotes So this tells the computer which
page this should open when we click this
link inside here we're going to insert
the size chart link so we're going to
insert this. siiz chart
link so when we click this it will open
a page containing the size chart
image we'll scroll back
up and Link elements can have another
attribute called Target equals double
quotes and we're going to give it a
value of underscore blank
and I'll add some new lines here to make
it a little easier to
read so Target equals blank tells the
link to open in a new
tab so now let's save this
file and we'll go back to the homepage
so I'll scroll down here to amazon.
JS and below the quantity
selector let's
insert and we'll call the method that we
just created which is the
product. extra info
HTML and
brackets so this will ins some HTML
containing extra information about the
product like the size
chart now before we run this code
there's one thing that we need to fix
currently only the clothing class has
this
method if it's just a regular product
it's not going to have this method and
it's going to cause an
error to fix this we're also going to
create this method on the product class
so we'll go back to our
code and open products.
JS and we're going to scroll up to the
products class here and at the bottom
we're going to add the same
method extra info HTML brackets and
curly
brackets and for regular products we
don't have any extra info we want to
display so let's just return and empty
string and
save so now if we call extra info HTML
it doesn't matter if it's a product or a
clothing both of these will have this
method
defined so we'll go back to amazon.
JS and now this should always
work so let's click this file and
save and then open the web page to see
the
result so now you notice that products
that are clothing have a size chart
underneath and regular products don't
have any extra
information and if we click the size
chart link it will open a new tab to the
size chart image
so that's how we create this size chart
link for only the clothing
products let's go back to our code and
we'll learn more about this new
technique that we just
used so on the left we'll go back to
products. JS
first so notice that the product class
has a method called extra info HT ML and
then clothing extends this
class that means clothing will
automatically get the extra info HTML
method but then we Define this method
again inside
clothing so this will actually override
or replace the parents method and this
technique is called method
overwriting one more thing to know about
method overwriting is that if we really
need access to the parents method
there's a feature that we can use called
super so super gives us access to the
parent
class so if we want to call this method
up here we can do super and then extra
info
HTML so it's the same super as we used
up here except this calls the parents
Constructor and this calls one of the
parents
methods so let's comment this out since
it's just an
example and let's
save and lastly let's go back to amazon.
JS and we'll take a look at this code
and notice that when we call extra info
HTML we don't know what class this is
this might be a clothing class or a
might just be a product
class this technique is called
polymorphism which means we can use a
method without needing to know exactly
what class this
is polymorphism is sort of like an
alternative to doing if statements here
instead of doing if it's clothing do
this if it's a regular product do
something else we can just have both of
the classes use the same method and then
the class itself will Det determine what
this method
does if we add a new class like an
appliance class we don't need to change
any of this code the appliance class
will determine what extra info HTML
does and that's it we learned about
inheritance which lets us reuse code
between classes and we learn some of the
techniques we can do with inheritance
like method overwriting and polymorph
PRM which can make our code a little bit
cleaner now let's check our test to make
sure that everything still works so
we'll open the test page and make sure
that everything is still passing and
then we'll go back to our code and we'll
save this into git open the git
section and in products.
JS we created the clothing class which
inherits from product
and one thing I forgot to do is to
remove this practice
code so let's actually go back to our
code in products.
JS and below the clothing let's remove
this practice
code and
save we'll go back to
git and just make sure that it's been
removed and then we added the size chart
image
and in amazon. JS we used polymorphism
to add some extra info below each
product so let's create a message
describing our
changes use
inheritance and
polymorphism to add size chart and
commit
in the rest of this lesson we're going
to learn more details about classes the
first detail is how to test classes so
testing classes is the same as writing
normal
tests so we generate an object using a
class and then we test if its properties
and methods are
correct I'll leave writing tests as an
exercise at the end of this
lesson the second detail we're going to
learn is built in
classes these are classes that are
provided by the
language so let's go back to our
code and open products. JS
again and we're going to practice using
a buil-in
class an example of a built-in class is
date this class generates an object that
represents the current date
below the classes that we created we're
going to create some new lines and we're
going to practice using the built-in
date
class first we'll generate a new date
object using the code new and then the
class capital D date and
brackets and now let's save this object
in a variable so at the front we'll use
const and we'll call it date and make it
equal to this object that we just
generated and below this let's
console.log the date to see what it
looks like so we'll
save and then open the
page and we'll go back to our project
here and we're going to check the
console so right click
inspect and the
console and we can see that the date
object represents the current date and
time so this is the current date and
time that I'm recording this
video so this date object has properties
and methods that we can use that are
related to the
date for example we'll go back to our
code and every date object has a method
called two local time string this
basically gives us the current
time so let's try it out we'll create
create a new line and type the code date
dot to local time string and brackets so
make sure that this is in cam case two
is lowercase and every other word starts
with an
uppercase and we'll console.log this to
see what it looks like
console. log and
brackets so let's save this file
and open the
console and that method gave us the time
so for you you should see your current
time
here so that's the built-in date class
it lets us create objects that represent
the current date and
time an interesting thing to know is
that we used the external Library DJs
earlier in the project DJs uses this
date class behind the
scenes however DJs gives us a lot of
extra features so we usually use DJs
instead of using the date class
directly so now let's comment out this
code because it was just an example so
at the top we'll type
slashstar and below it star
slash the last thing we're going to
learn is more detail dets about
this as a
reminder inside an object we can use the
value this and this will point to the
outer
object so this feature lets an object
access its own
properties now in JavaScript this can
actually be used anywhere in our
code for example we're going to create
some new lines
and here we can just directly
console.log
this so here we're using this but we're
using it outside of any object in this
situation there's no object for this to
point to so this will be undefined which
actually makes
sense if we
save and we check our console
this will equal
undefined now originally this actually
equaled the window
object however this Behavior caused
confusion so when they release
JavaScript modules inside a module this
is now undefined which makes more
sense let's go back to our code and
another place we can use this is when
we're creating an object so let's go
down here and we're going to create a
new object using const we'll call it
object two and make it equal to curly
brackets and we're going to give this
object a property let's just call it a
colon give it a value of two comma and
add another property B
colon and we'll set the value of this
property to this Dot
a now you might think that because we're
inside this object this will point to
object 2 however at this point in the
code object 2 has not been created yet
so this doesn't have anything to point
to and this will be
undefined if we
save and then open the
console it will give us an error because
this is
undefined let's go back to our
code so so far if we're inside a method
we can use this and it will point to the
object if we're outside of a method
there's no object to point to and this
will be
undefined and everything makes sense so
far so let's comment this out using SL
star and and at the bottom start
slash now the last important place we
can use this is inside a
function so at the bottom here we're
going to create a
function and let's call it log this
brackets and curly
brackets and inside we're just going to
console. log this
so again we're not inside of any object
so there's nothing for this to point2
and in this situation this will be
undefined as
well below this if we run the function
log this and brackets and
save and check the
console it will tell us that this is
undefined when it's just inside a
regular
function next this actually has a
special
feature so inside a function we can
change this to whatever we want to do
that functions have a method called
call So Below this line let's type the
function name log this and use a method
do call and brackets
so call runs this function so it does
the same thing as the line above except
we can set the value of this to be
whatever we want so the first value that
we give to do call is going to be the
value of this for example we can give it
the string
hello and now this will run the function
and this will be equal to hello if we
save
and open the
console you can see that we set this to
be equal to
hello so that's a special feature of
this inside just a function we can
change this to whatever we want using a
method like
call so call is the same as calling or
running the function except we add an
extra parameter in front this first
parameter is the value of
this the last important thing to know
about this is that Arrow functions do
not change the value of
this for example below this let's create
a method by using an arrow function this
time so we'll create some new lines and
first we're going to create an object
using
const we'll call it object three equals
curly
brackets and inside will give it a
method and colon and we're going to
create this method using an arrow
function this time brackets arrow and
curly brackets and inside we'll just
console. log
this so usually this will point to the
object itself
however Arrow functions do not change
the value of
this here this will have the same value
as outside the arrow
function outside the arrow function
let's type
this here this has no object to point to
so this will be
undefined and then inside the arrow
function it will also be undefined
basically this keeps the value that it
had outside the arrow
function as a test below this we'll run
object 3. method and
brackets if we
save and check the
console it will show us that inside here
this is also undefined
so in an arrow function this will be
whatever the value is outside the arrow
function now you might be wondering why
are Arrow functions designed this
way so JavaScript had a common problem
in the past when we are inside a method
this points to the object but if we try
to do a for each Loop inside the for
each Loop this does not point to the
object anymore it points to undefined
and that's because we created a whole
new function here and remember inside a
regular function this becomes
undefined so this caused problems
because we no longer had access to the
outer object up
here so that's why we created Arrow
functions if we replace this with an
arrow function this would be equal to
whatever it is outside the Arrow
function Arrow functions do not change
the value of
this so outside for each this points to
the object and inside for each this also
points to the
object so that's why Arrow functions are
designed this way to avoid accidentally
overwriting
this so let's summarize what we learned
about this inside a method this points
to to the outer object inside a function
this is undefined but we can change it
to whatever we want using something like
call and arrow functions do not change
the value of
this don't worry if these rules are a
bit confusing at first they are actually
sort of
reasonable if there's an object to point
to this will point to that object if
there's no object to point to this will
be undefined and we have tools like call
and arrow functions to kind of
manipulate the value of this to be what
we want the more that you work with it
the more you just get used to
it so now let's comment out this
practice code at the top we'll type
slashstar and at the bottom star slash
and
save and we'll save to get
we'll open the git
section inside products. JS we added
some practice code to learn more details
about classes and
this let's type a message describing our
changes learn more details about classes
and this and commit
now that we learned object-oriented
programming you might notice that it's a
very different style of programming than
just writing out a bunch of functions
directly so you might be wondering which
style of programming should we use
objectoriented programming or procedural
programming which is the step-by-step
style that we used in the earlier
lessons the answer is it's up to you I
personally prefer procedural programming
in JavaScript because I think it's
simpler I only use objectoriented
programming if I'm working on a team
that also uses it also object-oriented
programming is much more popular in
other languages so it's still useful to
know object-oriented programming in case
you work with other programming
languages in the
future and that's the end of this lesson
in this lesson we learned about
objectoriented programming which means
we organize our code into objects we
learned how to use a function to
generate objects and we improve that by
using a class to generate objects we
learned that classes can have private
properties and methods we learned about
inheritance which lets us reuse code
between classes and we learned about
method overwriting and polymorphism
which lets us call a method without
needing to know what the class is and
lastly we learned more details about
this and how to control the value of
this thanks for watching this course so
far if you want to support this channel
you can check out the premium version of
my courses just like this one where you
can get a certificate of completion and
a Better Learning platform if you're
interested in extra videos from me more
in-depth videos and behind the scenes
content you can check out these links
here you can also support the channel by
liking the video subscribing and sharing
this video with others thanks again and
let's continue with the
course here are some exercises to help
you practice what we learned in this
lesson
in this lesson we're going to learn
about backend and this will prepare you
for the next step after finishing this
course first of all
what is backend a backend is just
another computer that manages the data
of a
website for example in our Amazon
Project we created this website where we
can pick which products we want but how
does Amazon the company know which
products that we
ordered in this situation there has to
be a second computer somewhere that's
owned by
Amazon and then our computer sends the
order information to this second
computer and now Amazon will know what
we
ordered so this second computer is
called the backend computer or just the
backend it manages the data of a
website on the other hand our computer
or the web page where we can see and
interact with the products this is
called the front end
now that we know what a backend is how
does our computer or the front end send
information to the back end when two
computers are connected to the internet
they can actually send messages to each
other using a feature called
HTTP or hypertext transfer
protocol in an HTTP message we can
actually attach information like our
Amazon order
when Amazon's backend receives this HTTP
message now Amazon will know what we
ordered now that we know what HTTP is
let's send our first HTTP message using
JavaScript so we'll go to our code and
on the left we're going to create a new
file just for practicing backend so
we'll scroll up to the data folder and
we'll click inside this folder and then
create a new
file and let's name this file backend
Das
practice. JS and press
enter and now to send an HTTP message
we're going to use a class called XML
HTTP request so this is a built in class
meaning it's provided by
JavaScript first we gener at an object
using this class using the code
new and the class name
XML all capital capital
HTTP capital r request and
brackets so this creates a new HTTP
message that we want to send to the
backend a message is also known as a
request so now let's save this request
in a variable at the front we'll create
a variable with const and name it
xhr equals this
request next we need to set up this
request so we'll create a new line and
to set it up we'll do xhr
doop and
brackets and to set up this request
we're going to give open two
parameters the first parameter is what
type of HTTP message to
send so one type of message we can send
is the string
get get means we want to get some
information from the back
end there are several common types of
requests that we can give to the backend
but we're going to start by learning get
next we're going to give open a second
parameter and this parameter tells a
computer where to send this HTTP message
so using HTTP we can send a message to
any computer that's connected to the
internet now to locate another computer
on the internet we need to use a
url url stands for uniform resource
locator and it's kind of like an address
but for the internet a URL helps us
locate another computer on the
internet so URLs look like this this is
the URL for Amazon YouTube and my
website the https in front means we're
using HTTP to communicate with this
computer the S after the http means
we're using a secure version of http
the second part of a URL is called a
domain name this is like an address it
points to another computer on the
internet so amazon.com points to one of
Amazon's backend computers youtube.com
points to one of YouTube's backend
computers and superimple dodev points to
one of my backend
computers if you want to learn more
about domain names and how the internet
works you can check out my video on how
to put a website on the
internet now for this lesson I actually
set up a backend computer that we can
practice with so my backend is located
at the URL
https super simple backend
dodev so in the second parameter of open
we're going to give it a
string and we're going to give it the
URL of the back end end that we want to
send the message
to so the URL for my backend is
https colon SL SL super simple
backend.
death so that's how we set up an HTTP
message we give it the type of message
we want to send and also the URL which
is where to send this message to
the last step is to just send this
message so we'll create a new line and
we'll type xhr
doent brackets and
save so this creates a new HTTP message
sets it up and then sends this message
across the internet to my backend
computer located at superimple backend.
deev so now let's actually run this code
and see the results we're going to go to
the left and we're going to open
checkout.
JS and in here just like we did before
we're going to load that practice file
that we just created so we'll create a
new line and we're going to import a
file or a string and we'll locate that
practice
file so first we need to go to the data
folder using using do dot SL dat slash
and load
backend D
practice. JS and
save so we'll go back to the practice
file and now when we open the website it
will run this code and send the HTTP
message to see that let's open the
website so we'll scroll down and if you
don't have the website open you can open
it again by right clicking checkout.
HTML and then open with live
server I already have the website open
so I'm going to open
it and then I'm going to go to the
checkout
page and now we're going to look at the
console so we'll right
click and
inspect and this time instead of going
to the console tab we're going to go to
a new tab
called the network
tab if you don't see this tab you can
make this window wider or you might find
it under these
arrows so we'll open the network
Tab and in here this will show us all
the HTTP messages that are coming in and
out of our
computer now before we start looking at
the the HTTP messages there's one
important thing to know about the
network Tab and that is messages will
only appear here after we open the
console if we send some messages and
then we open the console it's not going
to show up
here so to make sure our HTTP messages
are recorded here we need to open the
network tab first and then we're going
to refresh the page to resend those
messages and now if we open the network
tab we should be able to see the HTTP
messages at the
bottom okay so inside this list we
should be able to see that we sent a
message to superimple backend. deev if
you don't see it we can also search this
list by using the text box up
here so in here we can type part of the
URL that we sent the message to for
example super
simple and the message that we sent
should appear here so now we can click
this message to get more details about
it on the right side we have several
tabs here the headers tab gives us
details about our message or about our
request so it tells us which type of
requests that we sent which is get and
the URL that we sent it to which is
super simple backend.
Dev this sends the request across the
internet to my
backend and then when my backend
receives this message or this request it
will send back a message which is called
a
response to see the response from my
backend we can open the the response
Tab and you can see that my backend
responded with hello this is super
simple dev's back end and a
documentation page that we can check
out so we have successfully sent an HTTP
message or a request to my backend and
we got back a
response another useful tab here is the
preview tab it basically takes a
response and displays it in an easy to
read
format so now let's learn some
terminology when we send a message to
the backend this message is called a
request we are requesting something from
the
backend when the backend receives our
request it will send an HTTP message
back to us and this message is called
the
response so each request that we make
will get one response from the back
end and this is called a request
response cycle it's always one request
one
response next currently we're viewing
the response in the network tab but we
can actually get this response in our
code and then do something with this
response so let's go back to our
code and here after we send the requ
Quest we can get the response using a
property called xhr do
response however there's a slight
problem with doing this when we send a
request to the backend it takes time for
the request to travel across the
internet to the back end and for the
response to come
back so the response is not available
right away and xr. response will be
undefined at first so xr. send is known
as asynchronous code asynchronous code
means it does not wait for this line of
code to finish it just sends the request
and then immediately goes to the next
line the response might come back later
in the future but we don't have access
to it
here so in this situation in order to
get this response we need to wait for
the response to come back first and then
we can access do
response in order to wait for the
response to come back at the top after
we create the
xhr we're going to use this code
xhr do add capital E Event capital L
listener and
brackets so this method listens or waits
for an event and then it can run a
function so this method takes two
parameters the first parameter is the
event that we want to listen for or to
wait for in this case we want to wait
for the response to come back so we're
going to give it the string load load
means the response has
loaded the second parameter is a
function that we want to run
after this event
happens so in this case after the
response has loaded we're going to run a
function brackets arrow and curly
brackets so because this function runs
after the response loaded inside here we
can access xhr do
response and this will not be undefined
it will contain the response that we saw
earlier in the network
tab so let's console.log this to see
what it looks like
console.log and
brackets and we'll remove this line at
the
end and
save so now let's go back and check the
console for the response so we'll open
the
console and then open the console
Tab and here you can see that we have
the response in our code and we console.
logged
it so this
response is a string and now we can save
this in a variable or do whatever we
want with it in our
code now one thing you might be
wondering is why do we put the event
listener up here at the top so first we
need to set up the event listener and
then trigger the event or send the
request this is the same as setting up
an event listener for clicking a button
we need to set up the event listener
first and then we click the button
after so that's how we send a request to
the back end wait for the response and
then save the response in our
code next we can send different messages
or different requests to the backend
using URL
paths a URL path is the part that comes
after the domain name for example in
this URL the URL path is /hello in this
URL the URL path is/ products
slir in this URL if there is no URL path
the URL path is
slash we can send a request to these URL
paths and each URL path will give us a
different
response so let's try sending requests
to different URL paths and see what
different responses that we
get so for this example let's send the
request to super simple backend. deev
and then the URL path SL hello and
save and now let's open our console to
see the response
and here you can see that this URL path
gave us a different response than last
time let's go back and try another URL
path to see what it looks like so we'll
delete this and then send the request to
slash products
slir and
save and we'll open the console to view
the
response and here here this URL path
give us a Json and this contains the
details of the first product in our
Amazon
Project so we can send requests to
different URL paths and we will get
different responses from the
backend next a backend only supports a
certain set of URL paths for example
when I created my backend super simple
backend .d I had to decide which URL
paths are supported and how my backend
would respond to each URL path if we
send a request to a URL path that is not
supported the back end will respond with
an
error let's go back to our
code and we'll try a URL path that is
not
supported so let's remove this at the
end
and we'll try sending the request to
not-
supported and
save and now if we look at our
console you'll see that the backend
responded with an error message saying
this URL path is not
supported the browser will also
console.log this red error
message this red message is displayed
automatically when there's an error
so this message tells us the type of
request that we sent which is get and
the URL that we sent it to and also this
number which is called the status
code whenever we get a response from the
backend the backend also gives us a
status code which tells us if a request
succeeded or
failed a status code that starts with
four or five means the response
failed starting with four means it was
our problem we sent the request to a URL
path that was not
supported starting with five means it
was the backends problem for example the
backend
crashed a status code starting with a
two means the response was
successful so we can also see the status
code in the network
tab so we can search for our request and
then when we click the request in the
headers tab it will show us the status
code in this
row so this tells us if our request
succeeded or
failed so now you might be wondering how
do we know which URL paths are supported
and which are
not so there's actually no way to figure
out all the URL paths that are supported
and this is for security reasons
however some backends do provide a
documentation page that lists the URL
paths that are supported and also what
kind of response that they give for my
backend I created a documentation page
and we're going to take a look at that
so we'll open the
browser and at the top we're going to
create a new
tab and to see the documentation for my
backend we're going to go to super
simple back back end dodev SL
documentation and press
enter so this is the documentation page
for my backend it gives us a list of
which URL paths that are supported and
what each URL path does so when we make
a request to slash it will give us this
message which we saw earlier if we make
a request to/ hello it will give us this
message which we also saw
earlier so by the way the list of all
the URL paths that are supported is
called the backend
API API means application programming
interface interface means how we
interact with something so this list of
URL paths are all the ways that we can
interact with the backend and that's why
we call this the backend
API next the backend can respond with
different types of data so one type of
data the back end can respond with is
text for example when we sent the
request to get/ hello it gave us some
text
back so in our
code if we change this URL path to
/hello
and
save and we open the
console and click the console
tab it gives us back some
text we can also see what type of
response that we got using the network
tab so we'll open the network Tab and
then search for the
request and then here when we click
it inside the headers tab if we scroll
down to the response
section here it will give us the content
type or the type of response that we got
back so in this example /hello gave us
some text and the type is text
slpl another type of data the backend
can respond with is
Json so if we go back to our code and
change the url path to products
slir and
save and then look at our
console in the network tab we'll open
this request and inside the headers if
we scroll
down it will tell us that the type of
the response is application SL
Json so the backend sent us back some
Json if we open the console tab we can
see the Json string here
so once we get this Json from the
backend we can use json.parse to convert
this back into a JavaScript
object basically this allows us to send
JavaScript objects across the internet
to the back
end another type of data the back end
can respond with is
HTML we'll go back to our
code and we'll change the URL path to
documentation so this was the
documentation page that we saw earlier
if we
save and then open the
console you'll see that the back end
responded with a bunch of
HTML if we look at the network Tab and
search for the request and open the
request here and in the headers tab we
scroll down
to the content type it will tell us that
the type of the response was text/html
finally another type of data the backend
can respond with is an
image for example we'll go back to our
code and change the url path to
imagesapple
jpg and say
save and we'll open the
console and in the network tab we can
open this
request and in the headers tab we can
scroll down and it will tell us that the
type of response was an
image/jpeg as you can see the backend
can respond with different types of data
not just
text okay so we got this image back from
the back end but what does this look
like in the console we'll open the
console and we'll see that we just get a
bunch of random characters here and
that's because the console is trying to
display the image as text but the image
is not really
text this is the image's raw data so
that's why it shows all these random
characters
here however it would be better to
display this as an actual ual image
instead of raw
data we can display this as an image by
using the
browser so if we open the
browser when we type a URL at the top of
the browser it actually sends a get
request to that
URL so typing in here actually does the
same thing as our code it makes a get
request the one big difference is that
that in the browser when it gets back
the response it will display the
response on the
page for example if we enter superimple
backend dodev and change the url path to
just nothing or slash and press
enter this actually sends a get request
to my back end the backend responds with
some text and it displays this response
on the
page so using the browser is the same
thing as making a get
request now the cool thing about this is
that if the browser gets back an image
it will display it as an actual image
instead of raw data that we saw in the
console so here if we change the url
path
to/ images
slapple jpg and press enter
it will get back the same image as
before except the browser will display
it as an actual image on the
page same thing happens with the backend
responds with
HTML so at the Top If we change the url
path to slash
documentation and press
enter if the response from the back end
is HTML theow browser will display this
HTML as an actual web page instead of
raw
HTML so again using the browser is the
same thing as making a get
request and depending on the type of
response the browser can display the
response in a more useful way on the
page and that's it we learn the basics
of how a backend Works how to send
requests to a backend and how to send
requests to different different URL
paths so now let's go back into our
code and we'll remove this URL path and
just dodev so that we don't keep console
logging and image and then
save and let's save this practice code
into git we'll open the kit
section in backend practice we learn how
to make requests to the backend and in
checkout. as we loaded that backend
practice
file so let's type a message describing
our
changes add backend
practice file and
commit now that we learned what a
backend is and how to communicate with a
backend let's use a backend in our
project
so first we're going to open our code
and we're actually going to open
checkout.
JS and we're going to comment out this
import statement because we're not going
to run the practice file anymore so
we'll type double slash to comment that
out and
save next super simple backend dodev has
a URL path called slash
products this gives us a list of all the
products in the Amazon Project so first
let's open our browser and visit this
URL path to see what the response looks
like we'll open this tab to super simple
backend dodev and we're going to change
the url path at the end to slash
products and press
enter and you can see that this URL path
gives us a Json response so this
contains all the details of the products
for our
project now instead of using a file on
our computer to load the products let's
use the backend to load the
products so let's go back into our
code and on the left we're going to open
data/ products.
JS and we're going to scroll down to the
array of prodct S at the end so now
instead of loading the products from
this file we're going to load the
products from the back end so first
let's comment out all this code if you
need to you can click this arrow on the
left to collapse this array and we're
going to comment this out using slash
star and at the end star
slash and above this we're going to load
the products from the back end
first let's create a variable to save
the products again so we use let
products equal and empty array and let's
export this so we can use it outside of
this file like before at the front we'll
type
export next let's create a function to
load these products from the back end
we'll create a
function and let's name it load products
brackets and curly
brackets and inside here we're going to
create an XML HTTP request again to make
a request to my
backend so to create a request we're
going to use new in the class XML HTTP
request and brackets so this will
generate a new request object and let's
save this in a variable
so at the front we'll use const and
we'll name it xhr equals this
object next we're going to set up the
request using xhr doop and
brackets so open takes two parameters
the first parameter is the type of
request that we want to send in this
case the type of request will be the
string get
and we're going to give open a second
parameter which is the URL that we want
to send this request to so we'll give it
a string and the URL of my backend is
https colon slash super simple backend
dodev and then we'll add the URL path
which is slash
products finally we're going to send
this request using the code xr. send and
brackets so this will create and set up
a request and then send it to my backend
now remember that do send is
asynchronous that means it will just
send the request but it will not wait
for a response to come
back in order to wait for a response
above this code we're going to create
some new lines and set up an event
listener using
xr. add event listener and
brackets and this takes two parameters
the first one is the event we want to
listen for in this case it's the string
load which means the response has
loaded next we're going to give it a
second parameter which is a function so
brackets Arrow and curly
brackets and this is a function that we
want to run after the response has
loaded so inside here after the response
has loaded we can access it using xhr do
response for now let's console.log this
to see what it looks like so we console.
log and brackets
finally let's run this function so that
we run all this code at the bottom we're
going to load products and
brackets and
save so this will send a request to my
backend and then once we get the
response it will display it in the
console so now let's go to our
website we're going to open the project
tab
and don't worry if the page is blank for
you we're going to fix this in a bit for
now we're going to open the console by
right
clicking
inspect and open the
console and in here you'll see that xr.
response gave us this Json and this
represents all the products in our
Amazon
Project now that we have all this Json
we're going to convert this back into a
JavaScript object and then use it in the
rest of our code let's go back to our
code and here the response is a
Json we're going to convert it back into
a JavaScript object or in this case a
JavaScript array using the code
json. pars and
brackets so once we' converted this back
to an array we're going to replace the
product up here with what we loaded from
the back end to do that we'll do
products and make it equal to this
result that we got from the back
end now one more thing we need to do is
previously we converted the product
objects into a class so we're just going
to do that again with this
array so we'll select the code from map
all the way to the end
and then right click
copy and
here after this products array that we
got from the back
end right click
paste we're also going to transform this
array from objects into these
classes and at the end let's console.log
this products array to see what it looks
like now so we'll console
. log
products and
save and now if we open the console for
our
project you'll see that products is now
an array of product classes and clothing
classes so we converted the response
from a Json into a JavaScript array and
then into these
classes so that's how we load data from
the the back end and then convert it
into a JavaScript object or array that
we can use in our
code next let's go back to our code and
instead of console. loging the products
every time which will display a lot of
stuff in the console let's just
console.log a message to make sure that
this is working so we'll change this to
the string load products
and now that we have this function let's
use it in each of our
Pages first we're going to remove
calling this function for now and we're
going to export this function so we can
use it outside of this file so
export and save this
file and we're going to start from the
homepage so we'll scroll down to the
bottom to amazon.
JS and we're going to scroll to the
top and first we're going to import load
products we're already importing from
products. JS so we'll just add a comma
and load
products and now before we run all of
this code at the top we're going to load
the products first and brackets
so now let's
save and open the project in our
browser and we'll click the top left
icon to go to the
homepage and you'll see that the
homepage is actually empty so what went
wrong
here remember that HTTP requests are
asynchronous if we go back into our
code load products will send a request
to my backend
but it takes time for the request to
travel across the internet to my backend
and to travel
back so here it will just send the
request and at the next line the
response has not loaded yet so the
products array is still
empty and when we run this code with an
empty array the page will be
empty to solve this problem we need to
wait for this HTTP request to finish
first and for the response to come back
and then we're going to run the rest of
this
code so how do we do
that so we're going to go to the left
and we're going to scroll up to data/
products.
JS and I'm going to drag this file to
the top so we can see the code side by
side and I'll scroll down to the HTTP
request
which is right
here and remember that we used an event
listener to wait for the response to
come back once the response is loaded
we're going to run this
function so basically we want to run all
of this code at the bottom of this event
listener so after we've loaded our
products so one way to solve this
problem is maybe we can just copy all
this code and then paste it at the
bottom
here now obviously this doesn't make
sense because we're copy pasting a bunch
of code and then we can't really reuse
this
function a better solution is we're
going to put all this code in a
function and then we can give this
function to load products let's do this
step by step
so first at the top let's create a
function to group all of this code
together we'll use the word
function and let's name it render
products grid brackets and curly
brackets and now we're going to move all
of this code into the
function so we can do that by removing
this closing curly
bracket and then at the bottom we we're
going to scroll down all the way to the
bottom here we're going to add back the
closing curler bracket to put all this
code inside the function and now let's
also select this code so we can fix the
index so we'll select it all the way up
to
here and then press tab to add an indet
so now we put all the code inside render
products grid
next we're going to put this function
inside load products using a parameter
so between these brackets we're going to
give it this
function
render products
grid so remember in JavaScript functions
are values and we can use a function as
a
parameter so now inside load products if
we go up here at the top this function
will be saved in a parameter so let's
create a parameter at the top and we'll
name it fun to say that this parameter
will contain a
function so we basically saved this
function inside this parameter and now
after we load the response we're going
to run the
function so at the bottom here after
we've created the products array we're
going to run font and
brackets so that's how we run all of
this code after we've loaded the
products we group this code into a
function and then we save the function
up here after we load the response we're
going to run the
function so let's save these two files
we'll save products. Js
and then down here we'll save amazon.
JS and then open our
website and you'll see that the products
loaded again because this time we're
waiting for the response to come back
and then we run our
code so that's how we wait for an HTTP
request to finish first and then we run
some
code by the the way this function that
we provide to load products this is
known as a call back because we're
giving it a function to run in the
future or to call in the future so this
function will be called back in the
future and we've actually used call
backs before when we wrote the code set
timeout we provided set timeout a
function to run in the future or or to
call in the future so this function is
also known as a call
back don't worry if this technique is a
little complicated at first the more you
work with callbacks the more you'll get
used to
it let's get some more practice and use
the backend and callbacks on the
checkout page so we're going to open
checkout. JS which is the checkout page
and first we're going to in import load
products so at the top we'll create an
import curly brackets load
products from a
string and we'll locate products. JS so
inside here we're in the scripts folder
we're going to get out of it using do do
slash and then we're going to go into
the data
folder and then we'll add slash data
slash and we'll load products.
JS and then down here we're also going
to load products and
brackets and again we're going to give
load products a call back or a function
that we want to run in the
future this time instead of creating a
whole new function we're just going to
create a function in inside these
brackets using brackets arrow and curly
brackets so we don't need to create a
function name every time we can also
just create an anonymous function or a
function without a
name and then give this to load products
to run in the
future now inside this Anonymous
function we're just going to move this
code into here so we'll select this code
and then rightclick
cut and then inside here we're going to
rightclick and
paste and if you need to you can fix the
formatting so again this is going to
save this function inside the parameter
fun and then we're going to call fun
after we've loaded all the
products so let's save this file
and open our
website and we'll click the cart in the
top right to go to the checkout page and
now the checkout page is loading
again so that's how we use a backend in
our project we need to send a request
and then use a call back to wait for a
response and then run the rest of our
code so now let's save our changes into
G
we'll go to the git
section and in products.
JS we created the load products
function in amazon.
JS we used load products and gave it a
call
back and in checkout. JS we also used
load products and we gave it a call back
using an anonymous function or a
function without a
name let's create a message describing
our
changes load products from the backend
and
commit next we're going to learn testing
with a
backend now that we're using a back back
end in our code we need to update our
tests first let's go to our code and
we're going to run our tests so we'll
scroll to the bottom and if you don't
have the tests open we can run them by
right clicking test.html and then click
open with live server now I already have
the test open in my browser so I'm just
going to open that
Tab and for the video I'll zoom in using
control equals or command
equals and we have some failing tests
now so if you did the exercises from the
previous few lessons you might have more
than two failing tests but we're going
to focus on fixing these two tests here
for the
video so first let's open the code for
our order summary tests we'll open vs
code and then on the left we're going to
go into the test folder SL checkout SL
Ord summary
test.js so now we're going to scroll
down in this test and notice that here
we are rendering the order summary which
creates the cart on the checkout
page however this card requires the
products to be loaded from the back end
and currently we're not loading the
products in our tests so that's why the
tests are failing we need to to load the
products
first to do that let's import the load
products function at the top so we'll
scroll
up and we're going to add another
import curly brackets the load products
function from a string and we'll locate
products. JS so we need to get out of
checkout and out of tests using do do
slash do do slash and and then we'll go
into the data folder data/ and load
products.
JS and now we could call load products
inside before each but this will load
the products before each of our tests so
it will load it multiple times and we
don't really need to do this we only
need to load the products once for all
of our
tests to do that we're going to use
another hook provided by Jasmine called
before
all so above before
each we're going to use the function
before all and
brackets so this is the before all hook
it will run a function before all of our
tests inside these brackets we're going
to give it a function to run so brackets
arrow and curly brackets
and now before all of our tests we're
going to load the products so let's load
products and
brackets and
save and now let's open our tests in the
browser and unfortunately the tests are
still
failing let's go back to our code and
see what the problem is we'll open vs
code and here
remember that load products is
asynchronous that means it just sends a
request to my back end but it doesn't
wait for the response to come back so it
would just send a request and then
continue with the rest of the test
code and unfortunately at this point the
response has not come back yet products
is still an empty
array to fix this issue we need to wait
for a load products to finish first and
then continue with the rest of the
test to do that Jasmine has a feature
for waiting for some code to finish
called a done
function so in before all we can give
this inner Function One parameter called
done so done is a function and it's
provided by Jasmine when we we add this
done parameter before all will not
automatically go to the next step now
it's just going to wait and it will only
go to the next step when we call this
done function so when we do done and
brackets then it will go to the next
step if we don't call done then before
all we'll just keep waiting forever so
this done function allows us to control
exactly when before all finishes and
goes to the next
step and this is what we need to fix the
test we need to wait for load products
to finish first and then we're going to
call done and then go to the next
step to wait for load products to finish
remember we're going to give it a
function so between these brackets we'll
create a function using brackets Arrow
and curly
brackets now once the products have
finished loading it will run the
function inside here we're going to call
done and
brackets so this makes sure that the
products load first and then we call
done and then it goes to the next step
which is the before each hook and then
eventually it runs the tests at the
bottom
so now let's
save and take a look at our test page
and you'll see that those order summary
tests are now passing if you have any
other fail tests I'll leave that as an
exercise let's go back to our
code and that's how we test with a
backend we wait until the backend code
is finished and then we use the done
function to control exactly when to go
to the next step by the way we can also
use done inside before each and inside
it as well to wait for backend code to
finish now let's save our changes into
git we'll open the get section and
inside order summary test we imported
load products and then we called load
products and use the done function to
make sure that the products are loaded
first and then we go to The Next
Step let's create a message describing
our
changes load products in before all hook
and
commit next we're going to learn
promises which are a better way to
handle asynchronous code promises are
similar to Jasmine done function that we
just learned they let us wait for some
asynchronous code to finish before going
to the next
step so now let's create our first
promise we're going to open our code and
on the left we're going to go to
checkout.
JS and in here at the top we're going to
practice promises
promise is a class so we're going to
type the code new capital P promise and
brackets to create a new promise
object now inside these brackets we're
going to give it a function so brackets
arrow and curly
brackets so that's just how promises are
designed it's a built-in class and when
we create a promise we need to give it a
function
so when we create This Promise it's
going to run this function
immediately so inside here let's
console.log the string
promise to show that it runs
immediately so we'll save this
file and then go to the
website and we'll open the tab for our
project
and I'm going to zoom out a bit by
pressing control or command
minus and then open the console right
click
inspect and the
console and you'll see a logged
promise so when we create a promise it
runs this inner function
immediately now this inner function gets
a parameter called called
resolve and resolve is a function and it
works very similar to Jasmine's done
function so resolve lets us control when
to go to the next
step for example let's add some
asynchronous code into this
promise we'll remove the
console.log and we're going to run load
products which is asynchronous
so here we'll type load products and
brackets and now we're going to give
load products a callback function like
we did down
here brackets arrow and curly
brackets so it will run this function
after load products is
finished once this is finished we want
to go to the next step so here we're
going to call resolve so resolve and
brackets so you can see that the syntax
here is very similar to jasmin's done
function we run some asynchronous code
and then we wait for it to finish and
then we call resolve to go to the next
step now what is the next step to This
Promise so you might think that this
code down here is the next
step however a promise actually creates
a separate line of code or a separate
thread of
code so here these two groups of code
are sort of running at the same time
feel free to pause the video to get a
longer look at this
diagram the reason promises are designed
this way is it allows JavaScript to do
multiple things at the same
time so when the promise finishes it can
do a Next Step but this next step is
going to be separate from the rest of
the code it sort of does the next step
on the
side so right now this promise creates a
separate thread of code but this
separate thread doesn't actually have a
next step so we're going to add
one to add a next step to a promise at
the end and we're going to use a method
called dot then and
brackets and we need to give then a
function so we're going to type brackets
arrow and Cur
brackets and inside here let's just
console.log the string Next
Step so first we run this asynchronous
code and then we wait for it to finish
and then we run resolve and resolve
makes it go to the next
step to make this easier to see in the
console let's actually add some console.
logs to track the progress of this code
so at the top let's
console.log the string start
promise and then in here let's
console.log the string
finished
loading and we'll also comment out the
code that we had
before so we'll type
slashstar and at the bottom star slash
and now let's
save and check our
console so let's go through this step by
step first we start the promise which we
see here
and then we call load products which we
see here once the products are finished
loading it's going to run this function
and then we'll display finish loading
and then we're going to call resolve
which goes to the next step which runs
this function and we display Next
Step so resolve lets us control when to
go to the next
step in this case we waited until load
product prods was finished and then we
called resolve to go to the next
step so that's how promises work they
let us split our code into separate
steps and then we can wait for one step
to finish before going to the next
step now that we understand promises
let's convert the code that we had
before from a call back to using a
promise so first let's remove these
console. logs to make our code a little
easier to
read now in our previous code we
actually had two steps the first step is
to call load products and then once this
is finished the second step is to call
render order summary and render payment
summary and in our promise we have the
same thing our first step is load
product
once this is finished we're going to
call resolve and then go to the Second
Step so we're just going to copy this
second step into the second step up here
so we'll select this code and then right
click
copy and in do then we're going to right
click and
paste and now let's save
and let's check the web page so we'll
open the project and you can see that
everything is loading
correctly So This Promise does the same
thing as a call back that we had before
both of them have two steps the first
step is to load the products and then we
wait for the products to finish loading
and then we do the Second Step which is
to render the page
so now you might be wondering why do we
use promises it looks like it's more
work and more code than just using a
callback so callbacks have a big problem
which is multiple callbacks cause a lot
of
nesting nesting means having code inside
code like
this to see why this is a problem let's
say that we want to load the cart from
the back end as well I actually set up a
URL path that we can use to practice
called SLC
cart so first let's go into products.
JS and we're going to copy load products
and change it to load the
cart so we'll select this
function and then
rightclick
copy and let's open cart. Js
since we're going to load the cart from
the back end and let's scroll down to
the
bottom and here we'll right click and
paste that
code and now instead of loading the
products let's load the cart from the
backend so first let's rename this
function to load Capital C cart
and the first thing we need to change is
the URL path so instead of loading SL
products we're going to load slash cart
from my
backend so normally when we load SL cart
the backend will give us a cart
array however since we're just
practicing my backend will just give us
some text when we load SL
cart next we don't need this products
code anymore so we can select it and
then delete
it and instead let's just console. log
brackets and we just display the
response that we get back xhr do
response and we can remove this other
console.log and
save so now let's use load cart in our
previous
example on the left we'll scroll down
and open checkout.
JS and at the top let's import load cart
so here we'll import curly brackets load
cart from a string and we'll go to the
data folder which is do
dotdata slash and we'll load C.J
and now we're going to use this in our
callback code to show the problem with
callbacks first let's comment out this
promise so we can focus on the Callback
code at the top we'll type
slashstar and here star
slash and we'll remove the comments for
the
Callback and after we load the products
we're also going to load the
cart so inside this function we're going
to type load cart brackets and we're
going to give it a
function so this function is going to
run after the cart has
loaded so now let's say that we want to
wait for the products and the cart to
load before we render the
page to do that we need to move this
code inside this inner
function so we'll select this and then
right click
cut inside load cart we're going to
right click and
paste and remove this extra
line so now this code is going to load
the products wait for it to finish and
then it's going to load the cart and
then wait for the cart to finish
and then it will render the page or
display the page so let's
save and check the
console and now you can see that we
loaded the products and then we loaded
the cart and if we open the
page everything was displayed
properly so now let's go back to our
code and notice that when we added
another call back we we created another
layer of
nesting so we have code inside code
inside
code the problem with this is that each
layer of nesting adds some indents at
the front or spaces at the
front this means if we have lots of
callbacks our code will become more and
more nested like
this this is a big problem with
callbacks multi multiple callbacks cause
a lot of nesting and all these indents
make our code hard to work
with the promises solve this problem by
letting us flatten our
code for example let's load the products
and the carts again but this time using
our promise
instead first let's comment out the
Callback using
slashstar and and at the bottom star
slash and we're going to uncomment the
promise so here we'll remove the
comments and then in the next
step instead of rendering the
page we're going to load the cart like
we did down here so we'll type load cart
and
brackets now we have a problem here we
want to wait for load card to finish and
then go to the next step however we
usually do this using resolve but we
don't have resolve inside this
function to solve this problem inside.
then we can actually return a new
promise so at the top we're going to
return a new promise and
brackets so we're going to give this
promise a function just like we did up
here so we'll type brackets arrow and
curly
brackets and this function gets one
parameter called
resolve so inside do then if we want to
use resolve to wait for some code to
finish we can return a new promise
so now let's move our code into this new
promise so we can use resolve so we'll
select this code and then right click
cut and inside here we're going to right
click and
paste and remove these new
lines and we can give load card a
function to run when it's finished so
we'll type brackets arrow and and curler
brackets once load card is finished it
runs this function and then inside here
we're going to call resolve so that we
move to the next step so here we'll call
resolve and
brackets so now this will go to the next
step and we currently don't have a next
step to This Promise so let's add The
Next Step at the end to add another step
we're going to use dot then
brackets and we'll give this a function
brackets arrow and curler
brackets so the third step is to render
the page so we're going to do the same
thing inside
here so let's select this code and we'll
rightclick copy
inside the third step we're going to
right click and
paste and adjust the formatting if you
need
to so that's how we do these three steps
in the Callback using a
promise we do the first step wait for it
to finish call resolve and then it goes
to the second step we do the Second Step
wait for it to finish call resolve and
and then we go to the third
step so we promise let us have as many
steps as we want and we can use resolve
to wait for each step to finish before
going to the next
step so let's save this and check the
console to make sure it worked so we'll
open the
console and inside here we have the same
messages as last time first we load the
products we wait for it to finish and
then go to the next step then we load
the
cart wait for it to finish and then go
to the next step and then we render or
display the page if we open the page
you'll see that everything displayed
properly so now let's go back and
compare promises and
callbacks so even though promises
require a bunch of setup code you can
see that it keeps our code relatively
flat the third step doesn't get more and
more nested like in
callbacks so if we have lots of steps in
our promise this is what the code will
look like you can see that even when we
add more steps the code does not become
more and more
nested so promises help keep our code
flat
and avoid too much
nesting so that's why it's recommended
to use promises instead of callbacks
promises will keep our code more
flat so let's actually add some new
lines here as well as
here to better separate these steps so
it's a little easier to read
lastly we're going to learn two more
features of
promises the first feature is we can
give resolve a value so inside here
let's give it a value like the string
value
one so whatever we give to resolve is
going to be saved in a parameter inside
doth so inside this function we can add
a parameter called value
and now whatever we give to resolve is
going to be saved inside here and now we
can use
it so this lets us share a value between
two steps of a
promise so in here let's check if this
worked using
console.log
value and
save and if we look inside our
console you'll see that it displayed
value
one so whatever we give to resolve will
be saved in this
parameter the second feature is we can
run multiple Promises at the same time
currently we wait for things to load one
at a time for example we wait for the
products to load and then we wait for
the cart to load and then we go to the
next step to make this more efficient we
can actually load the products and the
cart at the same
time to do that we can use a feature
called
promise.all promise.all lets us run
multiple Promises at the same time and
wait for all of them to
finish so let's scroll to the top and
we'll do an
example so here we'll type the code
capital P
promise.all and
brackets inside these brackets we're
going to give this an
array inside this array we can give it
multiple promises to wait
for so let's just copy paste the two
promises that we have here into this
array so we'll start from here at the
end of the first promise and we'll
select this code right click
copy and in this array we're going to
right click and
paste and remove this line so we have
our first promise and at the end we're
going to add a comma and we're going to
give it a second promise so we'll scroll
down to our second promise here and
we're going to select this code starting
from here
and select the promise right click
copy and at the top we're going to right
click and
paste so we basically created an array
of promises and then we're going to give
this array to
promise.all and it's going to wait for
all of the promises to finish before
going to the next
step so now let's add a next
Step at the end to add a Next Step we're
going to use dot then and brackets and
we'll add a new line to make it a little
easier to
read so as usual dot then adds a next
step to a
promise it will give it a function to
run so brackets arrow and curling
brackets after we load the products and
load the cart we're going to render the
page so let's copy paste that code
inside this next step so we'll scroll
down to the render code and we'll select
it right click
copy and at the top inside then we'll
right click and
paste so now let's comment out our old
promise and try out promise do
all above our old promise we're going to
type
slashstar and below it we're going to
type star
slash and let's
save we'll go to our
console and you can see that it did the
same thing it loaded the products and it
loaded the cart and it's going to wait
for both of them to call resolve before
going to the next step which is to
render or display the page if we open
the page you'll see that everything
displayed
properly so that's
promise.all we can give it an array of
promises and it will run both of them at
the same time instead of waiting for
each promise one by
one also the values that we give to
resolve are saved in a parameter so
inside do then we can add a parameter
called
values and then these values that we
give to resolve are going to be saved
inside here so if we
console.log
values and
save and check the
console and it gives us an array of
values the first value is from the first
promise and the second value is from the
the second promise so here we didn't
give anything to resolve so the second
value is
undefined so that's an overview of
promises and
promise.all promises are a better way to
wait for asynchronous code to finish
versus
callbacks because they help us avoid
nesting and keep our code relatively
flat promises also have more features
like promise all which lets us run
multiple Promises at the same
time now let's save our changes into git
we're going to open the git
section inside cart.
JS we added a function to practice
loading the cart from the back
end and then in checkout.
JS we learn a promises and converted our
code from a callback to a promise
let's type a message describing our
changes learn
promises and convert code to promises
and
commit now that we learned promises
we're going to learn another feature
called
fetch fetch is a better way to make htd
PP
requests let's go back to our
code and we're going to open products.
JS and we're going to scroll down to the
load products
function currently we're using XML HTTP
request to make requests to the back end
and this uses a call
back fetch also lets us make requests to
the backend but fetch uses a
promise so let's do an example and we'll
make the same request except using fetch
this
time we'll scroll up and above load
products let's create another function
using
function and we'll name it load products
Fetch and brackets and curly
brackets and to use fetch we're going to
use the built-in function Fetch and
brackets so this makes an HTTP request
just like we did down here so let's make
the same request as we did in this
function at the bottom we made a get
request to this
URL so by default fetch will make a get
request so we just need to give it the
the URL that we want to make the request
to so at the bottom let's select this
URL and we're just going to
rightclick
copy and at the top inside fetch we're
going to right click and
paste so this will make the exact same
request as we did
below so you can see that fetch is a lot
more simple than XML HTTP request we
don't have to create a new object or do
any setup we can just call Fetch and
tell it where we want the request to
go so this will send a request to the
back end and now how do we get the
response so instead of using a call back
to get the response fetch uses a
promise when we call fetch this is going
to create a promise and we can add a
next step to This Promise using dot then
and
brackets so we'll give dot then a
function brackets arrow and curly
brackets so the way this works is that
fetch is going to send a request to the
backend when we get a response it's
going to go to the next
step it's also going to save the
response inside inside a parameter in
here so we'll add a parameter called
response and this will contain the
response from the back
end so instead of using a call back to
wait for the response fetch uses a
promise to wait for the
response so here let's
console.log the response to see what it
looks
like and now let's run this code
at the
bottom we'll run this function using
load products Fetch and
brackets so now let's
save and take a look at the
console so here's the response that we
get from Fetch if we open it you can see
it gives us a bunch of information about
the response like the status or whether
it succeeded or
failed as well as the URL that we made
the request
to so how do we get the data for the
products from this
response to do that we'll go back to our
code and to get data that's attached to
this
response we're going to use
response. Json and
brackets so this gives us the Json or
the data attached to the response in
this case it's our products
data next response. Jon is actually
asynchronous it returns a
promise so we need to wait for this
promise to finish before we continue to
the next
step to do that inside. then we can
actually return another promise so here
we're going to return this
promise when we return a promise it will
wait for this promise to finish before
going to the next
step so now let's add another step to
This Promise using dot then brackets and
we'll give this a function again so
brackets arrow and curly
brackets when response. Json finishes
it's going to give us the data that's
attached to the response and it's going
to save it inside this
parameter so this response should
contain our products data so let's name
this
parameter products data and let's
console.log this to see what it looks
like so here we
console. log the
products
data and and
save and let's open the
console and you see here that the
products data is the array of products
that we're going to use in our Amazon
Project you'll also notice that instead
of giving us just a big Json string like
before it actually converted the Json
into an array so basically it did json.
pars on the response for us so this this
saved us a little bit of
code finally now that we have the
products array let's do the same thing
that we did down here so we'll scroll
down and select all of this
code and we'll right
click
copy and then up
here we'll remove
this and rightclick and
paste so we'll do the same steps as
before
except using a promise this
time first instead of doing json. pars
on the response we already have the
array of products so we can remove this
and replace it with products
data and then we're still going to
convert this from objects to classes
like before we'll keep this console.log
so we can track the progress
this last line of code let us do
something after we finish loading the
products however instead of using a call
back like before we're going to remove
this
line and to do something after this step
we can actually return this entire
promise so to make it easier to read
let's save this entire promise into a
variable using const
let's call it promise equals
fetch so let's add some new lines here
as well as here to make the code a
little easier to
read so we're basically calling fetch
which creates a promise and then we're
going to save this promise inside this
variable and then at the end of this
function we can just
return the promise so we're just going
to return this whole promise out of the
function and then we can add even more
steps after this
promise so down here this is going to
give us the promise and then we can
attach another step using dot then
brackets and inside here we can give it
a
function brackets arrow and curly
brackets
so this attaches another step to the end
of This Promise so basically attaches
another step
here so after we load all the products
let's just
console.log next
step and
save so we'll check the
console and we'll see that we loaded the
products and then after we did The Next
Step so we can actually return a promise
out of a function and then keep
attaching more steps to that
promise so that's how we use fetch it's
a better way to make HTTP requests
because it uses promises
directly so now let's use fetch in our
project instead of using XML HTTP
request so first let's comment out this
code because we were just practicing
we'll type
slashstar and at the bottom star
slash and let's scroll up to load
products Fetch and we're going to export
this
function so we can use it outside this
file let's
save we'll go to the left
and open checkout.
JS and here instead of using load
products which uses callbacks let's
switch to load products fetch which uses
promises we'll scroll
up and we're going to import load
products fetch so here we're already
importing from products. JS we'll type a
comma load products
Fetch and now will replace load products
so remember that we need to give this a
promise and also remember that fetch
returns a promise so all we need to do
is to remove this code and just call
load products Fetch and
brackets this will return a promise and
we can use it with
promise.all so now let's save
we'll check our
website and you'll see that everything
is still
working so fetch helps us make our code
a lot cleaner because it can return a
promise directly and we don't have to
type out all of this extra
code finally let's use fetch inside our
tests on the left we'll open order
summary
test.js and remember that inside here we
used load products so let's switch this
to using load products fetch instead
first we'll import it at the top we're
importing from products. JS so we'll
type comma and import load products
Fetch and instead of load products we're
going to call load products
Fetch and brackets
so remember that this returns a promise
and we can attach more steps to This
Promise using the method dot then and
brackets and we'll give then a function
to run so brackets arrow and curly
brackets once the products are finished
loading it's going to run then and
inside here we're going to call done to
go to the next step of the test so here
we'll just call done and
brackets and we'll remove the old
code so now let's save to make sure this
is
working and we'll open the tests go to
the browser and open the
test and the order summary test should
be
passing so now let's save our changes
into git we'll open the git set
section inside products. JS we learned
how to use fetch which returns a promise
directly inside checkout. JS we used
load products fetch inside our project
and in order summary
test.js we use load products fetch
inside our tests let's create a message
describing these
changes convert load products
from xhr or XML HTTP request to fetch
and
commit next we're going to learn async
await which is an even better way to
handle asynchronous
code let's go back to our
code and we'll open checkout. Js
currently we're using promises to handle
asynchronous code but the problem with
promises is that it creates a lot of
extra code for example we need to create
a new promise we need to use resolve and
we need to use do
that async await is a shortcut for
promises and it removes all this extra
code so let's do our first example of
asyn a weit we're going to scroll
up and at the top we're going to create
a function using
function and let's name it load page
brackets and curly
brackets and inside we're going to
console.log the string load
page and now we'll learn the first part
of async await which is
async in front of the word function
we're going to add the word async and
space so async makes a function return a
promise so this code is a shortcut for
this code it basically wraps the code in
a
promise so now let's run this function
to show that it actually returns a
promise
So Below this we'll call load page and
brackets and because this returns a
promise we can add a next step to This
Promise using dot then
brackets and we'll give then a function
brackets arrow and curly
brackets and inside here let's just
console.log the string Next Step
now let's
save and we'll check the console so
we'll open the
console and you'll see that we loaded
the page and then in the next step we
displayed Next Step so when we put a
sync in front of function it makes this
function return a
promise this code is a shortcut for this
code
next if we return something from this
function for example we're going to
return a value like the string value
two this gets converted into resolve
value
two so this value is going to be saved
in a parameter in The Next Step so here
we'll add a parameter value and value
two is going to be saved inside here if
we
console.log the value and
save and then check the
console we'll see that value is equal to
this
string and that's it for async it just
makes a function return a
promise now you might be wondering
what's the point of this feature
so the reason we use async is because it
lets us use the second feature called
await await lets us wait for a promise
to finish before going to the next
line so let's do an example inside here
let's run some code that creates a
promise let's run load products fetch so
we'll type load products Fetch and
brackets so this loads the products from
the back end and usually this returns a
promise so one way to wait for this to
finish is to use do then and then give
it a
function so this runs this function
after load products has finished
now await gives us another way to wait
for this promise to finish instead of
using
then at the front we can just type
await so await lets us write
asynchronous code like normal code so
now it will wait for this line to finish
and get the response from the back end
before going to the next next line so we
don't have to do any more do then we
just write it like normal code line by
line this code is a shortcut for this
code and this makes our code a lot
easier to read than what we have down
here so now let's see what this looks
like in the console before we save let's
comment out this promise at the bottom
so we don't get
confused so we'll type
slashstar and at the bottom star
slash and now we're going to save this
code and check the console to see what
it
did so you see that we loaded the page
and then notice that it finish loading
the products before going to the next
step so this actually Waits for this
line to finish before going to the next
line in the code and this makes our code
a lot
cleaner now one very important thing to
know is that we can only use a weight
when we're inside an async
function that's actually the main reason
we use async so that we can use a weight
to make our code
cleaner now that we learned asyn wait
let's use it in our
project so previously we loaded the
products and then we loaded the cart and
then we rendered the page so let's
recreate this using async
await first we want to load the products
which we did here and we're going to
wait for this to finish and then we're
going to load the
cart so to load the cart let's use this
promise down here asyn await can only be
used with promises it doesn't do
anything with a call
back so we'll select this promise and
rightclick
copy and then up here we're going to
load the cart with a promise by right
clicking and
paste so now we want to wait for this
promise to finish before going to the
next line to do that at the front we can
simply type
await finally after we load the products
and we load the cart we're going to
render the page so we'll scroll down and
we'll select this
code and we're going to right click
copy and at the top
we're going to rightclick and
paste and that's it you can see that our
asynchronous code is a lot cleaner now
we load the products and then we just
wait for it to finish then we load the
cart and we also wait for it to finish
and then we run the rest of our code so
we can write asynchronous code like
normal code
so now let's remove the console.log at
the
top and also remove this return value
because we don't need
it and we'll remove do then at the
end and let's
save so now if we open our
website and open the
project you can see that everything
loaded properly
inside the
console you can see that we loaded the
products first wait for it to finish
then load the cart wait for it to finish
and then we displayed the page so that's
how we use a syn8 to make our code a lot
cleaner than what we had
before so now we'll learn some more
details about Ayn a weit
as I mentioned we can only use a weight
inside an async
function also the closest function has
to be
async for example here we have an async
function at the top and inside we have a
normal function so we can't use a weight
inside the normal function we have to
make this one
async another another detail is if a
promise resolves with a value for
example here we give resolve a value
like the string value
three normally this value will be saved
in The Next Step so if we did do then
and gave it a
function this value would be saved in
this
parameter however if we use await this
value just gets returned and we can save
it in a variable so instead of using
then we can Simply Save whatever is
resolved inside a variable using const
value
equals and this makes our code a lot
easier to read instead of having to use
then we can simply save this inside a
variable like normal code
and finally we can use await with
promise.all as well but I'll leave that
as an
exercise so that's async await it's a
shortcut for promises and it lets us
write asynchronous code like normal
code so when working with asynchronous
code a best practice is to use asyn
await over promises and callbacks
because they are much
cleaner so now let's save our changes
into git we'll open the git section in
checkout. JS we created the load page
function where we learned async and
await let's create a message describing
these
changes convert from promises to async
await and
commit now we're going to learn about
error handling when we're sending HTTP
requests across the internet we could
get unexpected errors for example the
internet connection might stop working
so we're going to learn how to handle
these kinds of unexpected
errors let's go back to our code and
we're going to open data/ products.
JS and we're going to
scroll to the load products
function so this uses a call back to
send a request and get a
response now what if there's an error
along the way for callbacks we usually
set up a separate callback just for
errors for example below this we're
going to add another event listener
using xhr do add event listener
brackets and the first parameter is the
event this time we're going to listen
for the error
event and then we're going to give it a
function so now if we get an unexpected
error it's going to run this function so
if we get an error let's just console
log a message
console.log a string
unexpected
error and usually when we get an error
we give some instructions on what to
do here let's just type please try again
later
and
save so this is called error handling if
we get an error during the request we
can handle it with this function so we
just display a
message so now let's try out this code
to simulate an error we're going to
change the url of the
request to
error. superimple backend. deev so this
will create an error because this URL
doesn't
exist so now down here let's call this
function so that we run this code and
get the error so we'll type load
products and
brackets and
save let's check the
console and you'll see that we displayed
this error
message so we got an error and it ran
this error function and it did not run
the load function
above also usually this callback gets a
parameter called error and this contains
some information about the
error so that's how we handle errors
when using callbacks we usually set up a
separate callback just for errors
so now let's remove this line since it
was just for
practice and we'll remove error from the
URL and change it back to super simple
backend dodev and
save next we'll learn how to handle
errors in
promises so we'll scroll up to the load
products fetch
function and this makes the same request
as below
but it uses
promises to handle an error in promises
promises give us two methods do then and
another method called dot catch brackets
and we're going to give catch a function
brackets arrow and curly
brackets so now if this request has an
error it's going to go to this catch
method and it's going to run this error
function so inside here let's also
display a message so let's just copy the
message that we had
below we're going to select this message
and then
rightclick
copy and then inside catch we're going
to right click and
paste and again to simulate an error
we're going to scroll up and change the
url
so we're going to add error at the front
do superimple backend
dodev so now let's call this function
and test out this error code at the
bottom we'll type load products Fetch
and
brackets and
save so now let's open the
console and you'll see in here that we
displayed the error message so we're
successfully creating an error it's
going inside catch and it displays this
message so just like callbacks catch
gets a parameter called error and this
contains information about the error if
we need
it so that's how we handle errors with
promises we have another method called
Dot catch that will run this function if
there's an
error so now let's remove this practice
code and switch back the
URL so remove error and Dot and
save lastly we'll learn how to handle
errors in async
await so let's go to the left and we're
going to open the checkout file so we'll
scroll down and open checkout.
JS and inside here we're using async
await so the catch errors when using
async await we're going to use some new
syntax called try
catch above this we're going to type the
word try and curly
brackets and now we're going to put the
code that could cause an error into try
so here we're making a request to the
back end and here we're also making a
request to the back end so this code
could cause an error so we're going to
move it inside try so we'll select it
right click
cut and then inside here we'll right
click and
paste and now if any of this code inside
a try gets an error we can catch it
using this code at at the bottom we'll
type
catch brackets and curly
brackets Now Catch is going to get one
parameter in these brackets called error
and this contains information about the
error if we need
it so catch Works similarly to catch for
promises if there's an error inside here
it's going to catch the error or it's
going to hand handle the error and run
the code inside catch so in here we can
put our error message so let's go back
to products.
JS and let's copy the error message so
we'll select this and right click
copy and back to
checkout inside catch we'll right click
and paste
so now I'll remove this new line and add
a new line here to make it a little
easier to
read and let's test out this
code to do that we'll go inside
products. JS again and we're going to
modify the URL again so at the front
here we're going to add error do super
simple backend and also we're going to
comment out the dot catch because right
now the error is going to be handled
here and it's not going to be handled
outside in the try catch so we're going
to comment this out using
slashstar and at the
end star slash and
save so we'll go back to checkout.
JS and here we'll also
save and now let's open the console
and you'll see that we had an error here
we caught the error and it ran this code
and displayed the error
message so that's how we handle errors
with async await we put our code that
can cause an error inside try and if
there is an error it's going to run the
code inside
catch so now let's go back to products
and remove error from the URL and the
dot and we'll also uncomment
catch and
save next we're going to learn some more
details about try catch so we'll open
checkout.
JS and one thing to know about TR catch
is that we don't have to use it with
async await we can actually use TR catch
with synchronous code or normal code for
example here we try to run a function
that does not exist and this will cause
an error try catch will catch this error
and display a message so notice that
we're not using async O8 here this is
just normal code so we can use try catch
to catch errors in normal code as well
another detail is whenever we get an
error it will skip the rest of the code
so here it will not console.log next
line it will skip the rest of this code
and go directly into
catch now one thing you might be
wondering is why don't we just use TR
catch everywhere and prevent all of our
errors so try catch and any error
handling is meant to handle unexpected
errors that means our code is correct
but something outside our control caused
the error so we can give some
instructions on what to
do so that's why we don't use try catch
everywhere we only use it for unexpected
errors or errors outside of our
control so the last thing to know about
error handling is that we can man
manually create
errors to manually create an error in TR
catch at the top we're going to use the
word
throw so throw creates a new error or it
throws an error that we're going to
catch a
later and now we need to give this error
a
value so we can use any type of value
for an error like a string number or an
object for an example we're just going
to use a string error
one so this will manually create an
error when we get an error it's going to
skip the rest of the code inside these
curly brackets and it's going to go
straight into catch so this error value
is going to be saved inside this
parameter and it's going to run the code
inside
catch so if we
save and then check the
console throw creates an error and it's
going to display this error message up
here so now let's comment out this
example and
save next if we're using promises there
are two ways to manually create an
error so inside this promise if we want
want to manually create an error we can
also just throw an error like the string
error
2 and this will throw an error and go
inside dot catch by the way if we await
a promise instead of going into catch
it's going to go inside catch
here so await makes it behave sort of
like synchronous code or normal code if
we save
and check the
console it will get an error it will not
load the cart and it will display this
error
message so now let's comment out this
example and we'll learn the second way
to create an error in a
promise inside a promise if we need to
create an error in the future then we
need to use different code for example
here we load the cart and then once it's
finished loading we're going to run this
function so this function runs in the
future inside this function throw does
not work because throw does not work in
the
future instead promises give us another
way to create an error when we create a
new promise it gives us a second
parameter
called
reject reject is a function and it lets
us create an error in the
future so here after we load the cart in
the future let's create an error using
reject brackets and a string error
three so let's comment out resolve as an
example
so now let's
save and check the
console and you'll see that reject
created an error in the
future and then it goes down here and
runs the code inside catch and creates
the error
message so the manually create an error
in a promise we have two ways we can use
throw if we're creating the error
synchronously or right away or we can
use reject if we're creating the error
asynchronously or in the
future so now let's comment out
reject and uncomment resolve and
save so that's error handling it lets us
handle unexpected errors and it also
lets us create our own
errors so now let's save these changes
into git we'll open git inside products.
JS we added. catch for
promises and an error function for
callbacks and then in checkout. JS we
added try catch for async await and we
also learned how to manually create our
own
errors so we'll type a message
describing our
changes learn and error
handling and
commit now that we learned backend
promises and async await let's use them
in our
project we'll open our
project and open the tab for the project
and we're going to go to the checkout
page so the feature we're going to work
on is in the checkout page we're going
to make this place order button
interactive when we click this button
it's going to take our cart and turn it
into an
order this time instead of writing this
code ourselves we're going to use the
back end to create an
order so first let's set up an event
listener for this button we'll go back
to our
code and open our files
and that button is in a section called
the payment
summary so we're going to open scripts
SL checkout payment summary.jpg
your order and now we have the code for
the button right here so we're going to
set up an event listener so we can do
something when we click
it first we'll add a class to the button
so we can get it in our
JavaScript at the end of the class let's
create a new line and add a class
js- Place Das
order and now after we put this HTML on
the page we're going to set up an event
listener to do that we're going to get
this button into our JavaScript using
document. query
selector
brackets and a string and to select this
class we're going to start with a
js- place-
order and now that we have this button
we're going to add an event listener to
to it so we'll create a new line and use
the method do add event
listener
brackets and we'll give this two
parameters the first parameter is the
event we want to listen for which is
click and the second parameter is a
function we want to run when we click
this button so we'll type brackets arrow
and curler brackets
and now when we click this button we're
going to make a request to the back end
to create the
order so for this example I set up a URL
path in my backend for creating orders
called slash
orders so inside here we're going to
make a request to the backend using
fetch
brackets and then we're going to give it
the URL of the request which is H ttps
colon double
slash super simple
backend. Dev and the URL path slash
orders however this time we need to send
some data to the back end so we need to
send our cart to the backend in order to
create an
order to send data in a request we need
to use a different type of requests so
there are four common types of requests
get post put and delete get means we
want to get something from the back end
post means we want the back end to
create something put means we want it to
update something and delete means we
want to delete something so far we only
use get request which let us get data
from from the back
end however get requests don't really
let us send data to the back
end so in this situation we want to
create an order so we're going to use
post to create something post lets us
send data to the
backend so to create a post request
instead of a get request we're going to
give fetch a second
parameter which is an
object and inside this object we're
going to give it a property called
method
colon and this is the type of the
request in this case we'll use the
string
post and after this we're going to give
another property called
headers colon and this is going to be an
object
headers gives the backend more
information about our request and this
is needed when we're sending data to the
back
end inside this object we'll add the
property string Capital C content Das
capital T
type
colon and the value will be the string
application slash Json
this tells the back endend what type of
data we're sending in our request here
we're going to send some Jon which is
basically a JavaScript
object next we're going to add another
property called body
colon and this is the actual data we're
going to send to the back
end according to the documentation we
need to send an object with a property
called cart and this contains our cart
array so in the body let's send an
object with a property called cart colon
and give it the cart
array so we should have the cart array
in this file and it should be called
cart and finally we can't send an object
directly in our request we need to
convert it into a Json string
to do that at the front we'll use
json.
stringify Open Bracket and close bracket
so this will convert this data into a
Json string and now we can send it to
the back
end okay so after we send this request
we need to wait for the response to come
back to do that fetch returns a
promise however instead of using dot
then to add a Next Step let's use async
a weit because it's cleaner so first we
need to make this function
async remember we can only use await
inside an async
function so at the front of this
function we'll type the word
async and now in front of fetch we can
use
await this is going to wait for fetch to
finish or for fetch to get a response
from the back end and then go to the
next
line now because we used await we can
save the response in a variable so at
the front we'll create a variable const
and call it response and make it equal
to this result
next remember that to get the data
that's attached to the response we need
to use response.
Json so down here we're going to use
response. Json and
brackets now remember that response.
Json is also a promise so at the front
we can use await to wait for this
promise to finish before going to the
next line
so this will give us the data that's
attached to the response which should be
the order that was created by the
backet so let's save this in a variable
using const order
equals and finally let's
console.log the order to see what it
looks like so now let's save
and then we'll open the
project and make sure you have some
products in your
cart and then we'll click place
order and now we can check our console
to see what the order looks
like and you'll see that we got an order
object from the back end it has an order
ID an order time and the products in our
order including a delivery time and the
quantity that we
want so we successfully use the back end
to create a new
order let's also check the network tab
up here and open
network so I'll resize this to make it a
little easier to read and we'll search
for the super simple
URL and then we'll find this request
orders with a status 200 and we'll click
it so inside the details you'll see that
it was a post request sent to/ orders
and the status code was 200 so it was
successful inside the payload tab this
is what we sent to the back end which is
our
cart in the preview tab this is what the
backend sent back an order object
and the response tab is the same thing
we got the order object
back so that's how a real world website
works instead of creating the order on
the web page or on our computer we send
an HTTP request to the backend to create
the
order okay now that we created an order
let's save it
somewhere we'll go back to our
code and on the left inside the data
folder let's create a file for our
orders so we'll click inside this folder
and then click here to create a file and
let's name it
orders. JS and press
enter at the top let's create an array
to contain rain all of our orders we use
const orders equals and empty array and
let's export this so we can use it in
other files
export next let's create a function for
adding an order to this array so we'll
create a
function add
order brackets and curly brackets and
we'll give this function an order object
and we're just going to add it to the
array now for orders we usually want the
most recent order at the top so we're
going to add this order to the front of
the array to do that we'll type the
array name orders and use the method do
unshift
brackets and we'll give it the
order so this will add the order to the
front of the array instead of the
back finally let's save our orders into
local storage so we'll create a function
to save to local storage
function save to
storage brackets and curly brackets and
we'll run local
storage. set item brackets and a string
we'll use a local storage key orders
comma and remember local storage only
supports strings so we'll use
json.
stringify
brackets
orders and now when we modify this array
we're going to save to storage and
brackets finally at the top let's load
the orders from Storage
so
here we use local
storage. getet item brackets the string
orders and remember that this will be a
string so we need to convert it back
into an array using the code json. pars
and
brackets now in the beginning we're not
going to have any orders saved in local
storage so we can give this a default
value using or and an empty array so if
there's nothing in local storage it's
going to use this empty array as a
default and
save so now let's use add order in the
payment summary so first we'll export
this
function and and
save and then open the payment summary
again and at the top we're going to
import that function so here we'll
import curly brackets add
order from a
string and we'll go into the data folder
which is do do slash
dotdata SL orders
doj and and we'll scroll back
down and now after we create an order
from the back end we're going to add it
to the array and save it in local
storage using the function add order
brackets the order
object and
save now if we go to our web page and
click place
order this should create an order order
from the back end and save it in local
storage so now we can open our
console and go to the console Tab and
let's check if it's inside local storage
using local
storage. getet item brackets and the
string
orders and press
enter and you'll see that we saved an
order in local store
storage if you ever want to remove the
orders from local storage you can use
this
code local
storage. remove item brackets and the
string
orders press enter and then refresh the
page let's go back to our code
and let's get some practice and add some
error handling to this code so at the
top for asyn of weight we're going to
use try catch so we'll type try curly
bracket and catch brackets and curly
brackets and catch gets a parameter
called
error so now we're going to move our
code inside a try we'll select this code
and then right click
cut inside try right click and
paste and I'll create a new line and now
if we make a request and there's some
sort of network error that error will go
down here and we'll run the code inside
catch so in here let's display a
message
console. log the string
unexpected
error try again
later the last step is after we create
an order we should go to the orders
page to do that at the bottom
here we're going to use an object called
window.location window.location is a
special object object provided by
JavaScript and it lets us control the
URL at the top of the
browser if we change the location object
it will change the url at the top so
let's give this a try we'll go into our
code and we'll type
window.location Now location has a
property
called href
this gives us the URL at the top of the
browser and if we change the href
property it will change the url at the
top of the browser so we'll try that in
our code we're going to change. href and
make it equal to the string orders.
HTML so this will replace everything
after the slash here with orders.
HTML and this will open the orders. HTML
file which is at the bottom
here and this will open the orders
Page by the way orders. HTML is a file
path the current file is checkout. HTML
because this code is running on the
checkout page so it starts from
checkout. HTML and then looks for a file
called orders. HTML beside it which is
this file here and it loads this file in
the
browser so now let's
save we'll open the project and then
click place
order so it should create a new order
using the backend and it will take us to
the orders
page so right now we have a list of
order objects and that's all the data
that we need to create this page I'll
leave generating the HTML and making
this page interactive as
exercises so now let's check our tests
to make sure that everything is still
working we'll open the tab for our tests
and I'll refresh just in case and it
looks good and we'll save our changes
into git we'll go to the git section
inside orders. JS we created some
functions for saving our orders and in
payment summary.
JS we made the place order button
interactive and we use the backend to
create an order let's create a message
describing these
changes create order using the back end
and
commit so we're going to learn one more
thing in this lesson and this is needed
to create the tracking page we're going
to learn how to use URL
parameters so first let's open our
project and we'll go back to the orders
page and on this page we have these
track package links beside the products
if we click this link it will take us to
the tracking page at tracking.
HTML however right now this page is just
plain HTML there's no
JavaScript so if we go back to our
orders and then track a different
product you'll notice that all of the
tracking pag pages are the
same so we need to make each tracking
page different depending on the order
and the product so how do we know which
product to track on this
page to create this we can use a feature
called URL
parameters URL parameters let us save
data directly in the
URL to create a URL parameter at the top
after this URL we're going to type
question mark and then order capital i d
equals 1 2 3 for example and press
enter so the question mark means we're
adding a URL parameter to this
URL so a parameter is a property value
pair the left side is a property and the
right side is a value
this is sort of like an object like
this so using URL parameters we can save
some data in the URL like
this and then we can use JavaScript to
get this data out of the URL to do that
we'll go back to our
code and we'll open our files here and
we'll scroll down to the bottom to the
tracking
page and let's scroll all the way down
to the
bottom and at the bottom of the body
let's add a script tag to run some
JavaScript so we'll type less than
script greater
than and to get the parameters out of
the URL we can use a built-in class
called
URL first let's generate an object using
this class we'll type
New Capital URL and
brackets and we'll give it the URL that
we want to get the parameters
from so in here we'll type
window.location.href
remember that
window.location.href gets the URL at the
top of the
browser and now let's save this object
in a variable
at the front we'll create const URL
equals this
object so this URL class analyzes the
URL that we give it and breaks it down
into different parts one of the parts
are the URL
parameters to get the parameters we're
going to use a property
url. search capital p perams
by the way URL parameters are also
called search
parameters because they're used for
features like YouTube
search so search params will let us get
the URL parameters up
here so let's say that we wanted the
order ID
parameter inside our
code search params has a method called
Dot
get brackets and this lets us get
individual parameters so inside here
we'll give it a string and we'll get the
order capital i d parameter out of the
URL so let's console.log this
console.log and
brackets if we
save and then open our project and go to
the tracking page and then open the
console right click
inspect the
console you'll see that it gave us the
order ID that we saved up
here so using that code we can get URL
parameters out of the URL at the top and
then use them to create this
page we can also say save multiple
parameters in the URL to save another
parameter at the end we can just type
and and now we can give it another
property value pair like product Capital
ID equal
456 and press
enter and now inside our code we can get
this second parameter
so inside here we're going to make a
copy of this line select it right click
copy and then down here right click
paste and this time we're going to get
the
parameter product Capital ID and
save if we open the page and open the
console
we got the order ID as well as the
product ID out of the
URL so URL parameters lets us save
different data in each
URL and we can actually go back and
forth between them so if we click the
back button it will go to this URL and
this URL has different data or
parameters saved inside if we click
forward this URL has different
parameters or data saved
inside and this is how YouTube search
works if we search for something our
search is saved as a URL parameter if we
search for something else our search is
also saved as a URL parameter and we can
go back and forth between the
two so this is actually all the data
that we need to create the tracking page
we need to know which order it is and
which product it
is now there's one more thing to know to
create this page we'll go back to our
code and we're going to open the orders
page at orders.
HTML and we're going to find the track
package button using control F or
command F and we'll type the text in
that button track
package so notice that these buttons are
just a link to the tracking page or
tracking.
HTML so when you're generating this
HTML make sure that you add URL
parameters after this tracking page
URL using question mark the order
Capital ID equals and then you
substitute the order ID like 1 2 3
and then and also attach the product ID
product Capital ID equals
456 so when generating this HTML make
sure you substitute the order ID and
product ID into this URL so that when it
opens the tracking page you know which
order and which product to track
I'll leave generating the HTML and
making the tracking page interactive as
exercises so now let's save this
file and let's check our tests so we'll
open the browser and open the test Tab
and everything is still working and
we'll save these changes into git open
the git
section in orders.
HTML we added an example of adding URL
parameters to the tracking page
Link in tracking. HTML we added an
example of getting the parameters out of
the URL at the
top let's create a message describing
these
changes add URL
parameters
example and commit
and that's the end of this lesson in
this lesson we learned what a vend is
and how to make HTTP requests to the
back end we learned how to use XML HTTP
request and
fetch we learned how to handle
asynchronous code using callbacks
promises and async await we learned how
to test asynchronous code we learned
about error handling for unexpected
errors we use the backend in our project
and we learn URL
parameters before we look at the
exercises you might be wondering what's
the next step after this course instead
of just using a backend the next step is
to learn how to create our own backend
to do that you need to learn the command
line and after that you'll learn a
technology called nodejs which lets us
create our own
backend also after this course you can
learn how to put a website on the
internet using this video right
here here are some exercises that'll
help you practice what we learned in
this
lesson e
thanks for watching here are some other
videos and courses that you might be
interested in if you want to support
this channel you can click like
subscribe and share this video with
others thanks again and I'll see you in
the next one
Can't find what you're looking for?
Get subtitles in any language from opensubtitles.com, and translate them here.