Introduction to JavaScript Basics
Introduction to JavaScript Basics
hey everybody today I decided I'm going to teach you everything you need to know to
get started working with JavaScript throughout this course we'll be working on a
few projects you could add to your
0:08
portfolio which include but are not limited to a digital clock a stopwatch a
functioning calculator a game of rock paper scissors an image slider and our final
project will be a
0:22
weather app that fetches data from an API if that sounds good to you I encourage
you to sit back relax and enjoy the show hey if you don't mind please give this
video a like post a
0:34
random comment down below and subscribe if you'd like to be a fellow bro it doesn't
cost you anything thank you JavaScript is a programming language used to create
Dynamic and interactive
0:46
web pages JavaScript runs on a web browser such as Google Chrome Safari Edge
whatever you use to browse the internet basically by using JavaScript we can
respond to user actions and
0:57
transform user input whenever somebody interacts with our site in this example I
have a calculator written with HTML it's not very pretty and it doesn't function we
have the framework that we
1:07
need at least though by applying CSS we can add color and style to this calculator
but unfortunately it still doesn't function by including JavaScript code this
calculator can perform actions
1:19
and is well useful so in this video I'm going to show you everything you need to
know to get started working with JavaScript I would recommend knowing HTML and CSS
before starting the series
1:29
I do have a full free course on my channel if you're interested in learning those
or if you need a refresher if you don't know either you could probably still get by
watching this video I'll
1:39
walk you through both as we go along throughout the series now before we do begin
you will need a text editor one text editor that I recommend is VSS code which you
can download from code. visual
1:51
[Link] for a step-by-step instruction of how to install it feel free to check
out the HTML and CSS series with that out of the way let's Dive Right In so what
we'll need to do is create a new
2:02
project folder in vs code you can go to the left toolbar go to explore we will open
a folder I'll place this folder on my desktop just for convenience I will create a
new folder which I will name
2:15
website to contain my website files let's select this folder and we are now within
our website folder we'll need three files an HTML file CSS file and JavaScript file
we'll
2:30
begin with the HTML file we can close out of this welcome window I will name my
HTML file [Link] in a website the [Link] file is typically used as the
homepage we have our HTML file next
2:47
comes the CSS file mine will be named [Link] the CSS stylesheet is in charge of
the overall appearance of the web page this can include fonts colors positioning
stuff like that then lastly
3:01
we have the JavaScript file which I will name [Link] the Javascript file is in
charge of the interactivity of a web page so alt together we have structure style
and actions so rearrange these
3:15
tabs however you like I switch back and forth between the JavaScript and HTML file
quite often so I tend to put them right next to each other but do whatever is most
convenient for you so to
3:25
generate the necessary text to create a web page in your HTML file in vs code you
can type exclamation point then hit tab so here you can change the title of your
web page if you want I'll change my
3:37
title to be my website and that's all we'll need for now now we'll need to link the
stylesheet to the HTML file now we are going to create a link tag we can link
3:50
an external stylesheet to our HTML file within the link tag there is a relationship
attribute shortened to re the relationship ship will be stylesheet we are linking a
stylesheet then the
4:03
next attribute we need is the hre attribute where is the CSS file located well it's
right next to each other we only need the file name so we are linking the CSS
Styles sheet now our CSS
4:17
stylesheet is linked to our HTML file now we need to link the Javascript file to
our HTML file we can do that by adding a pair of script tags we will set The Source
attribute to
4:30
be the name of the JavaScript file [Link] all right everything should now be
linked together the last thing we'll need is the live server extension in VSS code
go to
4:44
extensions we will search for live server it should be this one we are going to
install this extension so whenever we save any changes to our files the web page
should refresh
5:02
automatically so now let's test this you can go to file save or use the shortcut
I'm just going to save everything I'm going to rightclick on our HTML file then
open with live
5:16
server and here is our web page but it currently doesn't have anything uh let me
just minimize this I will readjust this window throughout this course I'll have VSS
code alongside a web browser
5:30
with our HTML file we can add elements such as an H1 element these are typically
used as headers I'm going to say hello then save and that should update
automatically or you can press
5:41
the refresh button but since we have live server installed we shouldn't need to
then paragraphs are typically used for a paragraph a text in vs code to generate a
random paragraph of text you
5:54
can type lauram then hit tab now we should have a random paragraph I believe it's
Latin at least it looks like it to change the style of our web page we can go to
our stylesheet to change the style
6:07
of the body of our document we will select body I'll change the font family to
something else font family how about verdana there we now have a different font to
increase the font size you can
6:21
set the font size property to be either in pixels or em personally I'm a fan of
using em 2 em means 200% where 3 em is 300% but that's a little too big let's stick
with 2 em all
6:39
right and that is everything we need to get started oh important note you do want
your script element at the bottom of the body of your document just in case there's
an error with your
6:48
Javascript file you do want all of the HTML elements to at least render first
before running any JavaScript code all right so let's delete our H1 elements and
our paragraph element we no longer
7:00
need them for now be sure to save everything we'll work with some basic output I'm
going to zoom in a little bit to Output some text you can type [Link] add a
set of parenthesis
7:14
then a semicolon at the end within the set of parentheses to Output some text you
can either use double quotes single quotes or back ticks personally I'm a fan of
using these back ticks this is
7:27
known as a template literal they're helpful with inserting variables which we will
discuss in the next lesson using either double quotes or single quotes or back
ticks we can output some text let's
7:38
say the word hello be sure to save I'm holding contrl s on Windows there's no
apparent output we have to go to Dev tools so right click on your web page go to
inspect then console and here's our
7:52
basic output hello for an additional line of output we can [Link] again let's
print print a different message I like pizza let's save and here's my second line
of text I like
8:08
pizza and I'm just going to move these windows a little bit that's better
throughout much of the series we will be working with this window again you have to
right click on your web page go to
8:18
inspect then go to console now within our web page to create an alert box you can
type window. alert at a set of parentheses semicolon to the end we'll use a
template literal we'll need a set of back
8:35
ticks this is an alert this should create a pop-up window this is an alert let's
create another let's copy what we have paste it I like pizza let's save this is an
alert okay I like pizza
8:59
not sure why we need to tell a user that but we can now we have comments to create
a comment you type two forward slashes comments aren't used for output they're used
as notes for yourself or
9:11
for other developers this is a comment so when I run this program then if we were
to go to our Dev tools we don't see this comment at all they're not displayed as
9:23
output they're either used for notes for yourself or for other people for a multi-
line comment you can type a slash asterisk anything that comes after will be a
comment this is a comment you can see
9:39
that the text is green that means it's a comment again we should not be able to see
these comments they're hidden I'm going to turn this JavaScript code into comments
just for the next part because
9:52
these window alerts are kind of annoying to be honest all right now what we're
going to do is populate our web page page with some text within our HTML file I
will create an H1
10:05
element H1s are usually used for headers or titles there will be no text content
yet but I will set an ID I will give this H1 element a unique ID of my H1 feel free
to pick a
10:19
different ID something you'll remember I will also create a paragraph element I
will set the ID to equal my P meaning my paragraph so remember there is no text
content currently using
10:34
JavaScript we will add some text content first we need to select these elements by
their ID my H1 and my p uh let's do that here we will type document meaning the
document of our web
10:49
page do get element by ID do pay attention to the capitalization what id are we
getting let's start with my H1 so copy the ID paste it within the set of
parentheses
11:05
be sure you're including quotes as well follow this with DOT text content we will
set this equal to how about the word hello let me zoom out a little again this can
be back ticks single quotes or
11:23
double quotes all right let's type the word hello now when I save and and refresh
the page that H1 element should display the word hello now this time let's get our
paragraph element with the
11:38
ID of my P my paragraph document. getet element by ID the ID that we're getting is
my P will change the text content equal to uh what can we say I like pizza there we
go hello I like pizza all right
12:03
everybody so that's the basics of JavaScript when working with basic output you can
use [Link] which we will be using a lot to create an alert you can use window.
alert to change the
12:15
text content of an HTML element you first have to select that element then change
the text content then set it equal to some text of you're choosing all right
everybody so that is the very
12:26
basics of JavaScript and in the next topic we will cover variables all right well
it's time that we discuss variables do you remember from middle school or
elementary school
12:38
when you learned algebra you had to solve for what the value of x was X was some
representation of a value well that's kind of what a variable is in programming
it's a container that stores
12:48
a value the variable behaves as if it were the value it contains there's two steps
to creating a variable declaration and assignment to use a variable we have to
first declare it it we'll use the let
13:00
keyword then a unique variable name like X then a semicolon so what we've done is
declaration each variable name needs to be unique if I were to declare another
variable named X we would run into an
13:14
error a syntax error identifier X has already been declared so your variable names
need to be unique I can declare two variables X and Y and they both have different
names that is fine but they
13:26
can't have the same name the next step to create a variable is to assign it a value
once you declare your variable you don't need to declare it again so I'm going to
assign X to equal some number
13:37
like 100 we can use this variable X and it will behave as if it was the value 100
let me demonstrate so if I was to [Link] X well then it's going to display 100
if
13:52
I were to change this value to 123 well X is now 123 you you can do both
declaration and assignment together that would look something like this let x equal
123 this is both declaration and
14:09
assignment if you're creating a program and you know what your value should be you
can assign them a value right away sometimes you may want to accept some user input
so then you might do
14:19
assignment later in two steps it's really up to how you write your program there's
a few different data types in JavaScript the first is number like 123 let's create
a descriptive name for our
14:31
variable like age we will store a user's age according to my analytics in YouTube
the average age of my viewers is 25 so let's say that my age is 25 then if I was to
14:45
[Link] my age variable it would behave as if it were the number 25 let's
create a few more variables another example of a number could be price let price
equal 10 .99 maybe it's
15:01
$110.99 or some other unit of currency of you're choosing then we will [Link]
price $10.99 what about a GPA a grade point average my grade point average is a
solid 2.1 it's not great but C's get
15:19
degrees [Link] GPA 2.1 using a template literal we can insert a variable using
a placeholder within [Link] I will use back ticks let's write a sentence you
are then to
15:35
insert a variable use dollar sign curly braces place your variable name within the
curly braces then we can continue our sentence you are variable age years old let's
create another sentence using
15:54
[Link] the price is dollar sign curly braces price the price is $10.99 I'm
going to insert a dollar sign before our price and that looks better feel free to
16:12
choose some other unit of currency okay let's add a sentence to display our GPA
[Link] your GPA is colon space we're inserting a variable we need dollar sign
curly braces we're displaying our
16:31
GPA your GPA is 2.1 now if you need to display the data type of a variable you can
use [Link] then preedee the variable with the type of keyword what is the type
of age age is a number
16:50
type price is also a number type same thing with GPA they're all numbers let's go
over a different data type let's go over strings a string is a series of characters
let's say we have a user's first
17:10
name to create a string you can either use double quotes or single quotes
personally I like double quotes then you can type in some characters like a first
name let's say my first name is bro feel
17:24
free to pick your own first name I will display the type of my first name variable
and it says it's a string a series of characters then I will display my name
[Link] first
17:40
name and it is bro or whatever your first name is whatever you put here let's
include our variable within a template literal your name is add a placeholder first
name your name is bro what are
18:00
some other examples of string maybe somebody's favorite food favorite food my
favorite food is pizza type in your favorite food [Link] you like at our
placeholder favorite
18:27
food you like pizza maybe if I like something else like sushi well you like sushi
okay another example of a string could be an email let email equals then type in
your email I'm just going to make one
18:44
up bro [Link] [Link] your email is email your email is bro [Link] let me
make the G lowercase now an important thing with strings is that strings can
contain
19:08
numbers after bro I'll add 1 two 3 so a string is a series of characters they can
include numbers but we can't use these numbers for any sort of math strings have a
different behavior from
19:21
numbers numbers we can use in arithmetic Expressions strings not so much all right
let's turn these lines into comment then I will discuss booleans okay booleans are
either true
19:33
or false typically they're used as Flags in your program let online equal true
booleans are either true or false is somebody online or are they offline this is
either true or
19:47
false I will display the type of my variable online [Link] type of online so
online is a Boolean variable let's display our variable within a template literal
type in whatever your first name
20:05
is bro is online then I will insert a placeholder add my Boolean variable of online
bro is online that is true if I were to change this to false bro is online is false
booleans are typically
20:23
used as a sort of flag so another example could be for sale is something for sale
or not let's say that we are selling I don't know cars is this car for sale I could
set this to be true or false let's
20:45
[Link] is this car for sale then I will add my Boolean variable for sale is
this car for sale that is true another example let's say that somebody is enrolled
in school like in college
21:02
courses we could say let is student is somebody a student are they enrolled this
can be true or false [Link] enrolled colon space is student is the student
enrolled in classes that is true
21:28
so those are booleans they're either true or false typically we don't use them as
direct output like you see here we usually use them with if statements to check
something like if somebody's
21:39
online do this if not do something else is a car for sale if that's true then
display the car if it's not then hide it we'll have more practice with booleans
when we reach if statements all right
21:52
now what we're going to do is we will close out a Dev tools we'll display some
variables within our web page so let's delete everything we have I'll create three
variables let
22:05
full name equals type in your full name feel free to add a space between your first
name and last name let age type in your age and let student equals if you're a
student type
22:24
true if you're not in school type false I am not in school anymore so I will type
false we will go to our HTML file then add some HTML elements I will add three
paragraph
22:38
elements so that's one 2 3 I will give my first paragraph an ID of P1 then let's do
the same with the other two paragraphs let's rename the second as P2 and the third
as
22:56
P3 so to change the text content of an HTML element we're going to type document
meaning the document of our web page then we will get our element by its ID get
element by ID then within a set
23:16
of parentheses within a set of quotes we will select the ID that we need let's
start with P1 then add do text content to change the text content then we will set
this equal to a
23:31
variable or a template literal let's begin with a variable so full name our P1
element should display your full name let's do this with P2 I'm going to zoom out a
little
23:48
bit P2 textcontent equals age it says that I'm 25 and then P3 let's display student
or better yet is student let's change that is student false I am not a student but
you
24:07
might be though that might be true then let's display our variables along with some
text using a template literal let's copy our full name your name is add a
placeholder
24:22
place our variable name your name is Bro Code or whatever your name is let's cut
our age variable you are variable age years old you are 25 years old and then let's
cut is student add a template
24:45
literal let's say enrolled are you enrolled in school add a placeholder paste our
variable enrolled that is false I am not in school anymore more all right everybody
so those are variables it's a
25:00
container that stores a value the variable behaves as if it were the value it
contains there's a couple different basic data types you have strings which is a
series of text numbers and booleans
25:12
there's more advanced data types but we'll cover that later and well those are
variables in JavaScript yeah what's going on everybody so today I need to explain
arithmetic operators because well
25:25
programming can sometimes involve a lot of M operand are values variables Etc in
this equation 11 x and 5 are all operand operators they can include but are not
limited to addition subtraction
25:41
multiplication and division in this equation the addition sign would be the
operator so there's a few things you should know regarding arithmetic operators in
JavaScript so let's begin
25:52
let's pretend that in the scenario we are a teacher we have a group of students let
students equals what's a good class size maybe 30 students then I will [Link]
my students
26:10
variable and it should be 30 let's say that a new student joins the class and I
need to change this variable to increase students by one I can say students equals
this will reassign my variable
26:24
equals the current value of students + 1 now we have 31 students now for
subtraction that is the minus sign to subtract a student we can reassign our
variable students equals students minus
26:40
one now we have 29 then we have multiplication which is represented by an asterisk
we will double the number of students we have students equals students as Risk 2 to
multiply by two we have 6
26:59
students division is a forward slash we will split our class of students into two
students divided two we now have 15 all right then we have exponents exponents is
represented by double
27:17
asterisks what is students to the power of two 900 students that is a very large
class maybe it's a lecture or something in a college so students to the power of
three that would be students to the
27:33
power of three would be 27,000 double asterisks is the exponent operator here's
another helpful one it is the modulus operator it gives you the remainder of any
division so let's say
27:50
we are going to divide our class into two so modulus which is represented as a
percent sign two well 30 divides by two evenly so the remainder is zero if we had a
class of
28:03
31 students well there's one remainder one student students modulus 3 would divide
my class of 31 students into three we would still have one student remaining since
we're reassigning students we
28:19
would be replacing 31 students with the value of one if you're using the modulus
operator I would recommend creating a separate variable entit ly let extra students
equal our students modulus 3 we
28:35
have one extra student just one okay that is the modulus operator there is a
shortcut for writing these Expressions because it can be kind of tedious to write
the variable name
28:46
twice so let's set students back to 30 I will [Link] students we'll use what
is known as augmented assignment operators to increase students by a number if
we're reassigning it we can
29:01
say students plus equals 1 or some other number students is now 31 if I were to
change one to be2 it's now 32 and 33 let's do the same thing with subtraction
students minus equals 1 we now have 29
29:22
students multiplication students times equals 2 that would give us 60 students
students divided by equals 2 we have 15 students all right then exponents students
to the power of equals 2 900
29:51
students then modulus students modulus equals 2 we have no remaining students 30
divides by 2 evenly so another place where modulus could be helpful is if you're
determining if a number is even
30:08
or odd 30 is an even number divided by two the remainder is zero 31 is odd the
remainder is one there's also the increment and decrement operator there's a couple
different ways to add one to a
30:20
variable but you should be aware of all of them to increase a variable by only one
you can take the name of the variable then add Plus+ Plus+ is the increment
operator 30 incremented by 1
30:34
is 31 then there is the decrement operator which is minus minus 30 decremented by 1
is 29 all right then lastly we're going to cover operator precedence this is pretty
important
30:49
given a very complex equation such as this example in which order do you solve each
part of this equation so with operator precedence beginning with the left working
our way to the right you
31:01
would solve anything with parentheses then exponents multiplication and division
and modulo otherwise known as modulus then lastly addition and subtraction let's go
through the step by
31:13
step let's see what the result variable is I will [Link] result so the result
is 23 so if we were to walk through this step by step let's solve anything with
parentheses es starting from the left
31:29
and then working our way to the right there are no parentheses we can skip this
step next is exponents there is one exponent here so we would solve 4 to ^ of 2
which is
31:40
16 then we will solve multiplication and division and modulus that's addition we
skip that we have multiplication 2 * 3 is 6 there is no more multiplication
division or
31:55
modulus then lastly addition and subtraction 1 + 6 is 7 7 + 16 is our result of 23
all right I'll give you a few more exercises how about this equation the result is
going to be six
32:12
so there's no parenthesis no exponents we do have a modulus operator here so we
solve that first 12 modulus 5 gives us a remainder of two we have some division we
would solve
32:26
that next 8 divid 2 is four then addition and subtraction the result is six all
right here's a challenge round the result is going to be 0468 we solve anything
with parenthesis first 2 + 5 that is
32:44
7 then exponents 2 the^ of 7 I might need a calculator 2 * 2 3 4 5 6 7 that's 128
then we have 6 / 128 then we have 6 / 128 which is 046 875 and that is our result
all right
33:12
everybody so that is everything you need to know about arithmetic operators you
have operand which are values and variables and arithmetic expression and operators
there's also augmented
33:23
assignment operators which is a shortcut to writing these equations if you're
you're going to reassign a variable then you have increment and decrement operators
to increase a variable by one
33:32
or decrease it by one then with operator precedence if you're solving a complex
equation you solve each part of the equation following this order and well that is
everything you need to know
33:42
regarding arithmetic operators and JavaScript yeah what's going on people so uh
today I'm going to show you how we can accept some user input in JavaScript
generally there's two good ways of doing
33:56
this the easy way is to create a window prompt the professional way is to create an
html text box of some sort and you'll likely need a button to submit the user input
let's begin with the easy way
34:08
we'll create a window prompt the first thing we should do is declare all of the
variables we're going to use let's create a variable named username we'll declare
it but not yet assign it then
34:20
when we assign it we can set username equal to then to create a window prompt we
can type window. prompt parentheses then within the parentheses our window prompt
can contain some text
34:36
let's ask what's your username okay let's run this and see what happens what's your
username I will type in my username press okay we have this variable username it
will have a value but we should do
34:52
something with it let's [Link] our username let's try that again what's your
username I'll type in my username feel free to type in yours let's check our Dev
tools and here is my
35:14
username so that's the easy way to accept user input with this window prompt you
could assign declaration and assignment together if you want to you know that would
also work now we will
35:25
accept user input the Prof profal Way by creating an html text box we will navigate
to our HTML file okay let's create an H1 element that says welcome we'll need a
text box we'll use
35:42
a self-closing input tag I will set the ID of this text box to be my text I'll
create a label for this text box too because if we're a user we don't know what
we're supposed to to type in
35:58
here I will create a label the text within the label will be username then a submit
button button the text will be submit I'll put this on a new line I'll add a Break
36:19
Tag maybe two to make it look nice for the ID of the button I'll set the ID to be
my submit let's see if this works this is a little Advanced when we click on this
button we're going to
36:36
execute a function but we need to select this button we will access the document of
our web page get element by ID the ID that we're getting is the ID of the button my
36:52
submit So within quotes type the name of the ID follow this with DOT onclick equals
here we'll write everything we're going to do after clicking the button we need a
function function parenthesis
37:10
curly braces everything between this set of curly braces is everything we'll do
when we click on the button so first we need a username variable outside of the
function when we click on the button get
37:26
the text from this text box we will reassign our username then set this equal to
the text from the text box we'll use document. getet element by ID the ID that
we're getting this time is my
37:46
text we need the value of the text box so follow this with DOT value all right then
to test this let's console log the username all right let's type in our username
press submit then check Dev
38:07
tools yeah there it is okay let's replace [Link] we'll change the text content
of our H1 element I will give this H1 element a unique ID let's say my H1 we need
to select my H1 ele El
38:27
document. getet element by ID the ID was my H1 we are changing the text content
equal to let's use a template literal hello username all right let's try this again
38:47
type in your username press submit and that should change the H1 element hello
whatever your name is all right everybody so those are two different ways to accept
user input you can use a
39:00
window prompt or you can use an html text boox and that is how to accept user input
in JavaScript all right so uh yeah type conversion type conversion is the process
of changing the data type of a
39:15
value to another data type for example we can convert strings to numbers numbers to
booleans booleans to Strings numbers to strings booleans to numbers I think you get
the idea why might we want
39:26
to do this well when we accept user input the data type of that input is a string
if we need to use it for any sort of math we need to convert it to a number here's
an example let's say we
39:36
have variable age I will create a window prompt window. prompt we will ask a user
how old are you I'm going to add one to our age age plus equals 1 then [Link]
age
39:57
how old are you let's say I'm 25 press okay let's inspect our page go to console it
shows that age is 251 when we accept user input it's a string data type a series of
characters
40:11
by adding one we appended one to the end of our string we're not increasing our age
by one we're doing string conation we are going to convert our user input into a
number and this is how so after
40:24
accepting our user input and before making any changes to it let's reassign age
equal to and this is a function the number function it will convert another data
type such as a string or Boolean
40:37
into a number then we'll place our age variable within that function so now this
should work how old are you let's say I'm 25 press okay 26 so that's the reason you
may want to
40:51
type convert because different data types behave differently along with my age
variable I'm going to display the type of age what's the data type how old are you
25 press okay 26 and it shows
41:06
that the data type of age is number if we removed this type conversion and then run
this again it shows that our age is 251 and it's a string which is not exactly what
we would like that's a
41:21
reason why type conversion is important let me give you another example let's
create three variables let X let Y and let Z I'll show you what happens when we
convert different values
41:34
into different data types let's say x is the word Pizza same thing with Y and Z I
will typ Cast X as a number then we need to place X within the number function I
kind of want to
41:52
see what happens when we try and convert pizza into a number it's probably not
going to go well let's convert Y into a string then Z will be a Boolean let's
[Link] X as well as the type of
42:19
X let's do the same thing with y and z all right what's going to happen if you
attempt to convert alphabetical characters into a number that variable will be Nan
which means
42:38
not a number the data type is still number though as you can see the word Pizza is
already a string so converting it into a string really doesn't do anything that's
why for this line the
42:49
value is still pizza and the data type is still a string if you convert a string
into a Boolean booleans again are either true or false converting the word pizza
into a Boolean returns true and
43:02
the data type is Boolean so basically as long as there's some value here and you
convert it into a Boolean it will always be true let's replace pizza with zero what
will
43:15
happen we can convert zero into a number it doesn't contain any alphabetical
characters X contains zero it's a number Y is zero but it's treated as a string Z
contains true and it's a
43:31
Boolean what about empty strings just a set of quotes typ casting an empty string
as a number is still zero we have an empty string for y then with our Boolean it's
false why might you want to
43:46
typ cast a string as a Boolean that's one way in which you can check to see if user
input is empty like did somebody type something in if a user skipped user input
it's it's most likely going to be
43:57
an empty string then you can check to see like if this is false then the user
didn't type in anything and you can let them know what about a variable that's
declared but not assigned a
44:09
value converting an undefined variable to a number results in not a number our
string is undefined and our Boolean variable returns false so that's the basics of
type conversion it's the process of
44:22
changing the data type of a value to another it's pretty important when you accept
user input because when you accept user input it's a string data type at times you
may want to convert it
44:31
to a number if you need to include that number with any sort of arithmetic
expressions or a Boolean if you're checking to see if that user input was completed
we'll have more practice with
44:42
this in the future and well that is type conversion in JavaScript why hello so
today I need to explain const const short for constants are variables that can't be
changed
44:55
changed once you assign them in this example we're going to create a program to
calculate the circumference of a circle given a radius let's define our variables
first we have Pi we'll begin
45:06
with using let then I'll show you the benefit of using const so let pi equals I'll
use the first few digits of pi 3.14159 then we have let radius which we will assign
later we'll ask for user
45:23
input then let circumference I think I spelled that right I can never spell
circumference all right now we need to ask the user what the radius is I will just
use a window prompt radius equals window.
45:42
prompt enter the radius of a circle then once we have our radius when we accept
user input it's a string data type we need to convert our radius into a number by
using the number
46:02
function then once we have our radius we can calculate the circumference by setting
circumference equal to and here's the Formula 2 * pi * our radius that the user
enters in then once we
46:16
have our circumference let's [Link] our circumference let's see if this works
enter the radius of a circle I'll enter 10 press okay their circumference is 62.8
so why might you want to use a
46:36
const in this program you may accidentally or somebody else may maliciously change
the value of a variable so that the program doesn't behave as intended for example
somewhere
46:48
within my program I will set pi to be a new number pi equal 420.69 let's run this
program again enter the radius of a circle I'll enter 10 press okay and my
circumference is
47:04
8,413 I may not realize that this is the incorrect answer just for an extra
security measure I can turn any variables that shouldn't change to be a const a
constant replace let with const
47:20
and it is a good practice if you have any constants to make all of the letters in
the variable name uppercase so Pi is now Capital Pi hey this is bro from the future
there's one thing I needed to
47:31
clarify that I forgot to mention capitalizing your constants is usually only done
with primitive data types such as numbers in booleans reference data types such as
strings don't normally
47:42
followed this convention you'll see this in the next few upcoming videos Pi is a
constant and we're assigning a number that's why I'm making it all uppercase but if
this was a string normally we
47:51
wouldn't that is all let's try and change that variable again Pi = 420.69 so we
have an uncaught type error assignment to constant variable so JavaScript won't let
us reassign
48:09
constants once they are assigned once we can't make any changes to it once you
declare a constant you can't change the value and that's pretty helpful in a lot of
circumstances it's an extra security
48:20
measure what we'll do this time is within our web page we will accept some user
input via a text box we'll rewrite the same program let's create an H1 element I
will set the ID of the H1
48:34
element to be my H1 and the text will be enter the radius of a circle I'll create a
text box input I'll set the type equal to text the ID equal to my text I'll create
a label for this input text
49:06
box let's say radius I'll add a button the button will say submit the ID will be my
submit then I'll add to break right after the text box to make it look nice let's
get rid of
49:33
[Link] when we click on the submit button we will execute a function we need
to select the button let's take our document get element by ID the ID is my submit
follow this with DOT onclick
49:57
equals a function parentheses curly braces when we click on the button we'll
execute any code within the curly braces we can eliminate our window prompt we need
to get the value from the
50:11
text box again we can use document. getet element by ID but the ID is going to be
my text the text from the text box dot value get the value from the text box box
and we will assign that to
50:30
radius then we will typ cast our input as a number then we will calculate the
circumference but since Pi is a constant make sure that the letters are uppercase
uppercase
50:47
Pi once we have our circumference let's change an H3 element so let's add that as
well H3 the ID will be my H3 there will be no text content then again we will get
element by ID the ID will be my
51:10
H3 change the text content of this element to equal our circumference okay let's
try this the radius is 10 press submit and here is our circumference maybe this
will be in
51:29
centimet so let me change that I'll use string concatenation and just add plus CM
so 10 submit 62.83 CM if I attempt to change the value of pi maybe I'll do that
here pi equal 420.69
51:51
rerun the program 10 submit there doesn't appear to be a result so if we go to Dev
tools go to console we have that uncaught type error assignment to constant
variable so again
52:06
we can't change the value of a constant there are more graceful ways of handling
this we'll learn about that when we get to exception handling however this is what
we wanted we do not want to be able
52:17
to change the value of a constant all right everybody so those are constants it's
just a variable that can't be changed once you assign it a value and well those are
constants in
52:29
JavaScript hey what's going on everybody so in today's video we're going to create
a counter program using JavaScript HTML and CSS so sit back relax and enjoy the
show all right let's
52:42
begin everybody so what we're going to do is start with our [Link] file We'll
add any necessary elements then we will style those elements with our CSS file then
lastly we will add
52:55
functionality via JavaScript so let's begin with our HTML file within the body of
our document I will create a label to store the count so I will create a label with
an
53:12
ID of count label the text will be zero it's a little small but that's okay we'll
increase the font size with CSS I'll add a break afterward with the Break Tag we'll
need three
53:28
buttons decrease reset and increase so we have button one let's copy this button
paste it two additional times the ID for the first button will be decrease btn4
button the text will be decrease
53:58
then for the second button the ID will be reset button the text will be reset then
increase ID increase button the text will be increase what I'm also going to do is
place our buttons within a div
54:23
section let's let's cut our buttons then place the buttons within the div I will
give the div a unique ID of button container we'll Center align our button
container so it's in the middle of the
54:42
window okay that is everything we need with our HTML file let's move to our CSS
file let's style the count label it's a little small right now I will select the ID
count label I will display the
55:03
label as a block level element I will text align Center so it's in the center of
our screen let's increase the font size I tend to like to use the EM unit of
measurement the text will be 10 times
55:23
the size then let's change the font family pick a font of your choosing for this
example I'll use helvetica let's Center the button container that should surround
all three buttons as you can see
55:46
here the ID was Button container text align Center okay the buttons should be in
the middle one thing I forgot to do uh let's actually add a class to our buttons
too class equals buttons
56:16
there all right we will select the buttons class I'll add some padding padding 10
pixels and 20 pixels let's increase the font size font size 1.5 em that translates
to
56:39
150% let's pick a font color I'll just pick white then a background color for the
buttons background- color I'll use hsl values how's that not feeling it that's
pretty
57:06
good let's round the corners with border radius five pixels I'll change the cursor
into a pointer when we hover over a button cursor pointer then we'll add a
transition animation transition
57:37
background-color after 0.25 seconds then we'll apply the hover sudo class when we
hover over one of the buttons take our buttons class use the hover PSE sudo class
we will change the back ground
57:55
color after a quarter of a second then change the background color to something
slightly darker yeah that looks good there should be a delay when you hover over
one of the
58:13
buttons our HTML file is done same with our CSS now we need to add functionality
because well these buttons don't do anything I will individually assign all of
these buttons so that each is stored
58:26
within a constant so const decrease button equals then we need to select each
button by accessing our document. getet element by ID what's the id we're selecting
we will begin with our decrease
58:50
button all right then we need our reset button reset button the ID is reset button
then increase button increase button the ID is increase button we need our count
label okay then we will set
59:19
const count label equals then we need to get the of our count label so document.
getet element by ID count label then we will use let count equal zero we'll be
reassigning count we'll be
59:45
incrementing and decrementing count with our HTML elements we do not plan on
reassigning them so we can set them as constants now we need a few functions three
functions one for each of these buttons
59:58
decrease reset increase let's begin with increase so we are taking our increase
button that we assigned with the onclick attribute of this button set this equal to
a
60:13
function what's it going to do when we want to increase this value of our count
label let's increment count by one count Plus+ then we will set the text content of
our label count
60:29
label. text content equals whatever the count currently is let's see if this works
it looks like I misspelled on click all right let's see if this works yep every
time we press the button
60:47
our counter label increases by one okay let's work on decrease really we can just
copy this function paste it let's change increase to decrease count minus minus
save
61:06
everything and we should be able to increase and decrease then the reset button
let's copy one of these functions change decrease button to reset button when we
want to reset we
61:22
will set count back to zero then update our count label with the current count
which should be zero we can increase we can decrease and we can reset then increase
and decrease again
61:37
all right everybody so that is a counter program with JavaScript HTML and CSS hey
what's going on everybody so today I'm going to explain math math is a built-in
JavaScript object that
61:53
provides a collection of math related properties and methods for example if you
ever need the value of pi you would type math with a capital m.p then let's
[Link] this [Link]
62:11
[Link] Pi is 3.14 and the rest of the digits if you need e e is known as ul's
number it's used for the base of natural logarithms we won't really using e in the
series but if you ever need it it's
62:27
there math does give you access to a lot of useful math related methods let's
create a few variables let X = 3.21 let y equal to and let Z will be undefined if
you need to round a number
62:46
let's say Z equals you can type [Link] method Place whatever value or Vari
variable you would like to round within the round method let's round X store the
result within Z then display z
63:04
[Link] z so 3.21 rounded is three even there's also floor floor will always
round down let's change 3.21 to 3.99 let's copy this line paste it change round to
floor
63:25
floor always rounds down so 3.99 rounded down is again three to always round up you
can use seal as in sealing the opposite of floor c l let's change 3.99 to 3.21 3.21
rounded up is four then there's
63:53
truncate trunk short for truncate will eliminate any decimal portion 3.21 truncated
is three another way to raise a base to a given power is to use the pow method
64:08
P let's raise 3 to the power of 2 so x to the power of Y which would be 9 y to the
power of X would be 8 there's a square root function sqrt let's find the square
root of how
64:31
about 81 the square root of 81 is 9 if you ever need to find the natural logarithm
of a number you can use the log function [Link] let's set X to be 10 the natural
logarithm of 10 is
64:47
2.3 if you need to do anything with trigonometry there's s cosine and tangent
functions let's begin with sign s n within this function you will place radians
I'll set X to be 45 so Z is going to be
65:05
0.85 so that's s let's do cosine which is cosos 0.52 then tangent T and that is
1.61 let's change X to be 3.21 again to find the absolute value of a number you can
use the absolute value function
65:35
[Link] it's basically going to give you the same number but it's going to be
positive the absolute value of - 3.21 is 3.21 basically we're eliminating the
negative
65:49
sign to find the sign of a number you can use the sign function s i g n so the sign
of - 3.21 is1 If This Were a positive number it would be one if it's zero then the
sign is zero here's a
66:08
pretty helpful method we can find the maximum or minimum value from a set of values
or variables let's set Z to be one y will stay as two and X will be three I will
create a new variable named
66:25
Max it will store the maximum value from these three variables math. Max comma
separate each of the variables x y z then display the maximum within our
[Link] method the maximum value
66:43
from these three variables is three then there's Min for the minimum let Min do min
so the minimum of these three variables is one all right everybody so that's math
it's a built-in JavaScript
67:02
object that provides a collection of properties which was pi and d and methods such
as round truncate power methods related to trigonometry and Max and Min methods
they're pretty helpful
67:17
if you ever need them and well that is what math is in JavaScript hey hey what's
going on everybody so in today's video we're going to create a random number
generator but first I need to explain
67:29
how to create a random number in JavaScript let's store our random number within a
variable which we will name random num to create a random number in JavaScript we
can use the random method
67:42
of math math. random method this will generate a random number between zero and one
uh but it looks like we forgot to Output our random number so let's do do that with
67:55
[Link] [Link] random num this will generate a random number between zero
and one it will give us a number with a long decimal portion most likely let's say
we would like to roll a
68:07
six-sided dice I need a random number between 1 and six not including the decimal
portion so the first step is that we will multiply math. random * 6 what this will
do is give us a random
68:21
number between 0 and 6 exclusive now I don't want the decimal portion I would like
a whole integer we'll enclose this equation with the floor method of math math.
floor then we will enclose our
68:37
equation so now we have oops it looks like I misspelled math it should be Capital
there so far a random number is going to be between zero and five so there's zero
and there's
68:51
five but I need one through six well we can increase the minimum by adding plus one
or whatever you want the minimum to be so now that should give us a random number
between one and six there's
69:06
six and there's one for a random number between 1 and 100 I can set the maximum to
be 100 math. random * 100 + 1 so now the number is going to be between 1 and 100 if
you're looking for a random
69:22
number between a certain range let's say 50 and 100 well we're going to change our
equation just to make this easier to read I'm going to set two constants const Min
what's the minimum let's say
69:35
50 and the max const max will be 100 let's replace 100 with our maximum and one
with our minimum there's one additional change we need to make for example our
random number is
69:52
139 we're multiplying math. random times 100 our maximum then adding an additional
50 to it so one change we're going to make is that we will subtract our minimum
from our maximum then I will
70:07
surround this portion of our equation with the set of parentheses just to force
operator precedence now the random number should be between 50 and 100 so depending
on the range of numbers you're
70:17
looking for you can change the minimum and the maximum all right now with that out
of the way let's create our random number generator let's go to our HTML file I
will create a
70:30
button the ID will be my button the text on the button will be roll we will roll a
six-sided dice within our CSS stylesheet I will set the text of the body of our
document the font family I
70:47
will set to be verdana cuz I like that font two to Center align everything to make
this easy I will set text align Center all right we're getting somewhere let's work
on the button I will select
71:03
the ID of my button I will change the font size of the button to be three em
meaning 300% I'll add a little bit of padding within our button 5 pixels by 25
pixels and I will set the Border radius
71:21
to be 5 pixels just to smooth the corners we're also going to need a label so let's
go back to our HTML file I will add a label with an ID of my label within our CSS
stylesheet I will
71:41
select the ID of my label then change the font size to be 3 em so be sure to save
your CSS file save your HTML file then within our JavaScript file we will need to
get our button and the label
72:00
we'll store those within some constants const my button equals document. getet
element by ID the ID of the element we're getting is my button then we will need to
get my label my label the ID is my
72:27
label let's set a minimum const Min equals I'll set that to be one as if we're
rolling a six-sided dice const Max equals 6 then let random num we'll declare a
random number variable but not assign it
72:46
quite yet okay when we click on the button we'll execute a function we will take my
button with the unclick attribute I will set this equal to a function what's the
73:00
function going to do it's going to roll a random number random num equals math.
random times our maximum we'll enclose this equation with math. floor to round it
math. floor then add our
73:22
minimum then we will change the text content of my label to display it my label.
text content equals our random num when we click on the button it should roll a
random number uh what are
73:38
we missing not a number oh okay it looks like I made a mistake I forgot to add a
set of print this is after random there we go I'm going to put the number on a new
line so within our HTML
73:51
file I'm just going to add a Break Tag there we go let's save everything roll again
so I roll a 6 3 1 2 5 3 let's say we would like to roll three dice not just one
we'll make a few
74:06
changes I will replace my label with label one for the ID then I'm going to add a
break after okay let's copy our label paste it two times we'll need labels two and
74:21
three I'll also give the labels a class of my labels we can apply CSS styling to an
entire class to make it easy all right within our CSS stylesheet let's replace
74:35
the ID of my label with the class of my labels be sure to save all of your files
then within our Javascript file let's replace my label with label one the ID is
label one
74:54
copy this line of code then we need labels two and three label two label three
let's rename random num as random num one copy it paste it two times then we need
random number two random number
75:14
three within our function for our button change random num to be random num one
copy this line paste it two times then we need random number two random number
three we'll change the text content of
75:29
my label to be label one equals random num one copy this line paste it two times
change one to B2 then for the third line change one to be three what we'll do now
is generate
75:44
three random numbers between 1 and six as if we're rolling three dice 232 361 225
all right everybody that's how to create a random number generator in JavaScript
Hey so uh what's going on
76:01
everybody today I got to explain if statements so in JavaScript if a condition of
our choosing is true we can execute some code if it's not true we can do something
else that's how to put
76:13
it simply for example let's say we have a user's age let age equals 25 to write an
if statement we can type if a set of parentheses then a set of curly braces within
the set of
76:28
parenthesis we can check a condition let's check to see if our age variable is
greater than or equal to 18 if this condition is true we can execute whatever code
is within the set of curly
76:42
braces if this condition is true let's [Link] a message you are old enough to
enter enter this site my age is 25 this condition is true we will execute this
76:59
code within the curly braces you are old enough to enter this site what if my age
was 13 well if this condition is true we don't do this we don't execute it we skip
over it if you would rather take a
77:16
different course of action if you would rather do something else you can write an
else clause if this is not true we will do whatever is within the else Clause let's
display a different message
77:31
you must be 18 plus to enter this site my age is 13 we will end up displaying you
must be 18 plus to enter this site basically speaking if this condition is true do
this else if not do this instead
77:53
it's kind of like a fork in the road which path are we going to take here's another
example let's say we have variable time time will be in hours in military time if
our time is 9 as in 9
78:09
a.m. let's write an if statement if time is less than 12 as in noon then
[Link] good morning else if it's after 12 that means it's at least the
afternoon [Link] good
78:40
afternoon the time is 9: as in 9:00 a.m. good morning what if our time was 14 like
1400 in military time well then we will display good afternoon conditions also work
very well with
78:56
Boolean variables let's create a Boolean variable is student if you're a student
say true if not then false now with a Boolean variable if you need to check the
value with an if
79:13
statement you can just place the Boolean variable within the condition itself the
condition either evaluates to be true or false if is student is true then
[Link] you are a student else
79:39
[Link] you are not a student is student equals false we will execute the else
Clause you are not a student If This Were true will execute the if Clause you are a
79:57
student you can even create nested if statements this time we will have two
variables let age equals some age and let has license as in a driver's license uh
that's how to spell
80:13
license has license will either be true or false so in the United States you need
to be at least 16 years old to have your Li we'll check that first if age is
greater than or equal to 16 let's
80:35
[Link] you are old enough to drive else [Link] you must be 6 plus to have
a license if I changed my age to 15 well I'm not old enough to have a license at
least in the United States it
81:08
might vary depending on your country let me know in the comments section how old
you have to be to get a driver's license I'm kind of curious you can use another if
statement within an if statement
81:18
after we check to see if somebody is old enough to have a license let's check to
see if they do have a license or not so I will add another if statement within our
if statement pay attention to the
81:32
indentation if has license since we're checking a Boolean variable that is going to
be the condition itself it evaluates to be true or false if has license [Link]
you have your
81:55
license else again pay attention to the indentation [Link] you do not have
your license yet my age is 15 I don't have a license this is the result you must be
16 plus to have your
82:17
license since this condition is false we skip over everything within curly Braes
entirely if I set my age to be 18 you are old enough to drive but I don't have a
license that's set to false
82:33
you do not have your license yet so we execute this condition so we enter anything
within this set of curly braces we display this message then check this if
statement my condition is false then
82:47
we will execute the else Clause if I set has license to be true well then you are
old enough to drive you have your license all right now I need to discuss else if
83:00
statements we will keep our age variable we have our if statement if age is greater
than or equal to 18 then we will [Link] you are old enough to enter this site
else
83:25
[Link] you must be 18 plus to enter this site my age is 18 I can enter this
site if my age was 12 I can't enter the site if there's any other conditions you
want to check before reaching your
83:42
else statement you can add an else if Clause then you can check another condition
let's check to see if somebody's age is less than zero your age can't be below zero
let's let the user know
83:59
[Link] your age can't be below zero I will set my age to be1 that's not
possible your age can't be below zero since this condition is false we skip over
this Clause then move on to the
84:19
next condition else if this condition is true execute this clause which it was then
it's not necessary to go to the else statement because we already executed one of
these Clauses you can
84:31
add as many else if statements as you would like let's add another else if let's
check to see if somebody is over 100 years old age is greater than or equal to 100
[Link] you are too old to enter
84:54
this site okay now pay attention to this it's really important my age will be 101
you are old enough to enter this site so why didn't we execute this Clause our age
is greater than or equal
85:11
to 100 the order of our Clauses does matter we start at the top and work our way
down and check all the conditions on the way down so with our first statement this
if state
85:23
age is greater than or equal to 18 101 is greater than or equal to 18 we will
execute this clause and skip over everything else that comes after even though this
response is more appropriate
85:36
for what we're looking for we still skip over it even though this is true because
we executed this one first so I would recommend that we move this Clause to the
beginning and change it to an if
85:47
statement first let's check to see if age is greater than or equal to 100 else if
age is greater than or equal to 18 so this should work as intended our age is 101
you are too old to enter
86:03
the site let's add another lsif Clause so to check to see if two values are equal
you got to use the comparison operator which is two equal signs let me give you a
demonstration else
86:17
if let's check to see if somebody's age is directly equal to zero so be sure you're
using two equal signs for a comparison not one one equal sign is the assignment
operator you want two equal
86:32
signs to see if two values are equal if somebody's age is exactly zero will display
a custom message you can't enter you were just born if somebody's age is zero
they're a
86:49
baby or an infant so let's set our our age to be zero you can't enter you were just
born this condition is false we skip this Clause this condition was true we execute
this clause and Skip everything
87:04
else that comes after using all this code let's work on an exercise we're going to
create a text box and a button so somebody can submit their age then depending on
what they enter we will
87:14
display a message so within our HTML file we'll create a few things let's create a
label the text on the label will be enter your age let's add a break after then a
text
87:31
box the label will be input the type will be text the ID will be my text I'll add a
break we'll create a submit button button type equals submit the ID will be my
submit the text on the button will be
88:00
submit I will also create a paragraph element the ID let's say is result element to
display a result all right that is everything we'll need so we can't see the
paragraph element quite
88:16
yet the text content of the result element will be one of these lines of text so
let's go back to our index file we'll create our elements I will set them to be
constants const my
88:33
text equals document. getet element by ID the ID is going to be my text and const
my submit that's the submit button document. getet element by ID the ID is going to
be my submit then lastly result
89:01
element const result element equals document. getet element by ID the ID is result
element let's scoot these if statements down when I click on the button we will
89:15
execute a function the button is named my submit my submit onclick attribute equals
a function when we click on the button what are we going to do let's take all of
our if else if and else
89:32
Clauses cut them then paste them within the function for the button when we click
on the button then we will check our age let's set this variable to be undefined
then we will get our age from
89:47
the text box age equals my text. value get the value from the text box and assign
it to age but remember when we get text from a text box it's a string data type we
need to typ cast it
90:03
to a number so we will set age to equal then use the number function to convert it
to a number then we can check our age we'll replace [Link] with the text
content of the result element
90:19
result element. text content equals our message I'll use a template literal so I'll
use back ticks let's copy our text paste it within the template literal then I will
90:35
delete the [Link] message so we'll just follow this pattern result element.
textcontent equals our message all right let's see if this works so we will type in
our age let's say I'm 25 press
91:16
submit and we have one problem let's see what's going on oops okay so I forgot to
add a set of parentheses after the function let's add that let's say I'm 25 press
submit you
91:29
are old enough to enter the site let's say I'm 12 you must be 18 plus to enter the
site what if I'm 101 you are too old to enter the site what if I'm zero you can't
enter you were just
91:43
born I'm negative 1 your age can't be below zero all right everybody so that is
everything you need to know to to get started working with if statements in
JavaScript hey uh so today I'm going to
91:58
explain the checked property in JavaScript the checked property determines the
checked state of an HTML checkbox or a radio button element by examining this
property we can determine
92:10
if a check boox is checked or a radio button is selected in this program if I were
to not select any of these buttons we have a different result within our HTML file
we will create an input
92:23
element the type is going to equal checkbox then for the ID I will set this equal
to my checkbox and here is our checkbox we should probably add a label so that
people know what this is for so the
92:45
label I will set the four attribute to be my checkbox what's the label going to say
let's say subscribe like a subscribe button utilizing the four attribute if the
four
93:00
attribute is the same as the ID when we click on the label it should still select
the checkbox all right let's add a break then we will create some radio buttons we
will again need an input
93:15
element the type this time will not be a checkbox it will be radio for the ID this
will be a Visa button I'm going to abbreviate button to BTN so pay attention to
93:32
that then I will create a label for this radio button we will set the four
attribute to be the same as the ID then the text will be Visa I'm going to add a
break okay let's copy this radio button
93:53
paste it two times we'll change the second visa to be MasterCard let's change the
ID first Master Card let's copy the ID paste it within the four attribute of the
second
94:10
label then change the text Master Card then the third ID will be PayPal button then
change the four attribute and the text PayPal so with radio buttons they should
94:29
all be within the same group currently they're not so I can select all of them if I
would like we should only be able to select one from any group we will group these
radio buttons by their name
94:40
attribute they should all have the same name the name let's say is card so let's
copy this attribute and paste it within the other input elements now we should only
be able to select one and that
94:54
appears to work lastly let's create a submit button we are creating a button the
text will be submit the type is submit and for the ID the ID will be my submit I
will create a paragraph element
95:15
will populate it with some text depending if subscribe is checked or not same thing
goes with our r buttons I will create two paragraphs after our button the ID on the
first
95:28
paragraph let's name sub result there will be no text content to begin with we'll
change the text content of our sub result paragraph with some text that states if
the user is subscribed or not
95:42
we'll create another paragraph for the radio buttons again there's going to be no
text content I'll set the idea this paragraph to be payment result now before we
move to our
95:54
JavaScript file I'm just going to edit the CSS on the button to make it a little
bit bigger so you guys can read it so the ID of that button was my submit we are
selecting an ID my submit
96:07
I will set the font size to be 1 em and that's probably good enough uh maybe I'll
add one more break after the Subscribe button and the PayPal radio button just so
that it's not as
96:26
cramped that's decent enough okay so be sure to save your CSS file your HTML file
then we are now within our Javascript file what we're going to do now is get these
elements by their ID
96:40
and store them within constants so they're easier to work with okay let's start
with our checkbox so the checkbox had an ID of my checkbox const my check checkbox
be sure
96:52
to pay attention to the capitalization feel free to change that if you would like
just be sure it's consistent with what you have currently with your HTML elements
we are accessing the document
97:03
of our web page get element by ID the ID is going to be my checkbox and that's it
so let's get the other elements we have my checkbox then we have our Visa button
97:22
const Visa button get element by ID Visa button then let's repeat this with our
MasterCard button again pay attention to the capitalization it's pretty important
then we have our PayPal
97:41
button we need our submit button next my submit then our paragraph elements sub
result then payment result all right here are all the constants that we'll need so
when we
98:06
click on the submit button we will execute a function so we are taking my submit
that's the name of the button dot on click I keep on spelling on lick on click equ
equal a function parentheses
98:23
curly braces when we click on the button what are we going to do we recently
learned about if statements we will first check the checked property of the
Subscribe button we'll place it within an if
98:36
statement so to create an if statement it's if parenthesis krly braces we are
examining my checkbox that's the Subscribe button dot checked property this will
evaluate to be true or false
98:52
if this is true we will execute this code if not we do something else if somebody
is subscribed let's change the text content of our sub resultes paragraph So sub
result we are accessing the
99:07
text content to equal maybe I'll use a template literal you are subscribed else the
user is not subscribed let's copy this line paste it you are not subscribed Let's
test
99:33
this if I click on the check boox then press the submit button it states that I am
subscribed you are subscribed if I were to refresh the page I don't click the
Subscribe button press submit you
99:46
are not subscribed all right we know that that works let's move on to the radio
button first we will check to see if somebody selected Visa we are accessing the
Visa radio button if Visa
100:01
button. checked if this is true we are changing the text of the payment result
paragraph payment result. text content equals you are paying with Visa let's see if
that works I'll select Visa
100:27
press submit you are paying with Visa all right let's add else if the next radio
button is Mastercard button if this is checked MasterCard button. checked then we
will change the text
100:46
content of the payment result to be you are paying with MasterCard you are paying
with MasterCard let's add another else if statement else if this time we are
examining the PayPal
101:05
button PayPal button. checked if this is true change the text content of the
payment result to be you are paying with PayPal you are paying with PayPal else if
none of these radio buttons are
101:25
checked we will change the text content of the payment result to be you must select
a payment type I will press submit without selecting a payment type you must select
a payment
101:45
type all right everybody so that is the checked property by examining the checked
property of of an HTML checkbox or a radio button element we can determine if those
elements are checked
101:56
or not and well that is the checked property in JavaScript hey y welcome back so
today I'm going to explain the trary operator in JavaScript you write a condition
then
102:10
add a little question mark kind of like you're asking a question how is this useful
well it's a shortcut to if and else statements it helps to assign a variable based
on a condition you write
102:22
a condition then use the tary operator as if you're asking a question you can write
some code if that condition is true what would you like to do then add a colon then
some code if that condition
102:35
is false here's an example let's say we have a user's age age equals 21 I would
like to check to see if somebody's age is greater than or equal to 18 age greater
than equal to 18 then
102:52
I will use the tary operator kind of like I'm asking a question is age greater than
or equal to 18 if this condition is true we can write some code I'll create a
string your and
103:07
adult then what if the condition is false I'll add a colon then I will execute this
code if the condition is false you're a minor this is helpful if you need to assign
a variable based on a
103:26
condition so I'll create a new variable let message equals then we write our
condition so if age is greater than or equal to 18 if that's true we will assign
this
103:41
string to this variable this message if it's false instead we will assign this one
it's an alternative to writing something like this so with programming we try not
to repeat
104:03
ourselves if we don't have to here we're assigning message to be either this string
or this one our trary operator is more condensed and I feel like it's easier to
read than that if else
104:17
statement it's a shortcut if you choose to use it I tend use it a lot then just to
test it let's [Link] our message just to be sure that it works fine
[Link] our
104:30
message our age is 21 you're an adult if my age was 12 you're a minor let's go over
a few more exercises this time we will have let time time will be between 1 and 24
like
104:46
a 24-hour clock I will set time to be 6 16 16 I think would be 400 p.m. we will
assign a greeting equals then we'll write a condition is time less than 12 then
tary operator like we're asking
105:06
a question if the time is less than 12 it's the morning good morning we'll use a
colon then write some code if it's false if it's not the morning it's at least the
afternoon good afternoon then let's
105:25
[Link] our greeting good afternoon because it's 400 p.m. what if it was 99
good morning all right I have a few more examples what if somebody's a student let
is student this will be true or
105:46
false if you're a student let message message equals now with the Boolean variable
you can just write the Boolean variable itself is student question mark are you
106:00
a student if so you are a student if not you are not a student then let's
[Link] our message we are a student you are a student let's set this to be
false you are not a
106:26
student it's very easy to read with Boolean variables you write the Boolean
variable then add a question mark here's a challenge round we will have a purchase
amount as if somebody's
106:39
buying something if somebody's purchase amount is over $100 they get a 10% discount
so let purchase amount equal let's say $125 or some other unit of currency of
you're choosing let
107:00
discount equals then the condition is we're checking if purchase amount is greater
than or equal to $100 $100 question mark is somebody's purchase amount greater than
$100 if so they will get a 10%
107:21
discount colon if that's false they get no discount zero so then let's display the
total [Link] I'll use a template literal your total is I need a dollar sign
for our unit of currency then I
107:42
need a placeholder so I need another dollar sign the purchase amount minus us the
purchase amount multiplied by let me scoot over a little the discount divided by
100 so the total since we get a
108:09
discount is $112.50 if our purchase amount was $99 well we don't get that discount
your total is 99 all right everybody so that's the trary operator it's a shortcut
to an if else
108:25
statement it helps to assign a variable based on a condition you write a condition
add a question mark as if you're asking a question do this code if that condition
is true else do this code
108:37
if that condition is false I'll be using the tary operator a lot just because I
feel like it's helpful and well that is the tary operator in JavaScript hey what's
going on everybody
108:50
so today I'm going to explain switches a switch can be an efficient replacement to
using many else if statements here's an example of a program I wrote without using
a switch we have a day day will
109:02
normally be the number 1 through 7 if day equals 1 will [Link] it is Monday
which you can see here if day was two well then it's Tuesday all the way up to 7
which is Sunday I do have an lse
109:16
statement that states our day variable is not a day for for example if I set day to
be I don't know like a string of pizza well then Pizza is not a day but it really
should be if you find yourself
109:29
using a lot of else if statements I would instead recommend creating a switch
here's how to create one we'll keep our day variable I'll set that to be one to
create a switch we will type
109:41
switch parentheses curly braces within the parenthesis of the switch we will place
a variable or a value what are we examining let's examine our day variable we
examine a value against
109:57
matching cases to create a case type case then a value or a condition we will see
if day equals 1 so day case one are these two values equal if they are then we can
do something we can execute some
110:13
code so add a colon then any code underneath this case will be executed if there's
a match between our value or variable day and this value so let's [Link] it is
110:31
Monday then be sure to add a break I'll demonstrate why you need break later so day
is one it is Monday let's add another case for case two in case day equals 2 so
let's copy and paste what we
110:49
have case 2 it is Tuesday let's change day to B2 it is Tuesday all right let's do
this all the way up to case seven all right we have cases 1 through 7 if I change
day to be seven well then it is
111:29
Sunday you can also add a default case in case there are no matches now what if we
set day to be Pizza which doesn't make sense well there are no matching cases once
we
111:43
review all of the cases and there's no matches we exit the switch you also have the
capability to add a default case in case there are no matches what's the default
behavior of
111:56
the switch if there's no matching cases let's [Link] I should probably use a
template literal for this if we're inserting a variable our day variable is not a
day so now we should
112:13
execute this default case Pizza is not a day all right now the reason that that we
have these break statements is to break out of the switch once we have a matching
case I'll demonstrate what
112:26
happens if we remove these all right let's set day to be two as in Tuesday it is
Tuesday it is Wednesday it is Thursday it is Friday it is Saturday it is Sunday two
is not a
112:41
day so the reason that we have these breaks is to break out of the switch if we
don't have them once we have a matching case we will execute the code found within
that space then Cascade
112:53
down and execute any code that follows after including code within different cases
so that's why you want these break statements after each case to break out of the
switch let's go over a more complex
113:06
example let's say we have a test score variable between 0 and 100 my score will be
92 92% I will also create a letter grade variable which we will declare but not
aign I'm
113:23
going to examine our test score so another way in which you can write a switch is
something like this I'm going to examine the value of true against matching cases
which
113:35
contain a condition so case then I'll write a condition is test score greater than
or equal to 90 as in 90% this condition will eval valuate to be true or false if
true is equal to
113:53
true we will do some code if this is false we skip over it if our test score is
greater than or equal to 90 let's assign our letter grade variable to equal an a
then be sure to
114:08
break then I'm going to test this with [Link] we will display our letter grade
we have an A let's do this for anything greater than 80 the user will receive a
114:22
B test score greater than or equal to 80 letter grade will equal B let's change our
test score to be 85 the user receives a b let's follow this pattern 70 will be a c
yep C 60 will be a d
114:55
60 is D then for the default case I will set letter grade to be F letter grade
equals F if I set my test score to be 33% so with the test score of 33 the letter
115:15
grade is f all right everybody so that's a switch if you find you're using a a lot
of lse if statements I would recommend using a switch instead it's not bad if you
have a few but if you
115:25
have many I would use a switch instead and well everybody those are switches in
JavaScript hey it's me again so today I'm going to explain string Methods in
JavaScript string Methods allow you to
115:39
manipulate and work with text also known as strings in this example I have a
username username equals a string of text why don't don't you go ahead and create a
username variable and set it
115:52
equal to either your username if you have one or your full name strings have
different built-in methods where we can manipulate this text one way or another
here's a few examples suppose I would
116:04
like to get the first character of the string I can use the Char at method type a
string or a variable containing a string then follow this with DOT by adding a DOT
we are accessing any
116:18
Properties or methods that the string has follow this with Char at then list an
index the first character is zero the second character would be one so get the
character at index zero that should be a
116:34
b however if I were to run this let's go to our Dev tools uh nothing appears to
happen because it's going to return a single character let's place that within
[Link] just so that we can see
116:47
it cut this code and and paste it within [Link] so the first character in my
string is B but depending on what you wrote it might be different for you the
character at index one would be R then
117:03
two is O so that is the Char at method the index of method will return the index of
the first occurrence of a character let's find the first occurrence of n o it will
return an
117:17
index and then again I have to [Link] whatever is returned so let's place this
method within [Link] what is the index of the first occurrence of an o that
would be
117:33
two 0 1 2 otherwise for the last index let's change the method to be last index of
which would be four 0 1 2 3 4 so the length property this isn't a method to get the
length of a string
117:54
type the string or a variable containing the string dot length this isn't a method
but it's very similar so the length of my username is seven characters 1 2 3 4
118:09
5 6 7 so that's how to get the length of a string now we are going to trim the
string maybe there's a bunch of white spaces after or before I will reassign
username equal to
118:25
let's take our username variable Dot and use the trim method to trim any Whit space
then I will [Link] my username there's my name and there's no wh space after
let's add some wh space before our
118:44
name yep and there's no white space to make my name I'll uppercase I can use the
two uppercase method now my string is all uppercase then there's two lowercase to
make all of the characters
119:01
lowercase there's repeat to repeat a string within the parenthesis of the method
how many times do you want to repeat the string if I were to type three we'll
repeat the string three
119:14
times to determine if a string starts with a given character we can use the starts
with method this will return a Boolean I will store that within a result variable
username dot starts with
119:32
method we will check to see if the string starts with an empty space then let's
[Link] the result that is false my username does not begin with the space but
what if it
119:47
did I'll add one then that returns true this could be useful within an if statement
if result if the string starts with a whit space let's [Link] your username
can't begin with an empty
120:12
space else let's [Link] the username my username has a whit space in the
beginning your username can't begin with Whit space if that were false then we will
display my username so that is the
120:32
starts with method there's also ends withth does my username end with the Whit
space it does not but what if it did your username can't end with an empty space
next is the includes method does
120:54
the string contain an empty space I'll split my username into two your first and
last name would work as well your username can't include an empty space currently
121:08
it does your username can't include an empty space if it didn't then we pass the
test we will display the username all right now this time we will create a phone
number let phone number
121:23
equals make up some phone number including dashes 2 3 4 5 6 7890 so this phone
number is a string even though it contains numbers because strings can contain
numbers but we treat them as
121:38
characters let's eliminate all the dashes in our phone number here's one way in
which we can do that let's reassign our phone number equals our phone number we
will use the replace all
121:53
method which character are we replacing let's replace any dashes comma then the
character to replace the dashes with or whatever you put for the first character we
will replace all dashes with no
122:08
characters then let's [Link] our phone number and that should eliminate all of
the dashes or otherwise you could replace it with a different character let's do a
forward slash so 1 2 3456 SL
122:26
7890 there's also the pad start method. pad start the first value within the pad
start method is a specified length how many characters should the string be I would
like the string to be 15
122:43
characters long then for the second value make sure to comma separate it we can pad
the start of the string with a given character let's say zero so the result is a
couple zeros than our phone
122:58
number pad this string with zeros until it's 15 characters long if I were to set
this to 20 then we would have more zeros there's more padding then there's pad end
pad the end of the string with this
123:15
character until the string is 15 characters long all right everybody so those are
string Methods they allow you to manipulate and work with text also known as
strings
123:26
we'll have more practice with these in the future and well those are a few useful
string Methods in JavaScript hey everybody so today I'm going to explain string
slicing in
123:39
JavaScript string slicing is the process of creating a substring from a portion of
another string this won't alter the original string just just to demonstrate let's
create a constant for our full
123:52
name go ahead and type in your full name or you can copy me I'm going to extract
the first name from my full name and create a new string out of it so I'll declare
this let first name equals Now
124:08
to create a substring we can follow this formula we take our string in this case
our full name dot then use the built-in slice method slice then we can list a
starting and
124:22
ending index where would we like to begin so the first character has an index of
zero we'll start at the beginning index0 comma where are we going to end 0 1 2 this
isn't
124:37
necessarily going to work and let me demonstrate so let's [Link] our first
name so my first name is BR so the ending index index is actually exclusive in my
full name we're
124:51
ending at o but we don't include it within our substring because the ending index
is exclusive I'll increase the ending index to three that should include one more
character which it does
125:03
now let's get the last name let last name equals again following this formula take
our original string use the built-in slice method State the beginning index 0 1 2 3
4 mine will be
125:20
four yours may be different depending on what your name is and the ending index
four 5 6 7 and remember that the last index is exclusive so I'm going to increase
that to be eight then we'll
125:34
display our last name [Link] last name and there's my last name so the reason
that I set the beginning index to be four and not three is because we'll include
that space within the result as
125:48
you can see here if you're going to be creating a substring from some position all
the way to the end you don't necessarily need an ending index I'm going to remove
the ending index and
125:59
this should work the same all right what if I need the first character in the
string let first Char meaning character equals take our string we will use the
slice method for the first character you
126:16
can use 0 comma 1 then let's display our first character and in my example mine is
B for the last character let last character full name do slice we can use a
negative index even
126:38
if you're using a negative index you'll begin at the end then by decreasing the
number you'll work your way towards the beginning so the last character in my name
is is e -2 would be
126:53
de 3 is o four is c for code negative indices work as well with these specific
numbers that I've listed they're only going to work if my name is exactly this what
if I were to change my first name
127:07
to be instead of bro broseph like Joseph then let's display our first name then our
last name first name bro last name f which is not correct to make this program more
127:27
Dynamic we can combine string slicing with the index of method we'll search the
string for the first instance of a space then depending on where that space is
we'll take the first part of our full
127:39
name and create a substring for the first name anything after the space will be our
last name so let's turn these lines into comments we don't need them anymore let
first name equals again take our
127:55
full name do slice we'll begin at the beginning index zero now where do we end
we're not going to count the number of characters this time we're going to
calculate it the
128:08
ending index will be take our full name dot then use the index of method where's
the first index of a space so that is the ending position wherever there's a space
then we'll display our first
128:29
name uh let me get rid of our last name there brosive now for the last name let
last name equals let's copy this line of code paste it the beginning index will be
f full name. index of
128:51
space you can list an ending index but we don't need to we would like to extract
every character that comes after this position so we don't need an ending index all
right let's see if this
129:02
works brosi space code we're including that space so to remedy this I can add plus
one find the first index of a space then start in the position after that's why
we're adding plus one then give me
129:18
every letter that comes after and that works just fine broi code all right let's go
over an exercise this time we will list an email const email equals why don't you
129:33
go ahead and type in your email I'll make one up for me bro 1@[Link] I'll
extract the first part of my email to be stored as a username let username equals
again we're going to take our
129:51
string email do use the slice method where are we going to begin we'll begin at
index zero that's the beginning of a string where will we end we'll end wherever
the at symbol is but we need to
130:04
search for it we'll use the built-in index of method of a string email. index of
what are we searching for we are searching for the at symbol and let's see if this
works [Link] our
130:25
username yep bro one then let's get the extension let extension equals we can copy
this line of code paste it make a few changes this substring will begin where the
last one ended then again
130:50
[Link] the extension at [Link] again like I said before I would like to
begin after this index I will add plus one my username is br1 my extension is
[Link] all right everybody so that's
131:09
string slicing it's the process of creating a substring from a portion of another
string when you create a substring you won't alter the original and I've proven
that by setting this
131:20
string to be a constant you can't change a constant to create a substring you take
the string use the built-in slice method then you can list starting or ending
indices and well everybody that
131:31
is string slicing in JavaScript what's up everybody so in today's video I got
explained the concept of method chaining in JavaScript method chaining is a
programming
131:44
technique it's where you call one method after another in one continuous line of
code I'll give you two examples of the same program one that uses no method
chaining and another that does then
131:55
we'll be able to see some of the benefits of method chaining what we'll do in the
first version of this program is create a variable for a username and I will ask
the user for some input using window.
132:07
prompt the text will be enter your username after typing in some username I would
like to to trim any white space around the username take the first character make
it uppercase take
132:23
all of the other characters make them all lowercase and then display the output so
this program will have a few steps let's reassign our username equal to username
use the trim method to remove
132:37
any wh space before or after the name then I will get the first character of my
username to capitalize it we'll create a variable of let letter equals our username
follow this with the
132:52
Char at method the character at index zero letter is going to be a variable it will
hold the first letter of my username to make my letter uppercase I will reassign it
letter equals letter
133:06
use the two uppercase method to make that letter uppercase now with the rest of the
characters I would like to make them lowercase anything besides the first character
133:18
I will create a separate variable for extra characters let's say extra chars short
for characters equals take our original username use the slice method we will slice
our username everything after the
133:33
first character if my name was bro code and I created a slice of everything but the
first character extra characters would be R code without the B so then let's take
our extra characters make
133:45
them all lowercase extra characters equals extra characters followed with the two
lowercase method then we will combine the first letter which is uppercase and the
extra
133:57
characters which are lowercase then store them within our username username equals
our letter plus the extra characters then we will display our username [Link]
our
134:13
username so this program does have a lot of steps we will run this program enter
your username I will enter a few whites spaces type in my name but I'll mix up the
134:29
capitalization press okay and there's my username the first letter is uppercase the
rest of the letters are lowercase so this program does work but it is a lot to
write now with method chaining we can
134:42
combine some of these steps together and avoid creating variables that we don't
need such as letter and extra characters so with method training what we'll do is
start to combine some of these
134:54
steps after getting our username we will take our username equals take our username
again use the trim method we're not going to end this method with a semicolon we're
going to end it with a
135:06
DOT to write another method after trimming the username get the character at index
zero and then why sto there let's method chain again make that letter uppercase
following the two
135:18
uppercase method so this will work it's kind of like in a video game how you can
have a combo well this is a three hit combo boom boom boom take our username trim
it get the first character and then
135:30
make an uppercase all in one line of code not only that let's use some string
concatenation we need to take the rest of the characters of my username make them
all lowercase then combine them
135:40
together again let's take our username use the trim method method chain the slice
method slice the string after the first character then method chain again use the
two lowercase method and that should
135:59
work [Link] my username we're using a lot less lines of code and I'll zoom out
just so you can see everything Ander your username I'll throw in some white spaces
then mix up the capitalization
136:20
and that has appeared to work so that's method chaining it's a programming
technique where you can call one method right after another in one continuous line
of code it's like a video game
136:31
combo so to say so in this case trim our username give me the first character and
then make it uppercase we did method chaining here here and then we combined the
results using string catenation
136:43
which is something separate entirely by using method chaining this help helps you
avoid creating named variables but if your method chain is too long it can become
difficult to read like here I am
136:54
kind of pushing the limits and well everybody that is Method chaining in JavaScript
hey yeah it's a me so today I'm going to explain logical operators there's three of
them and or not they're
137:11
used to combine or manipulate Boolean values Boolean values if you remember are
true true or false let's create a program const temp meaning temperature what I
would like to do is see if my
137:25
temperature Falls within a certain range this will be in Celsius let's say the
temperature is 20° C without using any logical operators let's write this if our
temp is greater than zero then we will
137:46
[Link] the weather is good else if the temperature is less than or equal to 30
30° C we will also output the weather is good else the weather is bad currently my
138:14
temperature is 20° C the weather is good what if I were to change this to something
ridiculous like 200° C well the weather is obviously not good Earth probably got
hit by an asteroid or
138:28
something or if I were to change my temperature to like 100° C well the weather
isn't good either I don't know maybe the sun disappeared so what I want to do is
output the weather is good only
138:43
if my temperature Falls between the range of zero and 30 so we're going to change
this program if our temperature is greater than zero and we'll check another
condition
138:58
and our temperature is greater than or equal to 30 then we can eliminate this elif
Clause now let's check the temperature our temperature is -100° C well the weather
is bad if our temperature was
139:12
200° C the weather is also bad in order for us to execute this if statement both
these conditions need to be true this one and this one to join two conditions you
use double and per and meaning and
139:29
if our temperature was 25 well that falls within our range the weather is good this
is true and this is true so we will execute this code if one of these was false we
don't execute it at all
139:45
we'll skip over it so that that is the and logical operator you can check more than
one condition you can check one thing and something else now there's or which is
double straight
140:00
bars with the or logical operator at least one of these conditions needs to be true
this has to be true or that has to be true if I were to run the same program well
then the weather is good
140:13
let's change the temperature to 250 the weather is good but it's not it shouldn't
be so let's rewrite this program if our temp is less than or equal to zero or the
140:28
temperature is greater than 30 then the weather is bad else the weather is good our
temperature is 250 the weather is bad netive -250 the weather is also bad so with
the orological operator we're
140:46
checking more than one condition is this true yes it is -250 is less than zero or
is this condition true this one is false but since at least one of these is true
141:00
we will execute this code then we will cover the not logical operator let's create
a new program const is sunny is it sunny outside this will be true or false we will
create an if
141:16
statement our condition will be is sunny is this true if it is we will [Link]
it is sunny else we will [Link] it is cloudy is sunny is set to true it is
sunny If This Were false then it is
141:44
cloudy using the not logical operator we can flip a Boolean from True to false or
false to true I will precede this Boolean with the not logical operator which is an
141:56
exclamation point now we're checking if it's not Sunny then we will console. log it
is cloudy else it is sunny is it not sunny outside it is cloudy let's change this
142:13
to be true it is sunny so basic basally the not logical operator it'll change true
to be false and false to be true all right everybody so that's a short topic today
logical operators they're
142:26
used to combine or manipulate Boolean values use and to check to see if at least
two conditions are true with or at least one condition needs to be true and with
not not we'll do the opposite and
142:38
well that is an introduction to logical operators and JavaScript so uh yeah it's me
again so today I'm going to explain the strict equality operator which is
represented
142:51
by three equal signs before we dive in let me make a few important distinctions a
single equal sign is the assignment operator you usually see it when you assign a
value to a variable the
143:02
comparison operator two equal signs is used to compare two values to see if they're
equal now the strict equality operator has a whopping three equal signs it not only
Compares if two values
143:13
are equal but if they have the same data type as well let me give you a
demonstration suppose we have a constant named Pi Pi equal 3.14 pi in my example
has a data type of
143:27
number I'll create an if statement we will check if Pi is equal to the string 3.14
if it is let's [Link] that is pi else we will [Link] that is not Pi is
the number 3.14 equal to the string
143:57
3.14 well according to JavaScript that is pi that's because we're using the
comparison operator we don't care about the data type we only care about the value
are the values equal now if I was
144:10
using the strict equality operator which is three equal signs well then JavaScript
tells me that this is not Pi because with the strict equality operator not only do
we compare
144:23
the values but we also compare the data types as well these values are both 3.14
but this one is a number data type and we're comparing it to a string so they don't
match technically if we were
144:36
strictly comparing the number 3.14 to the number 3.14 well then we have a match
that is pi one case where this is pretty helpful is when you accept user input
because user input tends to be a
144:50
string data type and then just as an extra measure you can use the strict equality
operator and then be sure that the value is a number data type there's also the
inequality operator it will
145:02
return true if two values are not equal so let's take shut up this time we will
examine if Pi does not equal the string 3.14 if these are not equal this condition
will evaluate to be true so
145:22
this is not Pi else this is pi is the number 3.14 not equal to the string 3.14 well
that is Pi still using the inequality operator these values are still the same the
inequality operator
145:40
will return false then there's the strict inequality operator an exclamation point
and two equal signs are the values or the data type different so in this example
that is not
145:55
Pi they have the same values but the data type is different if I turned my variable
Pi into a string well that is pi now the string 3.14 stored within Pi does equal
the
146:11
string 3.14 so this condition turns out to be false so we execute the L state it
might take you a little bit of time to get used to this and that's okay it is a
little odd but just in case you see
146:24
these in the future you'll at least be familiar with them from now on we will try
and use the strict equality operator if we can and well everybody that is the
strict equality operator and I guess
146:34
well the inequality operator and strict inequality operator in JavaScript hey
what's going on everybody so today I'm going to explain while Loops in JavaScript a
while loop Loop
146:47
will repeat some code while some condition is true take this program for example we
have a variable username if our username is equal to an empty string then we will
[Link] you didn't
147:01
enter your name else [Link] hello username if I run this program then check
within our console well we didn't enter our username now if I were to change this
program to a while loop
147:15
while our usern name is equal to an empty string repeat this line of code Forever
Until this condition is no longer true then when we escape the while loop we can
print the message
147:27
hello username this is what happens when I run the program we just print this line
of code forever and my computer is probably going to crash I can't seem to stop
help okay I think it broke a while
147:46
loop will continue some code infinitely while this condition is true if it no
longer is true then we can escape the while loop if I were to set my username to be
something other than an empty
148:00
string well we never actually enter the while loop we skip over it entirely and go
straight to [Link] at the end so what we do first is check the condition
148:11
if it's true then we get sucked into the wild Loop and execute this forever you
usually want some sort of way to exit the while loop while you're in it otherwise
you get what is known as an
148:22
infinite Loop so let's rewrite this program let username equal an empty string
while our username is strictly equal to an empty string let's ask the user to enter
in
148:35
their name username equals I'll use a window prompt enter your name name okay let's
try this again enter your name I'll press okay we can't seem to close this window
until we type in
148:55
something you can see I'm clicking on okay nothing's happening I will type in my
name press okay then our console displays hello whatever your name is so that's a
benefit of a wild Loop repeat
149:09
some code until this condition is no longer true since we populated our username
our username was not not equal to an empty string we filled username with some
characters what if I instead press
149:22
cancel hello null null means no value username will equal null if I press the
cancel button let's append to this condition or username is strictly equal to null
now I shouldn't be able to continue
149:40
until I type in something and I can escape if I hit canc cancel while one of these
conditions is true execute this code forever let's type in our name again and now
we can escape the while
149:58
loop there's also another variation of a while loop it's known as a do while loop
how that works is that you can move while and the condition to the end so we'll
place it here then preedee
150:12
the set of curly braces with do so we will always execute this code at least once
then check the condition at the end using a do while loop I don't necessarily need
to set the username I
150:24
can set it to be undefined if I set my username to be undefined then use a standard
while loop we never execute the while loop our username equals undefined it doesn't
150:41
equal an empty string or the value null so we skip over the while loop entirely so
a do while loop is another variation of a while loop do the code first then check
the condition at the end so
150:54
there's a few different ways you can write the same program all right let's go over
another example we'll create three variables let logged in logged in will be false
to begin
151:08
with to log in we have to type in a matching username I will declare a username but
not a sign it and a password so let's create a while loop how do we escape the
while loop let's
151:25
say while not I'll use the not logical operator while not loged in once we're
logged in once this is true we escape the while loop we will ask a user for their
username username equals window. prompt
151:47
enter your username let's ask for a password as well password equals enter your
password I'll add an if statement within the wild Loop we'll check to see if our
username is strictly equal to then make
152:11
up some username my user name and if our password is strictly equal to some
password like my password if our username and password both match these values then
we can log in so logged in will equal
152:40
true then I'll [Link] a confirmation message you are logged in else let's
[Link] another message invalid credentials please try again all right let's
see if this works enter your
153:09
username I am just going to press okay enter your password I'll type in something
legitimate so I'll type in my password uh invalid credentials please try again
that's because I didn't type in a
153:23
username I'll type in my username be sure it matches my username my password and we
are now logged in so since we set logged in to be true when we go back to the
beginning of our
153:40
while loop this condition is no longer true while not logged in but since we're
logged in we escape the while loop now another variation of this is the do while
loop let's cut the condition along
153:54
with while add it to the end then add do to the beginning so we'll check to see if
we're logged in at the end it pretty much does the same thing but with one
exception in
154:07
this program how this is different is that I can set logged in to be true to begin
with we still receive that prompt I'll type in my username type in my password we
are currently logged in so
154:18
we do not continue the wild Loop if we used a standard while loop and We Begin by
being logged in well we never ask for any of this we never enter the while loop
while not
154:31
logged in do all of this but since we are logged in we don't do any of it all right
everybody so that's while Loops repeat some code while some condition is true while
some condition remains true
154:44
execute this code forever and until it's no longer true and well everybody that's
while Loops in JavaScript all right what's going on people so today I'm going to
discuss for
154:56
Loops a for Loop will repeat some code a limited amount of times with the while
loop a y Loop can repeat some code infinitely with the for Loop we can do something
a certain or limited amount of
155:08
times here's an example let's say we would like to display the word hello three
times with the for Loop we can write something like this now to create a for Loop
type four parenthesis curly
155:18
braces within the set of parenthesis we have up to three statements the first is
that we can create a temporary counter much like we're assigning a variable let's
create a counter named I let I I
155:31
is a common naming convention for counters within a loop I meaning index so let I
equal what number would we like to start at let's start at zero then semicolon this
is the first statement
155:45
we'll create a counter to keep track of the number of iterations the next statement
is the condition in which we continue the for Loop we will continue this for loop
as long as I is less than
155:56
or equal to two that's if we're going to execute this for loop three times 0 1 2
that would be a total of three then the third statement we can increment or
decrement our counter I so let's
156:09
increment our counter by one during each iteration by typing i++ and that's a for
Loop I is set to zero will continue as long as I is less than or equal to two then
during each
156:21
iteration we will increment I by 1 that means we will execute this for loop three
times what are we going to do when we execute each iteration let's [Link]
hello so this should display the word
156:37
hello three times yep hello three now if I were to instead [Link] I we can see
what I is so during the first iteration I our counter is zero then one then two if
I
156:53
wanted to count up to 10 I could change my condition to be this I is less than 10
so we begin at zero then we count up to 9 so if I need 1 through 10 I'll set I in
the beginning to be 1 then continue
157:10
as long as I is less than or equal to 10 there so we have numbers 1 through 10
using a for Loop we can even increment by a different number instead of
incrementing our counter by one let's
157:23
increment by two so I + = 2 so then we should count up by twos 1 3 5 7 9 if I want
to start at two I can change our counter to start at two count from 2 to 10 but
increment by two 2 4 6 8 10 if we
157:44
would like to count down let's start at 10 then count down to zero let I equal 10
will continue as long as I is greater than zero then iusus to decrement hey for fun
after we escape
158:01
the for Loop let's [Link] happy New Year it's as if we're counting down to
midnight on New Year's Eve 10 9 8 7 6 5 4 3 2 1 Happy New Year or we could count
down by two i - = 2 10
158:22
8642 or three or whatever number 10741 happy New Year or whatever number you want
now I'm going to cover continue and break this time we will count to 20 we need a
for Loop we'll create a
158:38
counter let I equal I'll set I to be 1 that's our first statement our condition is
is we'll continue as long as I is less than or equal to 20 then increment I by One
during each
158:54
iteration so to test this let's [Link] I so we have the numbers 1 through 20
so with continue we can skip an iteration I'm going to write an if statement if I
is equal to now there is
159:17
a Superstition that 13 is an unlucky number let's say if I is equal to 13 we will
skip that iteration I know it's a weird example so if I is equal to 13 let's
continue continue will skip
159:32
this iteration of the loop else we will [Link] whatever I is so now when I run
this program when I run this program we skip over 13 we jump from from 12 to 14 so
if you ever need
159:48
to skip an iteration you can use the continue keyword now there's break break will
break out of the loop entirely we've seen this keyword in switches to break out of
the switch if I equals 13 then
160:02
just exit the for Loop entirely so in this example we count up to 12 but since I
now equals 13 we break out of the loop entirely we don't continue the rest of the
iterations all right everybody so
160:16
those are four Loops you can repeat some code a limited amount of times there's up
to three statements we can write we can create a temporary variable that serves as
a counter a condition in which
160:28
we should continue then we can increment or decrement our counter and those are
four Loops in JavaScript hey what's going on everybody in this video we're going to
create a
160:40
number guessing game using JavaScript so why don't you go ahead and sit back relax
and and enjoy the show all right let's get started everybody so the first thing
that we're going to need is to set
160:50
the minimum and the maximum numbers in our number guessing game so we'll create two
constants const minum for the minimum I will set my minimum to be one but feel free
to pick a different number
161:03
if you would like then a maximum const Max num I will set my maximum to be 100 so
what we got to do is generate a random number between our minimum and our maximum
inclusively so let's create another
161:18
constant const answer then we'll generate a random number between 1 and 100 our
minimum and our maximum to do that we can type math. random the random method of
math will
161:32
generate a random number between zero and 1 we will multiply this by within a set
of parentheses the range between our maximum minus our minimum then add plus one
let's see what we have so far just to
161:48
test everything I'm going to [Link] our answer okay let's inspect go to
console here's my answer currently 56 point and then a bunch of decimal places
after I
162:03
will round our answer by enclosing this equation with math. floor to round down
okay let's see what we get again 39 89 20 7 71 27 177 46 okay that seems like it's
working what if we have a
162:21
higher minimum let's say between 50 and 100 well I have 7 22 43 numbers that are
below our minimum so if we have a minimum besides one I will add to the end of this
equation our minimum
162:40
again okay let's see if that works so if I need a random number between 50 and 100
this equation should work 97 80 79 52 all right that seems like it's working so
this is the equation you'll
162:54
need to generate a random number between your minimum that you set and your maximum
but let's change our minimum back to one and make sure our maximum is 100 all right
let's move on to step two
163:06
we'll create a variable named attempts to keep track of the attempts it takes a
user I will set attempts to be zero and let guess I will declare this variable but
not
163:18
assign it quite yet we'll take care of that later I will also create a Boolean
variable named running and I will set this to be true the reason that we have the
Boolean
163:28
variable running is so that we can exit the game when it's over we'll set running
to equal false so to keep the game running we'll use a while loop while running
equals true now if this is
163:42
a Boolean variable you don't necessarily need this portion equals true you can just
set this to be while running while this Boolean is true keep the game going then
when we want to exit
163:55
the game we will set running to equal false so that will be at the end now we need
to accept some user input I'll do this with the window prompt we will set our guest
to equal window.
164:13
prompt I'll use a template literal guess a number between I'll add a placeholder
our minimum through add another placeholder our maximum all right to test this I'm
going to [Link] the type of
164:40
guess as well as what guess is there's something I need to show you guess a number
between one and 100 I'll guess something right in the middle 50 let's inspect go to
console so my user input
164:52
of 50 is a string data type we'll need to convert it to a number for comparisons so
after we get our guess let's reassign it and typ cast it as a number type let's try
that again guess a number
165:08
between 1 and 100 I'll type 50 okay inspect console we have our guess of 50 and
it's a number data type what if you were to type in something that wasn't a number
like a string of characters such as
165:23
Pizza here's the result if you type cast some characters that are non-numeric you
know the number Z through n you'll end up with not a number Pizza can't be
converted to a number
165:36
unfortunately I will delete this line of code we no longer need it I'll add an if
statement there's a function to check to see if something is not a number is not a
number
165:48
function if our guess is not a number if this evaluates to be true let's add an
alert window. alert please enter a valid number guess a number between 1 and 100
what if I type
166:08
pizza please enter a valid number now what if somebody types in a guess that's
below our minimum or above our maximum I'll add an else if statement else if our
guess is below our
166:23
minimum or our guess is above our maximum will window. alert please enter a valid
number again guess a number between 1 and 100 what if I type in 150 that's above
our maximum please enter a
166:42
valid number please enter a number between 1 in 100 netive -1 please enter a valid
number if the user's guess is a number and it's between our range between the
minimum and the
166:57
maximum we'll execute an L statement if they reach the L statement that means they
have a valid number we'll increase our attempts variable by one attempts Plus+ to
increment it if the
167:13
guess if the yes is less than the answer then will window. alert too low try again
else if the guess is greater than the answer will window. alert to high try again
if the guess
167:43
isn't lower than the answer and the guess isn't higher than the answer that means
the guess must equal the answer within an else statement we'll congratulate the
user they have the right answer
167:56
window. alert correct the answer was and I should probably use a template literal
for this if we're inserting variables the answer we'll let the user know how many
attempts it took it took
168:22
you the variable attempts then the word attempts at the end of our lse statement
we'll move running equals false to within the lse statement at the end to exit the
game we no longer want to play
168:39
once we have the correct answer all right and this should work let's try it guess
or not number between 1 and 100 I'll guess something right in the middle 50 too low
try again okay so the answer
168:51
is between 50 and 100 75 too high so it's between 50 and 75 62 two low 68 two high
so it's between 62 and 68 65 too high 6 three to low 64 yeah correct the answer was
64 it
169:21
took you seven attempts and we can exit all right everybody so that is a number
guessing game in JavaScript hey welcome back so today I got to explain functions in
JavaScript a
169:35
function is a section of reusable code you declare that code once and you can use
it whenever you want all you have to do is call the function to execute that code
here's an example we'll create a
169:47
function to sing Happy Birthday whenever we call this function it's going to sing
Happy Birthday so to declare a function you type function a unique function name
169:57
let's name our function happy birthday because it's well the happy birthday
function then you add a set of parentheses then you add a set of curly braces any
code we write between this
170:09
set of curly braces we can reuse whenever we want so what do we want to do exactly
with this function I'll create the lyrics to my own happy birthday song [Link]
170:24
happy birthday to you let's repeat that again happy birthday dear you happy
birthday to you trust me I'm going somewhere with this so we have a function when
we run the program it currently doesn't do
170:42
anything to execute this code within the function function we have to call the
function by its name happy birthday then add a set of parenthesis so now we should
execute this code yep happy
170:54
birthday to you happy birthday to you happy birthday dear you happy birthday to you
so to call a function you type the function name then you add a set of parentheses
I like to think of the
171:04
parentheses as two telephones talking to each other that's how I remember it so if
I were to call this function again what do you think's going to happen well we're
going to execute this function
171:16
twice three times we'll execute it three times as many times as I want in fact
that's what a function is it's a section of reusable code reuse it whenever you
want you just have to call it you can
171:29
send a function some values or variables let's change our happy birthday function I
will turn this line into a template literal let's replace you with the placeholder
then we'll add a
171:42
username I'll add one one more line we'll use a template literal you are insert a
placeholder age years old so when I run this program we have an uncaught reference
error username is
172:04
not defined at happy birthday so our happy birthday function doesn't know what our
username is or the age so we can send some information to the function when we call
it so within the
172:17
set of parentheses what would we like to send this function let's send our name so
whatever values you place within the function be sure to comma separate them so why
don't you go ahead and send
172:32
the happy birthday function a name and an age but there's one step missing these
are known as arguments they're data that you send a function but you need a
matching set of parameters within
172:46
the parentheses of the Declaration in a way we can Define some temporary variables
and they're all comma separated we will Define a username parameter as well as age
now this
172:58
function should work properly happy birthday dear bro code you are 25 years old so
these are parameters and what you send to the function are arguments let's call the
function but send different
173:13
information happy birthday uh how about SpongeBob SpongeBob will be I don't know
how old he is according to SpongeBob lore but let's say he's 30 years old happy
birthday dear SpongeBob you are 30
173:28
years old how about Patrick this time it's his birthday everybody gets a birthday
Patrick will be 37 happy birthday dear Patrick you are 37 years old so that's a
benefit of
173:46
passing arguments to a function when the function receives this data it can do
something with it now the order of the parameters does matter if I were to switch
age and username here's what
174:00
happens happy birthday dear 37 you are Patrick years old with the arguments that
you're passing to your function you'll want to be sure that the parameters match up
all right now I'm
174:12
going to cover the return keyword we'll create a few other function examples we'll
create a function to add two numbers function add then we'll need two arguments
which
174:24
we will name X and Y so when we invoke this function I would like to add X and Y
together I'll create a temporary variable named result just to store the result
result = x +
174:40
y so I'm going to add two numbers together let's add two and three together and
let's see what happens well nothing appears to happen well we can send some data
back to the
174:54
place in which we call a function but we need to use this return keyword let's
return the result so 2 + 3 should be 5 after this function resolves think of this
function becoming the value five so
175:10
we'll probably want to do something with that value I'll store that with within a
variable let answer equal add 2 and three then let's [Link] the answer which
should be five when you
175:29
return something from a function after you resolve the function think of it as
becoming whatever is returned in this case it's our result or otherwise I can place
this function within
175:42
[Link] if we don't plan to to store it at all so add two and three then
display the result which is five there is a shortcut too you don't necessarily need
to declare a variable within this
175:56
function we could shorten this to return x + y that is also valid so that should
return five okay let's create a subtract function function subtract will return x -
y but we need a matching set of
176:20
parameters because I forgot that okay let's see what happens when we subtract 3
from 2 that'll give us 1 Let's multiply function multiply we'll multiply X and Y
176:37
together return x * y we will multiply 2 * 3 which is 6 divide we need parameters X
and Y then return x / y then we will invoke the divide function pass into two and
three and the
177:01
result is 0.666 repeating let's go over a more complex example we'll create a
function to determine if a number is even or odd here's the function function is
even we have one parameter a number so
177:22
when we invoke the function we'll have to pass in a number so when we receive a
number how do we check to see if this number is even here's one solution we'll use
an if statement if our
177:37
number modulus 2 modulus gives you the remainder of any Division if this number
divides by by two evenly if this is equal to zero and yes I'm using the strict
equality operator I'm trying to
177:51
use that more often if our number is divisible by two then let's return the Boolean
value true else will return false okay let's [Link] let's check to see if a
178:09
number is even let's start with 10 is 10 even that is true how about 11 that is
false 12 12 is even so that's kind of cool if you would like a shortcut for this
you can use the trary operator that
178:26
would look something like this we are going to return then a condition what are we
checking is our number modulus 2 strictly equal to zero question mark so that is
the tary operator the question mark
178:44
if it is true then we will return a Boolean value of true colon false if it's false
is 12 even that is true is 13 Even no it's not it's odd how about 14 that is true
all right last example I
179:03
think we're probably getting the hang of this now we'll create a function to see if
an email is valid function is valid email what kind of information are we going to
179:16
send we'll set that up as a parameter we will need an email we'll invoke the is
valid email function and pass in an email why don't you type in your email I'll
just make one up bro
179:31
[Link] so when we invoke this function this string of text will become our email
we'll check to see if our email contains the at character we'll use an if statement
if email and there's a
179:48
built-in method for this the includes method if our email includes the at character
then we will return true that is a valid email they have the ad character else we
will return
180:08
false is my email valid that is true let's remove the at character brof [Link]
maybe it's a website or something that is false let's try another email again we're
going to invoke the
180:25
function is valid email [Link] don't actually go there I don't know what's
going to pop up uh that is not a valid email all right how about Zucker Borg
[Link]
180:45
that is a valid email it contains an at character and for something like this if
we're returning either true or false we can use the tary operator return then our
condition is we're going
180:59
to check if our email includes the at character then add the tary operator if this
is true return true else we will return false so these should be the same which
they are all right everybody so
181:17
that's an introduction to functions it's a section of reusable code you declare
some code once and use it whenever you want you call the function to execute that
code if you need to send your
181:29
function some data you'll need a matching set of arguments and parameters and you
can return something too with the return keyword we'll have more practice with this
in the future don't
181:38
worry and that is an introduction to functions in JavaScript hey what's going on
everybody so today I'm going to explain variable scope in JavaScript variable scope
is where a
181:51
variable is recognized and accessible in this beginner's tutorial we'll be
discussing the differences between a local scope and a global scope suppose we have
a variable let X = 1 each
182:03
variable name needs to be unique within that scope I couldn't declare another
variable named X where I set X to equal 2 if I were to run this we have a syntax
error
182:14
identifier X has already been declared you can reuse the same variable names in
your program as long as they're within different Scopes to demonstrate let's create
two functions function Function
182:26
One within function one we will declare a variable x x = 1 then we will [Link]
whatever X is then let's create function two by copying function one and then paste
it
182:41
function 2 x will equal 2 [Link] x if I were to invoke Function One X = 1 if I
were to invoke function 2 well x = 2 so we have two variables with the same name in
our program that's legal as long
183:03
as they have different Scopes any variable declared inside of a function has a
local scope or anytime you declare a variable within a set of curly braces there's
no naming conflicts because
183:15
they're within different Scopes that way you can declare variables with the same
name which we've done with X now functions can't see inside of other functions
within function two we will
183:26
declare variable y equal 2 then [Link] X within function one we will
[Link] y if I were to invoke function one we have an uncaught reference error
why is not defined at Function One
183:44
one functions can't see inside of other functions function one has no idea what Y
is we've declared that within another function it's kind of like functions are
183:54
neighboring houses you can't necessarily see inside of your neighbor's house
function one has no idea what variable Y is likewise function two if I were to
invoke it function two has no idea what
184:07
X's each of these variables are declared inside of a function so they have a local
scope a global scope for a variable is any variable declared outside of a function
with Function One let's get rid of
184:22
X and we will [Link] X function two we will get rid of y [Link] x if I
were to declare a variable outside of these functions let x equal 3 I'll invoke
function one we'll display x
184:39
x is three let's invoke function two x is three any variable declared outside of a
function has a global scope it's available through the whole program a global
variable is recognized and
184:52
accessible from anywhere hey this is bro from the future I was editing this video
and I thought of a really good analogy for Global variables let's say that a
function is a house we live in function
185:04
one and our neighbor lives in function two we can see inside of function one but we
can't see inside of our neighbor's house at function two any anything that's
declared in the global
185:14
scope isn't found within any houses it's outside everybody can plainly see it it's
kind of like a creepy stalker that's under a street light at 3:00 in the morning
everybody while inside of
185:25
their house can still see everything outside that's an analogy I thought was kind
of accurate to describe a global scope however it's not recommended to declare
Global variables in a large
185:35
program just because you can have naming conflicts in a large program I might
accidentally reuse the variable X or change it somewhere X is a very common name
for a variable so in a large
185:46
program I would stick with local variables but in a small program like this it's
fine when inside of a function we'll use any local instance of a variable first if
it's not found we'll
185:58
look at the global scope So within Function One let's declare X to be one within
function two we'll declare X to be 2 and then within the global scope we have xal 3
if I were to declare function
186:14
one do you think X will equal 1 or 3 well it's one if we have two variables with
the same name and they're in different Scopes we'll use the local version first
that's why X is one and
186:28
not three if I were to invoke function 2 well xal 2 if these local variables
weren't available we would use the global version instead where x equals 3 all
right everybody so that is variable
186:44
scope it's where a variable is recognized and accessible you have a local scope
that's anytime a variable is declared within a set of krly braces that variable is
then only accessible to
186:55
anything within that set of krly braces and a global scope is where a variable is
declared outside of any functions it's available throughout the whole program and
well everybody that is
187:06
variable scope in JavaScript hey what's going on everybody in today's video we're
going to create a temperature conversion program using HTML CSS and JavaScript so
sit back
187:18
relax and enjoy the show all right let's begin everybody we will begin within our
HTML file make sure you've linked a script to your Javascript file which we'll fill
in later so within the body
187:30
of our document we will create a form element within our form we will create an H1
heading for the title of this program which we will name temperature conversion is
187:46
good after our H1 element we'll create an input element this is a self-closing tag
it's a text box since we're going to be converting temperatures I will set the
187:59
type to be number so that should give us some arrows to increase or decrease the
number or type one in if we need to I'm going to give this text box an ID of
textbox we'll be referring to this text
188:14
box by its ID later I'm also going to go ahead and set an initial value of zero
then we can increase or decrease the number like I said before it is a little small
but with CSS we will increase the
188:26
size what I'm going to do now is create two radio buttons along with labels so we
have input input is a self-closing tag the type will be radio and for the ID this
will will be a radio button to
188:44
convert to Fahrenheit I can never spell Fahrenheit we'll want the radio buttons in
the same group I will set the name of the group to be unit oh looks like I
misspelled type
188:59
there we go so I'm going to place our radio button on a new line so within our
first input element I will add a line break all right so after our first radio
button I'll create a label for
189:10
it label this lab will be 4 2 fah and the text will be Celsius to Fahrenheit or if
you prefer you could create like an arrow I don't really like the look of that let
me use an emoji instead so on
189:33
Windows to create an emoji you can hold windows and semicolon is there an arrow
that'll work so when you click on the label you should also be able to select the
radio button that's because
189:46
the four attribute is the same as the ID attribute of the radio button okay let's
copy both the first radio button and the label then paste it but change Fahrenheit
to Celsius let's switch these
190:03
around Fahrenheit to Celsius to Celsius I'm also going to add a line break after
our first label so right here as well as here Google wants to translate my web page
from German to
190:23
English it's probably because of the word fahrenheit I'm guessing now I'll create a
button the type will be button the text will be submit there is an onclick
attribute for buttons onclick
190:43
when we click on this button we can execute a JavaScript function eventually we'll
be creating a function named convert actually let's take care of that now before we
forget
190:53
So within our Javascript file function convert we'll fill this in later so when we
click on the button we will execute the convert function then lastly we're going to
display a result whatever the new
191:08
temperature is we'll use a paragraph element the ID will be result and just as a
placeholder for now I'm going to type select a unit all right so far so good let's
191:25
style this program with CSS now be sure to save your HTML file we'll move on to CSS
we will first change the body of our document let's change the font family of
191:36
the body of our document I'll pick aiel with a backup of son serif I'll change the
background color too background- color I like using hsl values let's type a color
such as black
191:56
we will change the color to be hsl I'll go with a very light gray color like 95% so
the background is going to be slightly light gray we'll fill in the form section to
be Pure White we will
192:12
select our one element that's going to be the header I'll pick a color again I'll
be using hsl values let's go with I don't know blue feel free to pick a different
color if you would like that's not
192:26
bad then we'll fill in the form our form contains pretty much all of these elements
so let's select our form I will change the background color I'll just copy this
line and paste
192:41
it but I'll I'll make this Pure White I'll text align Center everything within this
form so everything should be centered I'll set a Max width of the form because
right now it's taking up
192:56
100% of the width of the web browser so max width will be how about 350 pixels we
would like this form to be within the middle aligned horizontally we can set margin
to be
193:14
Auto to automatically Center that I'll add a little bit of padding around the
elements within our form padding let's do 25 pixels I'll smooth the corners of the
form using border radius border
193:31
radius 10 pixels then I'll add a box shadow box Shadow the first value is the
horizontal off offset let's set that to be 5 pixels then the vertical offset I will
193:48
set that to be 5 pixels the third value is the blur radius because right now it's
fairly concentrated let's stick with 15 pixels not bad you can also select a color
again I'm going to use hsl
194:03
values you can also change the transparency I'll set mine to be 30% or
approximately 30% 0.3 not bad so that's my box Shadow now we're going to change the
text box so
194:20
this text box does have an ID text box let's select this element by its ID I'll set
the width to be 50% it's going to take up 50% of the width available let's text
align
194:38
Center the number is going to be right in the middle let's change the font size
let's do 2 em for 200% I'll add a border to pixel solid then I'll pick some hsl
values for the
195:00
color I'll make it a little transparent maybe like 80% let's select a border radius
for pixels to smooth the corners I'll add a little bit of margin below the text box
margin-bottom 15 pixels is
195:25
good that's going to push the radio buttons down further just to give this text box
more space let's work on the radio buttons next so we are selecting the labels so
let's take every
195:39
label I'll change the font size so it's a little a little bigger 1.5 em for 150%
I'll make the font weight to bold just to bold it there let's select our button we
are selecting our button I'll
195:57
add a little bit of margin above the button margin-top 15 pixels let's change the
background color of the button pick a color I'll pick red and again I'm going to
use hsl values because I like
196:15
them Ah that's decent I'll change the font size of the button 1.5 em for 150% I'll
remove the border border none I'll add some padding 10 pixels for the top and
bottom of the button 15 for the
196:38
sides I'll round the corners with border radius border radius 5 pixels I'm going to
change the font color color white then when I hover my cursor over the button I
will change the cursor to be a
196:56
pointer and that appears to work now so when I hover over the button I'll use the
hover PSE sudo class to change the background color of the button we are selecting
our button then select the
197:10
hover sudo class we'll make the background color just a little bit darker we'll
change the lightness of our hsl value to be like 10% darker so I have 60% I'll
change that to be 50 so
197:23
now the background should change when I hover over the button lastly let's change
the CSS properties of the result so this should have an ID of result result I'll
make the font size a little
197:38
bit bigger font size 1.75 em is good and I'll make the font weight bold font weight
bold all right and that is all the CSS we need be sure to save everything and then
we will move on to
197:55
our Javascript file all right so what I like to do is at the top of my JavaScript
program I will declare all of the constants and variables that I'll need so let's
get our text box I'll set
198:06
this to be a constant const text box equals document. getet element by ID the ID
that we're selecting is our text box we'll need the two Fahrenheit radio button
let's copy this line paste it get
198:31
the ID of two Fahrenheit const 2 Fahrenheit get element by ID 2 Fahrenheit then 2
Celsius 2 Celsius const 2 Celsius the ID is 2 Celsius so that will be this radio
198:51
button copy this line paste it then we need the result to display the result result
get element by ID result within our HTML file we don't necessarily need to select a
unit
199:06
anymore We'll add that later if somebody presses submit without selecting a radio
button then we need let temp for the temperature when we click on the submit button
we will execute this function
199:21
convert so what are we going to do within this function we'll begin with an if
statement we'll check to see if our two Fahrenheit radio button is selected so take
two Fahrenheit we'll use the checked
199:36
property if this radio button is checked it's going to return true if it's not it's
going to be false else if 2 Celsius is checked to celsius. checked we'll perform
some different
199:54
actions else let's change the content of our result so here result. text content
equals select a unit let's see if this works be sure to save everything I am not
going to select a radio button
200:14
I'm just going to submit and that's correct select a unit we didn't select one
let's be sure that these two radio buttons are working just temporarily I'm going
to change the result within the if
200:26
and else if statement you selected two Fahrenheit and you selected 2 Celsius I just
want to be sure that these radio buttons are working so let's convert 2 Fahrenheit
submit you selected 2
200:48
Fahrenheit we'll select to the second radio button you selected 2 Celsius okay we
know that this program is reading these radio buttons successfully so we no longer
need these two lines of
201:00
code we're going to get the number from our text box we'll store that within temp
temp for temperature temp equals take our text box access the value within so when
we accept user input it's
201:18
of the string data type I'm going to typ cast the value as a number so we can use
it with math okay then we're going to take our temperature and convert it to
Fahrenheit here's the formula temp equals
201:33
temp * 9 / 5 + 32 then we're going to update the text content of the result result.
text content equals our temperature then I'm going to add plus Fahrenheit so to add
the degree symbol
201:55
on Windows you can hold alt then type 0176 on the numpad so this will be Fahrenheit
let's type 100 De Celsius to Fahrenheit that gives us 212° fah 10 would be 50 1° c
would be
202:16
33.8 0 is 32° F if you would like to add some Precision following our temperature
there's a built-in method to fixed We'll add one point of precision this will give
us one digit past the
202:32
decimal place 0° cus converted to Fahrenheit is 32.0 De F 10° C is 50° F let's copy
these three lines then paste them within the else if statement we'll keep this line
the same but we'll change the
202:53
formula temp equals within parentheses temp - 32 * 5 / 9 then change fit to Celsius
so what is 32° fah converted to Celsius that is zero 100 is 37.8 all right
everybody so that is a
203:20
simple temperature conversion program using JavaScript HTML and CSS hey what's
going on everybody so today I'm going to explain arrays in JavaScript think of an
array as a
203:33
variable like structure that can hold more than one value for example let's say we
had a variable named fruit go ahead and pick pick a fruit I'll pick an apple our
variable can store one value
203:46
but we can turn a variable into an array and it can store more than one value and
we can do so by enclosing all values with a set of straight brackets now my
variable of fruit is now an array it can
203:58
store more than one value just be sure that each value is comma separated this time
I'll add an orange and a banana just to make it more obvious that this is an array
I'm going
204:10
to add an s so that my variable name is plural it's not mandatory but it helps with
readability I now have an array of fruits but let me show you something if I were
to [Link] my array of
204:25
fruits well JavaScript is going to print out all of the elements in this array each
item each value is known as an element we have three elements if you need to access
an individual element
204:37
following the array you have to add an index number enclosed in straight brackets
if I would like the element at the first position that would have an index of zero
that would give me an
204:48
Apple fruits at index of one would be orange fruits at index of two is banana if I
were to attempt to access the element at index 3 well it's undefined we only have
three elements
205:03
within our array 0 1 2 arrays always begin with zero you can even change one of
these elements by accessing that array at a given element let's access our array
fruits at
205:17
index zero I will set the equal to be a coconut so now we have coconut orange
banana let's change fruits at index one to be a coconut Apple coconut banana index
2 will be a coconut Apple orange
205:34
coconut if I set fruits at index 3 to be a coconut let me console that log that too
fruits at index 3 we can add a new element to that array otherwise to add an
element there's a
205:46
built-in method of arrays fruits do push to push an element to the end I will add a
coconut to the end of my array Apple orange banana coconut then we have pop pop is
going to remove the last
206:06
element Apple orange undefined the unshift method will add an El m to the beginning
take our array use the unshift method unshift I will add a mango to the beginning
of my array mango Apple orange
206:24
banana then we have shift to remove an element from the beginning fruits. shift now
we have an orange banana and my last two elements are undefined to get the length
of an array there's a
206:37
length property let's create a new variable let num of fruits to store the number
of fruits that we have type the array name do length then let's [Link] the
number of fruits we have
206:57
we have three fruits I'll add another I'll add a coconut to the end and we have
four so that's how to get the length of an array there's a length property type the
array name do
207:09
length we can find the index of an element if there's a match let index equals
let's search for an apple fruits. index of method what are we searching for let's
search for an apple then I
207:26
will display the index so our apple is located at index zero let's search for an
orange that's index one banana that's two coconut three what if we search for an
element that doesn't exist like a
207:44
Maino well this method will return ne1 that could be helpful within an if statement
you can check to see if this method returns negative 1 then if it does that means
the element wasn't found
207:54
and you can let the user know if index equals -1 display that element wasn't found
now if you would like to Loop through the elements and display them there's an
easier way to do that you can
208:06
use a for Loop so four there's up to three statements we'll need a counter or some
sort of index let I equal Z that's the first statement we'll continue this as long
as
208:20
I is less than our fruits array do length property then we will increment I by One
if we have four elements we should execute this Loop four times during each
iteration I will
208:36
[Link] our fruits array but the index instead of being like Z 0 1 2 3 a hard
number we'll use our counter our index of I and let's get rid of that line now we
208:50
should Loop through all of the elements of this array and print them out
individually using a for Loop we can even increment by different number like two i+
equals 2 so here we're only
209:01
displaying the apple and the banana if I set index to be one then increment by two
will display orange then coconut so using a for Loop there's a few different ways
in which you can display the
209:14
elements of an array if you need to display the order of this array in Reverse we
can change this around we will set our counter I to be the length of our array then
we'll continue as long
209:25
as I is greater than or equal to zero then iusus there's one change I'm going to
make we have undefined coconut banana orange Apple so the length of my array is
four but if I were to access our
209:41
array fruits at index 4 where would that be 0 1 2 3 that's out of bounds I'm going
to set our index to be fruits. length minus one 0 1 2 3 our length is 4 minus 1 is
a total of three now we're
209:58
printing our array in Reverse coconut banana orange Apple there's also an enhanced
for loop it's a shortcut to displaying the elements of an array you can write
something like this let fruit of array
210:13
fruits really this variable can be anything but I like to write a singular version
of my array name then during each iteration I will display each fruit apple orange
banana coconut this is an
210:28
enhanced for loop it's kind of like a shortcut to displaying the elements of an
array if this array name were I don't know like meets you could say let meat of
meats and then display each meat
210:42
but of course they're still fruit that's a shortcut you can use now to sort an
array you can use the sort method fruits. sort and that should sort the elements in
alphabetical order apple banana
210:56
coconut orange to sort them in reverse order you can tack on the reverse method to
the end fruits. sort method. reverse method now they're all backwards in Reverse
alphabetical order orange
211:10
coconut banana apple all right everybody so that's an introduction to arrays we'll
have a lot of practice with this in the future so if you don't remember everything
that's okay an array is a
211:20
variable like structure that can hold more than one value a variable can hold one
value an array can hold many and well everybody those are arrays in JavaScript hey
everybody today I'm going
211:34
to explain the spread operator in JavaScript the spread operator is represented by
three dots the spread operator allows an iterable such as an array or string to be
expanded in two
211:46
separate elements what this does is unpack the elements here's an example let's
create an array of numbers pick some numbers I'll just pick 1 through five one 2 3
4 5 then just to test this let's
212:03
[Link] my array numbers in this array what if I would like to find the
greatest value well one way which I could do that is let's declare a maximum let
maximum this is
212:16
going to be a variable equals I will use the max method of math what would happen
if I place our array within this method then I will display our maximum so we have
not a number using
212:31
the max method we can't place an array directly within this method however by
utilizing the spread operator we can spread this array into different elements so
we will preedee this array
212:42
with the spread operator we are going to unpack the elements now if I run this
program again we have our result of five when you use the spread operator imagine
212:53
that you're opening a box and taking out all the contents inside like you're
unpacking something let's find the minimum this time let minimum equals [Link] we
will pass our array of
213:08
numbers then use the operator to spread our array into different elements what is
the minimum value from this array that would be one you can also do this with
strings too you can separate a
213:21
string into different characters let let's create a username equals type your name
first name and last name I will create an array named letters letters equals we'll
create a new array let's
213:39
take our username it's a string and use the spread operator then I will display our
letters [Link] letters and here's my name divided into different characters
what we have is an
213:55
array of characters with my array of characters I can join them back together and
insert characters between each element I will method chain the join method after
our
214:06
array We'll add a dash between each character so now my username is all one string
but there's a dash between each character okay now this time we're going to create
214:18
an array of fruits we'll make a shallow copy of an array using the spread operator
add some fruits I'll add an apple an orange and a banana then I will [Link] my
214:37
fruits I can create a shallow copy of this array using the spread operator a
shallow copy means it's a different data structure but it contains identical values
I'll create a copy of fruits
214:50
named new fruits equals an array let's take our fruits array then use the spread
operator let's display new fruits and it should be an identical copy yep there's
215:06
no apparent change we have two different arrays but they contain identical elements
we can combine two or more arrays using the spread operator let's create an array
of vegetables let's add some
215:24
carrots celery potatoes I'll rename new fruits as Foods let's add our array of
fruits we're spreading it comma then we will spread sprad our vegetables array then
we will display our array
215:45
Foods this array contains all of the elements from these two arrays fruits and
vegetables we can use the spread operator to combine arrays we even have the
capability to append separate
215:57
elements along with unpacking these arrays I will also add eggs and milk we have
all of the elements from our two arrays plus a few extras egg and milk all right
everybody so that's the
216:13
spread operator it's three dots it allows an iterable such as an array or string to
be expanded into separate elements and well everybody that is the spread operator
in
216:26
JavaScript hey hey hey what's going on everybody today I'm going to explain rest
parameters in JavaScript rest parameters is a parameter prefixed with three dots
they allow a function to work
216:37
with a variable number of arguments by bundling them into an array it's very
similar to the spread operator which we talked about in the last video the spread
operator expands an array into
216:48
separate elements rest parameters do the opposite they bundle separate elements
into an array spread will spread an array into separate elements rest parameters
will bundle separate elements
216:59
into an array it effectively does the opposite how could rest parameters be useful
let me give you an example say we have a bunch of different food const food one
food one equals
217:12
Pizza we'll create a few different food variables let's start with four food one
food two food three food four we have pizza hamburger hot dog and sushi I'm going
to create a function that uses rest
217:30
parameters it's going to Output all food that I send it we'll pretend that we're
opening a fridge imagine that all of this food is in a fridge oh open fridge fridge
short for
217:43
refrigerator to use rest parameters I need three dots we're going to stick all of
this food into an array but what should the array name be let's say Foods that's
descriptive then I'm going to
217:57
[Link] my array of foods now I'm going to call this function open fridge I
will send this function a variable number of arguments this method is going to
display an array we have food one
218:14
pizza food 2 hamburger hamburger is also within our array food three hot dog food
four Sushi let me add one more food let's add Ramen food five will be Ramen then I
will add food
218:34
five you can see that I can send this function any number of arguments that I would
like this function is is designed to accept any number of arguments I could combine
this function with the
218:45
spread operator when I'm displaying my Foods array all of these elements are in an
array but I could separate them back into separate Elements by using the spread
operator which is the same three
218:56
dots as the rest parameters rest parameters are used as parameters the spread
operator is used whenever you have an array or any sort of collection of something
so now when I combine the
219:06
rest parameters and the spread operator I can display all of my separate elements
you can even use rest parameters to stick all elements within an array so this time
I'm going to create a separate
219:20
function to get food we will use rest parameters our array name will be Foods all
we're going to do is return Foods take all of these separate elements stick them
within an array then return that
219:41
array so I'm going to create a new array const Foods equals call our get food
method pass in a variable amount of arguments let's pass in food one food two food
three food four and food
220:02
five and then we got to display it [Link] my array Foods so that's how the
rest parameters can be used to combine elements and bundle them into an array then
if you want you can
220:17
return the array or do whatever you want with it let's go over a second example
we'll create a method to sum a bunch of numbers together function sum we will use
rest parameter so we can
220:30
accept any number of arguments our array name will be numbers what we'll do within
this method is have a result result equals equal 0 we'll keep track of the current
sum within our result
220:44
I'll create a for Loop to iterate over our array for every let number of numbers
take our result plus equals the current number and then we are going to return our
221:04
result now we'll have const total equals in our some function pass in as many
numbers as we would like let's start with one oh then I should probably display the
total
221:20
[Link] I'll use a template literal your total is I'll add a placeholder total
your total is $1 let's add a few more arguments two the total is now $3 three $6 4
is 10 5 is
221:44
15 let's create a function to calculate an average let's copy our sum function
let's name this function get average all we have to do when returning our result to
get the average is divide
222:01
our result by the length of our numbers array divided by numbers. length property
that will give you the average so now const total equals get the average maybe
these are test scores one
222:18
student got a 75 another got a 100 another student has 85 90 and a 50 let's
[Link] the total the average is 80 let's go over example three you can use the
rest parameters to combine
222:39
strings together we will create a function to combine strings we'll send in a title
like Mister a first name such as SpongeBob a last name Square Pants he's the third
we still need to make this
223:03
function though but const full name equals whatever string is returned all right
let's work on this function function combine string let's make this plural strings
we need to use rest
223:24
parameters let's name our array strings an easy way to do this is to return our
array of strings and use the built-in join method to join all of the strings
together but but we'll add a
223:40
space between each string all right we should now have a full name variable that's
all of the strings combined so let's [Link] our full name Mr SpongeBob
SquarePants the third
223:59
that's one way in which you could use the rest parameters to combine a bunch of
strings into one such as if you're creating a full name all right everybody so
those are rest parameters they allow
224:10
a function to work with a variable number of arguments by bundling them into an
array it's the opposite of the spread operator the spread operator expands an array
into separate elements
224:21
the rest parameters bundle separate elements into an array and well everybody those
are rest parameters in JavaScript hey everybody so in today's video we're going to
use JavaScript HTML
224:37
and CSS to create a dice roller program this is an optional project you will need
some images of dice to work with if you're able to find some images of dice I would
save them somewhere maybe on
224:48
your desktop once you have images of your dice we're going to create a new folder
new folder I'll name my folder diore images then take all of your dice images move
them to that
225:03
folder and now we are ready to begin we'll create all of the HTML elements that
we'll need I will create a div section this div will have an ID of container to
contain our program I'll include an H1
225:19
heading with text of dice roller after this H1 element I'll create a label the
label will have text of number of dice afterwards I'll use an input element I'm
going to zoom in a little bit
225:42
temporarily with this input element I'll type in a number of dice I would like such
as 1 2 3 however I can type in characters which I would like to avoid I will set
the type attribute of the input
225:56
element to be number we're indicating to the user to select a number and not type
in anything although there are ways to circumvent this this will be good enough
226:07
for now for the input element we can set a default value I will set the value
attribute to equal one for the default we can go below zero I'll set a minimum with
the Min attribute Min equals
226:23
1 we can't go below one but we can select any number one or above now we'll create
a button the button will have text of roll dice the button will have its onclick
attribute I keep on spelling on lick
226:44
onclick attribute set to a JavaScript function let's say roll dice we'll still need
to Define this function in JavaScript after our button I'll create two div sections
the first will have an ID of
227:01
dice result this will display some text the numbers of the dice we roll the second
development will be for the images ID dice images and that is all the HTML that
we'll need let's head to our CSS file
227:19
and I'll Zoom back to 100% let's select our ID of container # container I will
change the font family to a sance s font such as Arial with a backup of s serif I
will text Al line
227:41
Center increase the font size in this project I'm going to use RM instead of em
because we'll be working with a lot of different font sizes em is the font size
relative to the parent RM
227:56
is for the root for this specific project I'll stick with RM and I will set the
font weight to be bold let's style our button next we are SEL cting our button I'll
228:11
increase the font size of the button to be 1.5 RM I'll add a little bit of padding
10 pixels by 15 pixels I will set the Border radius to round the corners 10 pixels
remove the Border because it's
228:32
ugly border none pick background color for the button I'll pick something blue but
I like using hsl values something like that looks good I will change the font color
to be
228:54
white and I will set the font weight to be bold not bad when I hover my cursor over
the button I will change the cursor to be a pointer let's change the background
color of the
229:12
button when we hover over it we are selecting the hover suda class of the button
let's take our background color I'll increase the lightness by 10% so that should
change when we hover
229:27
over the button now when I click on the button I'll increase the lightness even
more to show that it's active with our button we will select the active pseudo
class I'll set the lightness to be 70
229:39
% so when we click on the button it should flash momentarily which it is let's
style the input element cuz I can barely see it with our input element I need to
scroll
229:53
down let's increase the font size to two RM I'll set a width of50 pixels text align
Center and font weight bold with our HTML file we do have two empty div elements
currently we'll style
230:22
these at the end once we get our images to populate we'll style that last with the
onclick attribute of the button we set a function of r dice now we need to Define
it within our Javascript file we
230:34
will Define a function to roll dice we have a lot of constants to declare I'll
create a constant for the number of dice we would like what's the value of this
input element I will
230:46
Define const num of dice what is the number of dice we need to roll equals
document. getet element by ID the ID of this input element is I actually forgot
what was it oh we didn't set an
231:06
ID okay let's do that okay so for input element the ID will be num of dice num of
dice but I would just like the value I will access the value of whatever this input
element is for the next constant
231:30
we're going to get the dice result this empty div section const dice result equals
let's copy this line of code but we don't need the value we just need that ID dice
231:48
result then let's do this with dice images so we can copy this paste it const dice
images the ID was dice images I'll create two empty arrays const values this will
be an empty array
232:10
we'll store all of the dice rolls the numbers then we'll need an array of images
const images this will be for the images of the dice at this point in time we're
going to create a for Loop that
232:24
will Loop once for every dice that we roll we have to generate a random number
between one and six for each dice we're rolling if I'm rolling three dice I need a
for Loop to iterate three times let's
232:36
create a for Loop let I equal 0 continue this as long as I is less than the number
of dice then increment I by One during each iteration I need to generate a random
232:51
number between 1 and six I'll store that within a constant const value that will be
the random number equals math. random method this generates a random number between
0 and
233:05
1 but I'm going to multiply it by six to give us a random number between 0 and 5
it's not going to be a whole number though so I'm going to round it using math.
floor then enclose this part of our
233:20
equation now we should get a random number between zero and five but I need a
random number between 1 and six so I'll add one to the End plus one so now we'll
get a random number between 1 and
233:33
six just to be sure that this all works temporarily I'm going to con console. log
our value if I roll one dice we should get one random number one let's try three
dice 546
233:54
324 all right we don't need this console. log statement anymore we know that it's
working with these values I'm going to push them into our array of values take our
array of values use the push method
234:09
add our value that we randomly generate during each iteration and let's see if this
works I'm going to [Link] my array of values just to be sure that there's some
numbers in
234:22
there let's roll for dice inspect console I have an array of four elements the
number 6326 so that does work all right here's the tricky part I need to take my
array of images use the
234:41
push method I will create a string representation of an HTML element I need to get
one of the images found within the SCE images folder using angle brackets I will
create an image
234:55
element I will set the source equal to that folder name so my folder name was dice
uncore images dice uncore Images slash so with my images it might be different for
you mine are labeled appropriately
235:14
you know for one two for two three for three so on and so forth I will use a
placeholder add our value this number then follow this with the file extension of
the images my images are PNG images
235:30
do pay attention to that after we exit this for Loop we should have an array of
HTML images then we're going to take our dice result constant change the text
content to
235:44
equal all of the values all use a template string I will display the word dice at a
placeholder I'm going to join all of the elements together all of the values to do
that you can take your
235:57
array of values use the built-in join method and I will join them all by a certain
character or characters I will join all of these numbers by a common and a space
let's see if this works I'm
236:12
going to roll one dice yep dice I rolled a one I rolled a four I rolled a three
let's roll two dice I have 2 comma 5 four comma 6 2 comma 2 comma 3 6 comma 3 comma
2 then we have to get the images
236:32
let's take our dice images constant access the inner HTML set this equal to take
our array of images use the built-in join method I'm not going to join them by any
character I'll join them by an empty
236:49
string and let's see if this works I would like one dice yeah there it is two and
three now for some reason if your dice isn't displaying with our image element I
will set the alt attribute to
237:04
equal a string of dice space add a placeholder value let's say I get the folder
name wrong I will rename this as dice image I'll attempt to display one dice dice
three dice four dice three so in case
237:24
our image can't display for some reason will at least display the alternative text
this is good for troubleshooting and for screen readers for accessibility let me
correct the name of the folder
237:35
again so with our dice images at least for me they kind of big and I'd like to
space them out a little bit our last step is we're going to go back to our CSS
stylesheet I will select the ID of dice
237:49
result that's going to be for this title right here I'll add some margin around
this text right now it's kind of compressed I will set margin of 25 pixels then
with our dice images ID dice
238:05
images with my ID of dice images is take each child image set a width of 150 pixels
should be good yeah they're a lot smaller now I'll add a little bit of margin too
margin 5
238:26
pixels yeah that's not a bad looking program all right everybody so that was a dice
roller program you can make using JavaScript HTML and CSS impress your friends and
that's pretty much
238:43
it hey what's going on everybody so in today's lesson we're going to create a
project where we Generate random passwords this will help us solidify our
understanding of functions and random
238:54
numbers this will be an exercise for beginners by setting different options we can
change the format of the password and well let's begin everybody all right let's
begin we'll need to let our
239:04
program know what the length of our password is going to be let's create a constant
to store that const password length set this equal to maybe 12 but we can adjust
that accordingly we'll create
239:17
a Boolean to specify if our generated password is going to contain lowercase
characters we'll create a constant include lowercase do we want to include
lowercase characters we can set this to
239:32
be true or false we will set this to be true do we want to include uppercase
characters include uppercase I will again set this to be true do we want to include
numbers const include
239:51
numbers I will set that to be true do we want to include symbols const include
symbols we'll Define a function at the top of our program function to generate
password we have a lot of parameters to
240:12
set up we're going to pass in all of these constants as arguments so we have a
length include lowercase include uppercase include numbers and include symbols when
we call this function we
240:32
have to pass in all of these arguments so we will call our generate password
function pass in our password length include lowercase include uppercase include
numbers and include
240:51
symbols at the bottom of our function we will be returning a password but for now
I'm just going to write an empty string because we still need to determine what
that password is going to be after
241:02
finishing the generate password function this will return a string a string
password we will store that within const password equals whatever is returned from
the generate password function and
241:16
just so that this is more readable although not necessary I'm going to place each
of these arguments on a new line because I'm OCD about things being an alignment
and then at the very end of
241:28
this program I will display a template string of generated password I'll add a a
placeholder then we'll display our password that we generate so right now it's not
going to
241:45
display anything we're returning an empty string but that is everything we need
outside of this function to generate our password basically we're passing in
options when we generate our
241:56
password do we want to include lowercase characters uppercase characters numbers
and or symbols we have a number and a bunch of Boolean values within our password
we're going to
242:08
create a few constants within this generate password function we will create one
long string of all of the lowercase characters chars equals I'm going to go through
the
242:20
alphabet we will have one long string of alphabetical characters and I think I got
all of them so there should be 26 now we're going to do this with uppercase
characters const uppercase chars
242:43
equals I'm going to turn on caps lock go through the alphabet we'll create a
constant of number characters number chars equals 0 through 9 and symbols const
symbol
243:14
chars which symbols would you like to include I'll just add a bunch that's probably
good enough for now feel free to add more or less we will create a variable for
allowed chars meaning
243:36
characters and an empty pth password let password equal an empty string if some of
these constants are true we would like to take that corresponding set of characters
and
243:53
concatenate it to the allowed Char string so what we'll do is take our allowed
characters variable use string concatenation by using plus equals we'll check to
see if include lowercase is
244:07
true or false we can use theary operator for that if we would like to include
lowercase characters we will string concatenate our lowercase chars our lowercase
characters otherwise we'll concatenate
244:22
an empty string let's do this with uppercase characters with our allowed characters
let's string concatenate and check if we're including uppercase characters question
mark if this is true we will
244:36
concatenate all of the uppercase characters we've declared otherwise we'll
concatenate an empty string so we don't include them let's do this with number
chars include numbers are we including
244:51
numbers within our password if so we will return our number Char string and then
symbols are we including symbols within our password if so concatenate our string
of symbol character
245:09
all right just to test everything afterwards I'm going to [Link] our allowed
characters so right now I'm going to switch all of these constants to be false so
right now we're not including
245:27
any characters if I were to set include lowercase to be true we would include all
of the lowercase characters that's one long string Let's test uppercase yep we are
including all of the uppercase
245:40
characters include numbers yes that works and include symbols that also works at
this point in the program we're going to have one gigantic string of all of the
possible characters before we
245:54
move on with the program I do want to run some checks using some if statements
first let's check to see if the password length is zero or less than zero right now
it's set to 12 using an if statement
246:08
if the length the length of the password is less than or equal to zero we need to
let the user know that the password length must be at least one we will return a
246:22
string password length must be at least one right now we're not generating a
password we're returning an empty string if I set the password length to be zero we
will generate this message pass
246:37
password length must be at least one or even a negative number like1 password
length must be at least one let's set that back to be 12 what if we don't select
any options what if all
246:51
of these character options were false we can check the length of our loud
characters variable so if our loud characters length property is strictly equal to
zero this will only
247:12
be possible if all of these options are set to false we will return a template
string at least one set of characters needs to be selected and let's see if this
works yes
247:31
it does at least one set of characters needs to be selected I can select any
options that I would like like I will set these all to be true now here's the hard
part for as
247:46
many iterations as our password is we will select a random character from all of
the different possibilities we will use a for Loop we will let I be our index our
248:00
counter we will continue this for loop as long as I is less than the length the
password length then increment I by One during each iteration if our password
length is 12 we will execute this for
248:14
Loop a total of 12 times now we will generate a random index const random index
equals we will use the random method of math this generates a random number between
0o and one I can multiply this
248:31
number that's randomly generated by the length of our allowed characters let's say
we're including only lowercase characters well this is a total of 26 characters in
the
248:44
alphabet if I'm taking [Link] * 26 I'll be given a random number between 0 and
25 but I will need to round it down let's enclose this equation with the floor
method of math to round down math.
249:03
floor we'll use string concatenation with our password Cur our password is an empty
string but we will use string concatenation we will string concatenate a randomly
chosen character from our
249:16
string of allowed characters password plus equals our allowed characters at the
index of random index then at the end of this program we will return our password
and let's see if this works
249:34
let's close out of this function we don't need it anymore and let's see if this
works yeah there's our password so every time I run the program I get a new random
password and
249:46
I can turn these options on and off let's set all of these options to be false to
begin with and I will set the length to be zero let's see what happens password
length must be at least one all right
250:01
how about a password of 10 10 characters long at least one set of characters needs
to be selected let's select only lowercase characters yep we only have lowercase
characters let's allow uppercase
250:14
characters now let's allow numbers I didn't get any of that time let's do it again
okay there's a number I guess numbers don't come up very frequently and let's
include
250:28
symbols and there's a few symbols in there all right everybody so that was an
exercise to Generate random passwords it should give you some practice with
functions and working with random
250:39
numbers and well everybody that was a random password generator in JavaScript hey
welcome back everybody so today I got to explain callbacks in JavaScript a callback
is a function that
250:55
is passed as an argument to another function they are used to handle asynchronous
operations such as reading a file Network requests or interacting with databases
these activities take
251:07
some time to complete now with JavaScript we don't necessarily wait for a process
to finish before continuing with the rest of the program for example if we were to
read a file if it takes a
251:17
long time to read that file JavaScript might continue on with the rest of the
program we might attempt to display the contents of that file before we're finished
reading it that's where
251:25
callbacks come in we're telling JavaScript hey when you're done call this next when
you're done reading the file then display the contents only after that process is
complete I'll I'll
251:37
give you a few examples of the syntax of a call back we'll start with something
really simple we'll create a function to display the word hello this will be the
hello function then I will
251:50
[Link] the word hello so I can invoke this function hello to execute it hello
what if we were to create a function for goodbye function goodbye we will
[Link]
252:13
goodbye okay after hello let's invoke goodbye we have hello then goodbye what if my
hello function takes a lot of time to process well JavaScript isn't necessarily
going to wait around before
252:27
executing the goodbye function I'm going to add a few lines of code you don't need
to copy this these few lines of code are going to make us wait for 3 seconds you
don't need to write this
252:37
this down but do pay attention we will execute the hello function followed by the
goodbye function but we're going to pretend that our hello function takes a little
bit of time to
252:47
process so now we have goodbye already executed followed by hello but it should be
the other way around I would like to guarantee that the goodbye function follows
after the hello function well I
253:00
can do that by adding a call back to the goodbye function after the hello function
is complete we'll get rid of the this goodbye function invocation to use a call
back you pass a
253:11
function as an argument to another function we will pass the goodbye function as an
argument to the hello function So within the set of parentheses type the name of
the
253:22
function goodbye now be sure you don't add a set of parentheses after the function
name you'll call it right away we are passing the name of the function as an
argument but we need a matching
253:33
parameter I will name this parameter callback and after everything within this
function is complete let's take our call back then invoke it by adding a set of
parentheses
253:45
invoke meaning call all right now let's see what happens we have our hello function
followed by the goodbye function in that order let's create another function what
about a leave function
253:59
we'll tell somebody to leave [Link] leave I will pass pass the name of this
function as an argument to the hello function leave is now our call back after
executing the hello function
254:15
we will execute our call back and in this case it's the leave function let's create
another function for wait function waight [Link] wait we'll pass the name of
254:30
the function as an argument to the hello function wait is now our call back we will
execute the hello function followed by the weight function so by using callbacks we
are guaranteeing that the
254:42
function passed in will execute next you can pass callbacks as well as other
arguments to a function let's go over a second example I will create a function to
sum two numbers
254:55
together X comma y I'll also add a call back call back X comma y we have three
parameters total within the sum function we will create a local variable of result
add x +
255:12
y and then I will call my callback then I'll pass the result as an argument to the
Callback function then I will create a function to display the result to my console
display console there is one
255:28
parameter we have a result argument we're receiving then [Link] my result all
right now we will invoke the sum function but we have three arguments that we need
to pass in a call back a
255:46
value for x and a value for y let's invoke the display console function as a call
back again be sure to not add a set a parentheses after the name because then
you'll invoke it right
255:55
away X will be 1 y will be two and let's see the result the result is three So
within our sum function calculate the result first then after that process is
finished then
256:10
display the result to the console let's create a separate function to display the
result to our document object window our web page basically uh let's pretend that
this wasn't
256:21
here I'll create an H1 element with an ID of my H1 I will create a separate
function display page to display on the web page I think display Dom would be more
appropriate
256:41
but I haven't explained what the document object model is yet so let's just work
with display page we will accept a result I will change the text content of the my
H1
256:55
element document. getet element by ID the ID was my H1 we will change the text
content to equal our result that we receive as a callback we will use the display
page function display
257:15
page there and the result is three after this calculation processes execute the
call back and this time we are passing it to the display page function that we
created all right everybody so that's a
257:27
call back it's a function that is passed as an argument to another function they're
used to handle asynchronous operations operations that may take a variable amount
of time such as reading
257:38
a file Network requests or interacting with databases we're not exactly sure when
these processes are going to complete by using a callback we can ensure that a
function executes after
257:48
these processes are complete and not before accidentally all we're doing is saying
hey when you're done call this next we'll have more practice with callbacks
especially in the upcoming
257:59
topics and while everybody those are callbacks in JavaScript hey it's me again
today I'm going to explain the for each method in JavaScript the for each method is
used
258:11
to iterate meaning Loop through the elements of an array and apply a specified
function to each element you have an array we can use the built-in for each method
of arrays and send each
258:22
element through a call back to a function here's an example I'll create an array of
numbers let numbers equals 1- 5 then I'm going to create a function to display each
element function
258:41
display there will be one parameter an element we will individually display each
element within this array [Link] each element I can display each element of
this array by using the for each
259:00
method we will take our array dot use the built-in for each method then pass a call
back as an argument we will pass our display function as an argument so this should
259:15
display all of the elements in my array to the console 1 2 3 4 5 believe it or not
the element argument is provided for us with the for each method behind the scenes
the for each method will provide
259:27
to a callback an element index and array argument an element for the current
element that we're on when looping through this array an index that keeps track of
the current index number and
259:38
the location of the array itself in this case it would be numbers that's why when
we pass the display function as a call back we're already provided with an element
argument behind the scenes so
259:48
we're using the for each method to display all of the elements of this array let's
use the for each method again to double each element before displaying it I will
create a new
259:58
function function double to double the value of each element element index and
array are provided for us automatically for each element what are we going to do
let's take our array at
260:14
index of index index keeps track of the current index number so during each
iteration it's going to increment by one starting with zero we will take our
element multiply it by
260:29
two all right so let's take our numbers array use the for each method then pass a
call back to our double function so now all of these elements should be doubled
let's triple them now
260:43
we'll create a function for triple function triple we will set the parameters to be
the same but we will multiply each element by three then passing a call back for
triple so now we have 3 6 9 12 15
260:59
they're all tripled let's Square each element function Square again the element
index and array arguments are provided for us take our array that we receive at
index of the
261:14
current index number set this equal to to square a number we can use the power
method of math then raise a base to a given power we are raising our base of
element to the power of two if I pass
261:30
our Square function as a call back to for each we will now Square each number
before displaying it 1 49625 then this time let's create a cube function function
Cube raise our element to the power of
261:49
three pass our Cube function as a call back to the for each method and now each
number is cubed 1 8 27 64 125 let's create a more practical example I will create
an array of fruits
262:07
let fruits equals some fruit we have an apple we have an orange a banana and a
coconut we'll create a function to display each element function display it's kind
of like what we did
262:26
before an element argument is going to be provided to us during each iteration
let's [Link] each element and then we will use the built-in for each method of
our array fruits fruits.
262:43
for each we will pass our function as a call back to display each element of this
array Apple orange banana coconut let's create a function to make all of these
strings uppercase function
263:01
uppercase we'll need an element index and array element index array during each
iteration let's take our array that we receive at the index of our index equals
take the element that we receive use the
263:21
two uppercase method so we have an uppercase function that utilizes the two
uppercase method remember that a method usually belongs to something this method
belongs to the element that we receive
263:36
functions are Standalone before displaying each element within my array of fruits
let's take our fruits array use the for each method then apply a call back to
uppercase to make all of
263:48
the elements uppercase before displaying them what I'm going to do is copy all of
these elements so they will begin uppercase I'll create a lowercase function
function lowercase
264:06
we have our element index and array with this line of code we will use the two
lowercase method within the for each method we will pass our lowercase function as
a callback to make all of the elements
264:21
lowercase let's set the elements of our array to be all lowercase again this will
be a challenge round we will capitalize the first letter in each element of this
array we will create a function
264:37
function capitalize the element index and array arguments are going to be provided
to us take our array that we receive at the current index set this equal to we're
264:54
going to get the first character in each element we will take our element get the
first character Char at index of zero method to uppercase to make this letter
uppercase then we will strink
265:14
catenate our element use the slice method we'll create a substring begin at index
one this portion is going to create a substring of every character besides the
first the first character
265:29
we're going to make uppercase so now this should work so let's take our capitalize
function pass it to the for each method and now the first character in each element
is all
265:41
uppercase all right everybody so that is the for each method it's used to iterate
over the elements of an array and apply a specified function as a callback to each
element you take your array use the
265:53
for each method then pass a call back as an argument it's really useful if you need
to apply a function to each element of this array and well everybody that is the
for each method in JavaScript
266:07
hey it's me again today I got to explain the map method in JavaScript the map
method accepts a callback and applies that function to each element of an array
it's very similar to the for each
266:19
method however it returns a new array that's a key difference for example let's
create an array of constants I'm picking constants just to demonstrate that we're
not changing any elements in
266:30
this array we have const numbers I'll select the numbers 1 through 5 to keep it
simple I will create a function to square each number function Square we have one
parameter we have an
266:45
element all I'm going to do is return [Link] this will raise a base to a given
power we are raising our element to the power of two then returning it we're going
to take our array of numbers
267:02
use the built-in map method then pass in our function as a call back the map method
will return a new array we will create a new array to store the values that are
returned so I will create const
267:18
squares equals numbers. map and then let's display our squares I'll use [Link]
for now [Link] our squares here are all the numbers squared 1 4 9 16 25 let's
create
267:34
a function to cube these these numbers now we'll copy and paste our Square function
but change it to cube we'll raise our element to the power of three const cubes
equals take our
267:50
original array numbers dot use the map method pass in a call back to the function
we would like to use Cube then we will [Link] R array of cubes and we have
some new numbers 1 8
268:05
27 64 125 the map method is very similar to four each but after completion the map
method returns a new array we still have our original numbers whereas in four each
we'll change them that's a key
268:20
difference let's go over a new example we'll create an array of students const
students equals for my first student I will pick SpongeBob then Patrick Squidward
Sandy that's good enough I
268:41
will create a function to make all of these strings uppercase function uppercase
there is a single element remember the element is going to be provided for us with
the map method
268:56
element index and array but we only need element in this case I will return our
element dot to uppercase method and that's it we'll create a new array students
what can we name this uh
269:15
students upper I suppose we will take our array of students use the map method pass
in the function we would like to apply as a callback then I will [Link]
students
269:33
upper within my array all of the students names are all uppercase let's create a
function for lowercase function lowercase to lowercase I will create a new array
const
269:50
students lower equals the name of the array students map pass in our function as a
call back then display the array of students lower now all of the names are now
lowercase all right third example
270:08
this one is more practical we'll create an array of dates const dates equals
certain regions will order their dates differently for example you might have the
year followed by a month then a
270:23
day we're going to rearrange the order of these dates using the map method so come
up with a few dates I picked 2024 January 10th 2025 February 20th 2026 March 30th
feel free to rearrange
270:46
these however you want I will create a function to format dates we have one
parameter a single element within this function I will create a temporary array
named Parts
271:02
we're going to split each date into parts and it within an array within this
function const Parts equals element. split we are going to split each element but
where we are going to
271:18
split at each dash for example with my first element we'll split this date into
2024 that will be the first element 1 and 10 then we'll reformat these parts I will
return a template string so I'm
271:34
going to need some placeholders ERS so dollar sign curly braces let's take our
array of parts at index of one that will be the month I live in the United States
we arrange our dates with
271:50
month then day then year I will place my month first forward slash let's include
another placeholder Parts at index of two that will be the day of the month slash
Parts at
272:10
index0 that will be the year we will create a new array const formatted dates
equals take our original array dates use the map method then pass the function name
as a call back then after I will
272:31
[Link] our formatted dates and and here they are for me the dates are now
January 10th 2024 February 2nd 2025 March 30th 2026 feel free to arrange these
however you like all right
272:47
everybody that is the map method it's very similar to the for each method the math
method accepts a call back and applies that function to each element of an array
however it returns a new array
272:57
when it's finished that's nice if you need to preserve the original array that the
elements came from and well everybody that is the map method in Javas script hey
again everybody it's me big
273:10
surprise there today I'm going to explain the filter method in JavaScript the
filter method creates a new array by filtering out elements in this example we'll
create an array of
273:22
numbers we will filter out any numbers that are odd let's add the numbers 1 through
7 now we need a function function is even we have one parameter we have an element
that's going to be
273:39
provided to us by the filter method we are going to return then write a condition
we will take our element modulus 2 the modulus operator gives you the remainder of
any division you can
273:53
use modulus 2 to check to see if a number is even if this condition is zero
strictly equal to zero then we will return true we will be returning a Boolean true
or false the filter method
274:08
will take any values that return true and stick them within a new array which will
effectively filter out any elements we don't need that don't return true let's see
if this works I will create a
274:18
new array even nums equals take our original array use the filter method pass in a
call back is even we will display [Link] our new new array even numbers and
there we are 2 4 6 let's do
274:41
this with odd numbers function is odd take our element modulus 2 is this strictly
not equal to zero that means the number is odd let's create a new array let odd
nums equals our original array numbers
275:04
do use the filter method passing a call back is odd let's check out our new array
odd nums there we are we have the numbers 1 3 5 7 any numbers that are odd let's go
over another
275:20
example I will create an array of Ages I'll use const this time instead of let
const ages Pretend We're teaching a college class we might have some students still
in high school let's say
275:33
a student is 16 another is 17 two or 18 19 20 and then we have somebody that's just
a little bit older they're um 60 we'll use the filter method to filter out anybody
that is under 18 we
275:48
will find all of the adults we will need a function function is adult we have one
element as a parameter that's going to be provided to us we will return a condition
return
276:05
check our element is it greater than or equal to 18 so that's our function let's
create a new array of adults equals take our original array dot use the filter
method pass in a call back is adult then
276:26
display our new array [Link] adults we have five elements the age of the
students is 18 18 19 20 and 60 let's do this with is children to find anybody
that's under 18 is child
276:45
function return element less than 18 we'll create a new array const children equals
take our original array use the filter method passing a call back is child then
display the new array we have
277:05
two students that are children one is 16 the other is 17 last example we'll create
an array of words const words add some words I think I'll add some fruit I'll add
an apple orange banana kiwi
277:32
pomegranate and a coconut I will filter out any words where the length of that word
is above six so we will create a function function get short words we have an
element as a
277:51
parameter we will return a condition we will check if our element access the length
property of that element they're strings so they all have a length property how
many characters are they
278:03
long that's the length check to see if the length of this element is less than or
equal to six if it is return true if not return false we will create a new array
let's
278:16
call this array short words equals take our array use the built-in filter method
pass in a call back get short words then we will console. log the new array short
words in our array there are four
278:34
elements with the length of the characters of each string is six or under Apple
orange banana kiwi then to finish this off let's get any long words we'll create a
new
278:45
function get long words check the length of the element to see if it's above six
then we will create a new array const long words equals take our original array use
the filter method pass in a
279:03
call back get long words then we will display our new array long words within our
original array there's two words that are considered long pomegranate and coconut
these words each
279:15
have more than six characters coconut is seven pomegranate is 11 all right
everybody that is the filter method it creates a new array by filtering out
elements your callback is likely going
279:28
to checking condition does each element pass this condition and well everybody that
is the filter method in Javas script what's going on everybody so in today's video
I got to explain the
279:41
reduced method in JavaScript the reduce method reduces the elements of an array to
a single value in this example we'll create an array of prices as if it was a
shopping cart we'll sum all of the
279:53
prices within our shopping cart and return a total we'll need an array to work with
const prices equals an array think of some prices type in anything as as long as
it's a number I'll keep this
280:06
simple and use whole numbers I'll add something that is $5 another that is 30 10 25
15 and 20 we will create a variable for a total const total equals take our array
of prices we will use the built-in
280:26
reduce method of arrays but we do need to pass in a call back to a function we need
to create a function that will sum all of these values let's create a function to
sum our sum function will have two
280:43
parameters the first will be an accumulator the second will be the next element all
we're going to do is return our accumulator plus our element I'll explain how this
works momentarily I
280:59
just want to be sure that everything runs fine first within the reduce method we'll
pass in a call back to the sum function that will return a single value a total in
this case let's see what our
281:10
total is [Link] I'll use a template string pick a unit of currency I'll pick
American dollars add a placeholder let's display our total so my total is $15 if
you would like to add cents to
281:27
the end of that you can follow this with the two fixed method then add two decimal
places for sense all right so how does this work exactly we have two parameters
accumulator and element it
281:42
might be easier if I were to rename these parameters you can rename parameters
let's say accumulator is the previous element element is the next element we're
returning the previous element
281:57
plus the next element during the first iteration we'll have 0 and five well 0 + 5
would give us 5 five is returned to the accumulator whatever value is returned
becomes the accumulator during
282:13
the next iteration so now our accumulator is five the next element is 30 then we
are going to return the accumulator + 30 which is 35 we'll return this to the
accumulator during
282:30
the next iteration the accumulator is now 35 the next El element is 10 35 + 10
would give us 45 return that to the accumulator and add the next element 25 so you
just follow that
282:50
pattern all right let's go over another example we'll create an array of grades
const grades equals these will be some number grades 75 50 90 80 65 and 95 we'll
find the maximum value from this
283:11
array we'll create a constant to hold the maximum value what is the maximum score
const maximum equals take our grades array use the built-in reduce method then we
need to pass in a call
283:25
back to the reduce method we need a function to get Max there's two parameters an
accumulator and the next element like I said feel free to rename them we will
return the
283:42
max method of math math. Max pass in these two parameters accumulator and the next
element within the reduce method we'll pass in a call back to get Max the value
returned will be the
283:59
maximum grid from this array so let's [Link] whatever the maximum is the
maximum score from this array is 95 let's do this with the minimum let's copy this
function change any instance of Max to
284:19
Min get Min math. Min let's create a new constant const minimum equals our array of
grades use the reduce method to return a single value then passing a call back to
get min let's [Link] the
284:42
minimum the minimum score from this array is 50 all right everybody that is the
reduce method it's a built-in method of arrays to reduce the elements of an array
to a single value you can use it
284:55
to sum the elements of an array another possibility is to find the minimum or
maximum value from an array and well everybody that is the reduced method in
JavaScript hey everyone so today I'm
285:09
going to explain function expressions in JavaScript a function expression is a way
to define functions as a value or a variable not to be confused with function
declarations where you define a
285:21
block of reusable code that performs a specific task we're already familiar with
function declarations such as this function then you create a function name such as
hello in this example let's
285:35
[Link] the word hello with the function expression we can assign a function to
a variable or pass it as a value to another function so this time we're going to
write a function expression I will
285:49
create a constant named hello equals a function parentheses curly braces we'll do
the same thing we will [Link] hello and if I were to run this the identifier
hello has
286:04
already been declared so for now I'm just going to remove this function declaration
all we're doing is assigning a function to a variable to use the function that's
stored within we have to
286:14
take our variable name and add a set of parentheses to invoke it kind of like it's
a pair of telephones talking to each other hello using JavaScript we also have the
capability of passing a
286:25
function as a value I will introduce the set timeout function there's going to be
two parameters a call back to a function and an amount of time we're going to wait
then execute
286:40
this function this will be in Mills 3,000 milliseconds translates to 3 seconds let
me put this function back after 3,000 milliseconds I will execute the hello
function 1 2 3 hello instead of using a
286:58
function declaration we are going to pass a function expression as an argument to
the set timeout function instead of a call back we will create a function we will
pass an entire function
287:10
as an argument what are we going to do we will after 3 seconds [Link] thee
word hello and let's see if this works just to prove that I'm not a liar 1 2 3
hello in JavaScript it is
287:29
legal to pass an entire function as an argument or treat it as a value we'll use
previous examples of the map filter and reduce methods of arrays I will create an
array const
287:42
numbers equals the numbers 1 through six 1 2 3 4 5 6 I would like to square each of
these numbers what we've done in a previous lesson is declare a function function
287:58
Square we had one parameter in that example we had an element what we did is we
returned [Link] to raise a base to a given power we're raising our element to the
288:12
power of two the map method will return a new array const squares equals numbers.
map we're passing in a call back to square then [Link] squares this works we
are using a function
288:38
declaration but this time we will now use a function expression we will treat this
function as a value let's cut this function replace the call back then paste it
within the map method
288:53
then we just need to remove the name we don't need a name and this is still going
to work yeah it still does we don't necessarily need to think of a function name
one of the benefits of doing this
289:05
is that we're not polluting the global Nam space with function names we're only
going to be using this function once there's no need to declare a function let's
create a function expression to
289:15
cube these numbers now as a beginner it might be helpful to write out your
functions as a declaration first then transform it into a function expression
function Cube we have our element as a
289:29
parameter I'm going to copy this return [Link] element to the power of three we
will create a new array const cubes equals numbers. map we don't need to pass in a
call back we will cut this entire
289:50
function paste it within the map method then we don't need the name then
[Link] cubes there are all the original numbers cubed all right I think we're
starting to get the hang
290:02
of this let's quickly use the filter method to filter out any even or odd numbers I
will create const even nums equals take our array numbers we will use the filter
method then we will pass a function
290:19
expression as an argument there's one parameter an element we are going to return
element modulus 2 to see if it's divisible by zero is is the result strictly equal
to zero let's see if this
290:38
works [Link] even nums there they are we have 2 46 let's do this with odd
numbers odd nums use the filter method again all we're going to change is strictly
not equal to zero return any odd
290:57
numbers 135 then lastly reduce we will sum all of the elements of the array const
total equals our numbers do reduce pass in a function expression we have two
parameters an accumulator and an
291:24
element we will return accumulator plus our element return the total which is 21 we
already do have some practice with map filter and reduce instead of using function
declarations than passing a
291:42
call back we can pass an entire function expression as an argument to these methods
in the next topic I'll discuss Arrow functions which shortens the syntax even
further you'll like Arrow
291:53
functions all right everybody so those are function Expressions they are a way to
define functions as a value or a variable we've both defined a function expression
as a variable we stored that
292:05
within this hello variable we've also passed entire functions as an argument which
you can do with JavaScript there's a few benefits of function Expressions one of
which is you don't need to keep
292:15
on thinking of function names you can perform a function once then just forget
about it they're also used in callbacks and asynchronous operations higher order
functions closures and event listeners
292:26
these are topics we still need to discuss but we will be using function Expressions
a lot don't worry we will have more practice and well everybody those are function
expressions in
292:38
JavaScript hey hello there so today I'm going to explain Arrow functions in
JavaScript an arrow function is a concise way to write a function expression it's
good for simple
292:49
functions that you only use once here's the formula you have your parameters Arrow
then some code you would like to perform here's an example suppose I have a
function declaration I have the hello
293:02
function I'll work going to do is [Link] the word hello to use this function I
need to call it by its name add a set of parenthesis this will display the word
hello a concise way to
293:15
write the same function is to use an arrow function we'll begin with a function
expression then convert it to an arrow function just so we understand the
differences this time I will create
293:25
a constant hello hello is going to be a constant that stores our function
expression if I were using a a function expression we would say function
parenthesis curly braces then the code
293:39
we want to perform [Link] the word hello this would do the same thing hello a
more concise way to write this function expression would be to use an arrow
function following this formula we list
293:57
our parameters we don't have any we need a set of parenthesis Arrow then some code
we would like to perform I'm going to [Link] the word hello and that works
we're sticking an arrow function
294:12
within a variable or named constant to invoke the arrow function within we just
follow that constant or variable with the set of parentheses like we're calling it
as if it's a pair of
294:22
telephones talking to each other you can send some arguments to an arrow function
we'll need to set up the parameters I will have a name parameter within our code
let's [Link]
294:34
I'll use a template string hello add a placeholder add my name parameter now I need
to pass in an argument because right now it's hello undefined pass in your first
name as an
294:48
argument hello bro within your code if you need to include more than one statement
you'll need to enclose all of that code within a set of cly braces let's add a new
line console log you are
295:07
old hello bro you are old okay let's set up another parameter this time we will
accept an age argument let's transform our second [Link] to be you are at a
placeholder our parameter age years
295:29
old now we'll pass in a second argument for age hello bro you are 25 years old so
that's the basics of an arrow function you have your parameters Arrow then some
code you
295:41
would like to perform there's no need to create a function declaration let's go
over another example we have the set timeout function this function accepts a call
295:53
back then a given amount of time we are then going to execute this code this
callback after 3 seconds 3,000 milliseconds I will execute whatever this call back
is let's create a
296:06
function to say hello again function hello we will [Link] the word hello I
will pass in a call back after 3 seconds we say hello in place of a callback I
could
296:25
use a function expression let's cut our function remove this argument then paste
our function expression remember we don't need the name for a function expression
this works as
296:41
well hello or otherwise we can use a more concise Arrow function we will pass that
as an argument we have our parameters we don't have any Arrow then some code
[Link] the word hello after 3
296:59
seconds we display the word hello now we'll use Arrow functions with map filter and
reduce we have an array of numbers const numbers equals the numbers 1 through six
let's start with using the map
297:20
filter to square each of these numbers but we will use Arrow functions const
squares equals our original array number numbers. map normally we would pass in a
callback as an argument but we're not
297:39
going to do that we'll use an arrow function we have one parameter an element arrow
take each element use [Link] to raise our element to a given power then let's
[Link] our
298:00
squares [Link] squares there they are here are all the original num squared 1
4 9 16 25 36 let's Cube each number const cubes raise our element to the power of
three [Link] are
298:22
cubes there are all the numbers cubed we'll use the filter method to filter out any
numbers that are odd const even nums equals rray numbers we will use the filter
method we
298:40
can pass in a call back but we don't need to we will pass in an arrow function we
have our element as a parameter Arrow we don't necessarily need a return statement
if we have only one line of
298:56
code take our element modulus 2 is it divisible by two and does the strictly equal
Z if it does it's an even number let's [Link] our even numbers 2 46 let's do
this with odd numbers odd
299:17
nums take our element modulus 2 is it strictly not equal to zero display our odd
nums 1 35 and lastly let's do reduce we will get a total by summing all all the
elements of this array const total
299:36
equals our original array reduce pass in a call back or an arrow function this time
we have two arguments an accumulator and an element we have an Arrow return our
accumulator plus our
299:58
element then display the total our our total is 21 all right everybody so those are
Arrow functions they're a concise way to write a function expression they're good
300:10
for simple functions that you only use once you list your parameters within a set
of parentheses an arrow then some code you would like to perform in this example
we've written a more concise way
300:23
to use the map filter and reduce methods normally we can pass in a call back as an
argument a function expression or an arrow function and well everybody those are
Arrow functions in
300:39
JavaScript hey what's going on everybody in today's video I'm going to discuss
objects in JavaScript an object is a collection of related properties and or
methods properties are things that an
300:51
object has such as a first name or an age a method is a function that belongs to an
object for example I have a person object our person can say hello and they can say
by methods are just functions
301:05
that belong to an object what can this object do objects can represent Real World
objects such as people products or places in this example we'll be creating some
people objects people from the show
301:18
SpongeBob we'll start from scratch though we'll create a person object I'll use a
constant although it's not necessary const person equals then add a set of curly
braces we'll start with any property
301:32
properties you can add as many properties as you would like they're in key value
pairs this person will have a first name key colon then some value this person's
first name will be
301:46
SpongeBob separate each key value pair with a comma let's include a last name
property last name colon space will be Square Pants add a comma when you're done
with this key value pair We'll add
302:00
an age property of 30 age has a different data type it's a number the first two in
my example were both strings SpongeBob and Square Pants let's add a Boolean is
302:14
employed col in space I will set that to be true he has a job at the Crusty Crab
okay that's good enough for now I would like to access these properties let's
[Link] if I need one of these
302:28
properties take the object you're referring to in this case person dot the name of
the property let's do first name person. first name property that would give me
SpongeBob let's do this with
302:41
last name take the object name dot the name of the property person. last name is
SquarePants let's do this with age person. AG is 30 person. is employed is set to
true all right let's
303:01
create another object we'll create an object for Patrick const person now objects
can't have the same name objects need different names for example I can't have two
person objects they can't have the
303:15
same name syntax error identifier person has already been declared I will rename
our first person as person one our second person will be person two then any place
in which I'm referencing
303:28
person will now need to be person one let's reuse these same key value pairs person
two's first name will be Patrick his last name will be star Patrick will be I don't
know how old he
303:44
is according to the TV series let's say he's 42 is Patrick employed no he just
watches TV all day now I would like to access person 2's properties okay well
[Link] person 2's first name person
304:02
2's last name Person 2's age person two is employed okay for person two we have
Patrick Star 42 false so those are properties of an object they're key value pairs
add as
304:18
many as you would like in this example these properties mimic real world attributes
that a person might have like a first name last name age whatever you can think of
but not only that objects
304:29
can have dedicated functions that we refer to as methods what sorts of actions can
these objects perform for example a person could eat they could drink they could
sleep what sorts of
304:41
things do people do so just to keep this simple I am going to create a function to
say hello we'll start with person one say hello col in space this will be a
function
304:56
expression what are we going to do when we invoke this function let's [Link]
what would SpongeBob say if he's greeting somebody hi I'm SpongeBob be sure you're
not including a
305:12
semicolon at the end that should work let's test it I'm going to have person one
invoke their say hello method hi I'm SpongeBob let's add a say hello method to
Patrick person two
305:33
we'll change the output if say hello what would Patrick say hey I'm Patrick dot dot
dot now we'll have person two use their say hello method hey I'm Patrick you can
add as
305:50
many methods as you would like so with these functions we're using a function
expression if you prefer you could even use an arrow function list your arguments
Arrow then the code you would
306:03
like to perform this would work too let's add an eat method eat function we'll use
a function expression for SpongeBob let's console. log what is SpongeBob eating I
am eating a crabby
306:26
patty we'll include an eat function for Patrick as well what's Patrick going to eat
Patrick is eating I'm eating roast beef chicken and pizza and if you would like you
can use
306:44
an arrow function for this example list your parameters Arrow then the code you
would like to perform it's not necessary but I do like Arrow functions person one
SpongeBob
306:57
will use his eat method same thing goes with Patrick person two so SpongeBob is
eating a crabby patty Patrick is eating roast beef chicken and Pizza all right
everybody so JavaScript
307:11
objects are a collection of related properties and or methods properties are what
an object has methods are functions that an object can perform they can represent
Real World objects such as
307:25
people products or places properties are key value pairs methods are functions that
belong to another object and well everybody that is an introduction to object-
oriented programming in
307:39
JavaScript hey so we got to talk about this this is a keyword it's a reference to
the object where this is used the object depends on the immediate context if we had
a person object and we're
307:53
accessing their name property we could replace person with this as long as we're
within the context of that person object we'll create an object const person one
let's add a property for name the
308:08
name will be SpongeBob and a favorite food property fave food SpongeBob likes
hamburgers more specifically Krabby Patties I will give SpongeBob a say hello
method this will be a
308:26
function all we're going to do is [Link] I'll use a template string hi I am
I'll use a placeholder let's attempt to use person one's name let's see what
happens let's take our object of person
308:45
one I will invoke their say hello method let's see what happens hello I am and
there's nothing here for the name inside of this object of person one if I would
like to access one of these properties
309:01
I'm going toe received the property with this this do the name of the property and
that should work hi I'm SpongeBob we're using this within the context of person one
it would be like
309:15
us saying person one. name there would be no difference this is a reference to the
object we're within if I said this do favorite food well favorite food for short hi
I am hamburgers it would be
309:32
like like us saying person one. fave food let's add another method I will add an
eat method let's [Link] I'll use another template string add a placeholder
[Link] is eating add another
309:58
placeholder this. fave food let's have person one use their eat method SpongeBob is
eating hamburgers the cool thing about the this keyword is that if we create a new
object with
310:14
these same methods we'll use the second object's properties let's copy person one
paste change person one to person two the name for person two will be Patrick
favorite food will be
310:29
Pizza let's have person two use their eat method SpongeBob is eating hamburgers
Patrick is eating pizza since we're in the context of person two now imagine we're
replacing this with person
310:44
two person 2.n name Person 2. fave food if you were to use this outside of any
objects I'm going to [Link] this what we're returned with is a window object
basically we're returning
311:02
the window to see our website technically we're inside of an object already our
window object and we have all of these properties but since we're using the this
keyword inside the context of
311:15
person one and person two we'll instead make a reference to those objects hey one
thing I forgot to mention the this keyword doesn't work with arrow functions for
example with person two
311:27
let's convert this to an arrow function blank is eating undefined when you use this
within an arrow function it's making a reference to that window object still our
window object does have a name
311:45
that's why it's appearing empty but fave food is undefined because our window
object doesn't have a favorite food property all right everybody so that is the
this keyword we will be using this
311:56
keyword a lot all it is is a reference a reference to the object where this is used
and that is the this keyword in JavaScript what's up people so today I got to
explain Constructors in
312:10
JavaScript a Constructor is a special method for defining the properties and
methods of objects in Prior videos we've constructed objects like this we would
declare an object assign it some
312:22
properties and some methods you know this works but what if we have to create a lot
of objects here I'm manually creating three different car objects that can be a lot
lot of work what we
312:33
could do instead is use a Constructor to construct these objects automatically all
we have to do to construct these objects is passing some unique data to the
Constructor to construct these
312:43
objects here's an example we are going to create a function car do pay attention to
the capitalization we'll need to set up some parameters what sorts of properties
will
312:56
we accept when we construct a car object how about a make model year and color
these are arguments we'll receive when we construct a car object to assign these
properties we're going to use the
313:12
this keyword doake equals the make that we receive let's do this with model this
dood model equals the model we receive this doe equals year this do color equals
color
313:32
that's good enough for now our car Constructor is a reusable method where we can
define the properties and methods of objects we create to use this Constructor I
will create an instance of an
313:44
object I will use const car1 will be our first object equals we'll need to use the
new keyword type the name of the Constructor car car is a special method we'll need
to pass in some arguments
313:58
we'll need a make model year and color in that order my first car feel free to send
some different data to the Constructor but for me my first car will be a Ford make
sure each value is comma
314:12
separated Mustang the year will be 2024 and the color will be red we should now
have a car object with the name of car one and I'm going to console. log car 1's
properties car 1.
314:29
make Ford let's do this with the other properties we have model Mustang year 2024
and color red now this method is reusable we can reuse it to create other car
objects let's create const Car 2 equals
314:55
new car we'll pass in different data this time the make will be Chevrolet I will
pick a Camaro the year 2025 and the color will be blue now I can display car 2's
315:13
properties let's select car 2make car 2. model car 2. year car 2.c color we have a
Chevy Camaro year 2025 the color is blue let's create one more car same process as
before const car 3 equals new
315:33
car I'll go with a Dodge Charger the year 2026 and the color will be silver let's
access K 3's properties car 3. make car 3. model car 3. year car [Link] Dodge Charger
2026 the color is
315:55
silver another thing with these parameters too you can name these parameters
anything when we assign these properties it can be kind of confusing like this.
make equals make really we
316:05
write our Constructors this way just for readability technically this would work if
we renamed our parameters for example make will be parameter a model will be B year
is C color is D then be sure to
316:18
change these when we assign them A B C D this would still work however this
Constructor isn't as readable like what the heck is a b c and d it would be good
practice to clear clearly Define our
316:32
parameters for readability purposes all right now let's add a method we'll take
this. Drive equals a function we [Link] I'll use a template string you drive
the I'll add a placeholder this do
317:00
model With Cars 1 through three let's use the drive method car 1. drive you drive
the Mustang car 2. drive you drive the Camaro and car 3. drive you drive the
charger all right
317:20
everybody so that's a Constructor it's a special method for defining the properties
and methods of objects it helps with code reusability we can reuse it to create
many objects instead of
317:31
having to type them all out manually and well everybody those are Constructors in
JavaScript all right let's do this thing so I got to talk about classes and
JavaScript classes are an es6 feature
317:45
that provides a more structured and cleaner way to work with objects compared to
the traditional Constructor functions that we're normally used to classes are going
to be really helpful
317:55
when we reach future topics such as the static keyword encapsulation and
inheritance in this example I have a Constructor for a product our product needs a
name and a price for example we
318:07
have a shirt and the price is 1999 instead of using a Constructor method we're
instead going to use a class our class will include a Constructor so let's start
from the
318:19
beginning to create a class you type class then the name of the object so our class
is going to serve as a blueprint our objects will be products then add a set of
curly BRAC
318:32
to use a Constructor we can use the Constructor keyword within our class list any
parameters we will have a name and a price for each product we will assign the
properties of [Link]
318:46
equals the name parameter that we receive this. price equals price I will also
create a function our function will be display product now in inside of a class you
don't need to use the function
319:04
keyword when we would like to display this product we will [Link] product
colon space I'll include a placeholder [Link] let's also output the price price
pick a unit of currency I'll
319:24
use American dollars this do price let's create some product object objects const
product one equals to create a new object we have to use that new keyword the name
of the class
319:41
product The Constructor is going to be called automatically but we do need to pass
in a name and a price as arguments we will pass in a shirt the price will be $19.99
just to be sure that everything
319:57
works let's invoke the display product method product one do display product method
here are the details of our product object product shirt priced $19.99 let's create
a few more so this class is
320:17
reusable product two will be pants I'll pick 2250 for the price let's display
product two product two and we will use use the display product method of our class
product pants the price is
320:37
$22.50 uh looks like I only have one decimal point I'm going to make one change
after the price I will use the two fixed method and set this to be two decimals
there 2250 all right product three const
320:54
product 3 equals new product our third product is going to be underwear this
underwear is really expensive it's $100 it's really good underwear guys product 3.
display product product underwear price
321:13
$100 here's a challenge round I'm going to add another method this method will have
one parameter sales tax we'll create a method to calculate a total including tax so
let's create a new
321:25
method inside of a class we don't need the function keyword calculate total there
will be one parameter sales tax all we're going to do is return this. Price Plus to
calculate the sales
321:43
tax we'll take this. price times the sales tax assuming it's a percentage okay
let's display product one product one. display product I'm also going to create a
constant for the
321:58
sales tax that's not going to change const sales tax let's say the sales tax is 5%
0.05 I will create a variable const total equals let's take product one use the
calculate total method but we have
322:19
to pass in sales tax we can either pass in this number or this variable once we
have our total let's display it [Link] I'll use a template string total price
in parentheses with tax I'll add a
322:43
placeholder display the total pick a unit of currency I'll use American dollars
then I'll add two fixed two to set it to two decimal places all right our product
is a shirt
322:56
price is $1 199.99 total price with tax is $20.99 9 let's do this with product two
product two. display product product two. calulate total pants 2250 total price
2363 let's check out our really
323:14
expensive underwear product 3. display product product 3. calculate total our
underwear is $100 including sales tax it's $115 all right everybody so those are
classes they're an es6 feature that
323:30
provide a more structured and cleaner way to work with objects compared to the
traditional Constructor functions that we learned about in the last video classes
are going to be really helpful
323:40
with a few upcoming topics and well everybody those are classes in JavaScript hey
people let's do this thing so the static keyword static is a keyword that defines
Properties or
323:53
methods that belong to a class itself rather than the objects created from that
class in summary a class own own anything static not the objects so what we're
going to do is create a class for math
324:06
utilities class math util for short we'll create our own version of Pi we'll use
the static keyword the name will be Pi Pi will equal 3.14159 just the first few
digits I'm
324:24
going to zoom in a little if I would like the static property I have to access it
by its class so let's console llog the name of the class math util dot the name of
the property Pi our static
324:42
property is 3.14159 I don't need to create an object in order to use this property
I don't have to type const math UIL one equals new math youtil I would have to type
math util
325:00
one that's the name of this object in order to access Pi all I have to do is type
the name of the class and that's pretty convenient anything declared as static
belongs to
325:11
the class itself and not any object created from that class so now we're going to
create a static method we'll use the static keyword we'll get a diameter once we
pass in a radius as an argument get
325:26
diameter we have one parameter a radius all we're going to do is return radius time
2 okay let's console do log again we have to type the name of the class Matthew
till dot the name of the method get
325:47
diameter we have to pass in a radius though let's pass in 10 our diameter is 20
let's create a new static method for get circumference get circumference the
formula is going to be
326:06
we will be returning 2 times this meaning Matthew till. pi times the radius we
receive let's [Link] let me make the C Capital the name of the class Matthew
till dot get circumference pass in a
326:36
radius the circumference is 62.83 let's create one more for get area static get
area we need a radius we will return this Pi time radius time radius so that's Rus
squared
327:06
[Link] Matthew till the name of the class get area pass in 10 and the area is
31415 in the next example we'll have a mix of regular properties and methods and
static properties and methods this
327:23
will be example two we'll create a class of users class user we'll create a static
variable to keep track of the amount of users we create user count I will set that
equal to zero I'll include a
327:44
Constructor let me just space this out a little our Constructor is going to be
automatically called when we instantiate a new object we need one argument though
when we create a new user we need a
327:57
username once we have our username we will assign this do username equals username
not only that but when we create a new user I'm going to increase our user count by
one just so we can
328:13
keep track of how many users we create so inside of the Constructor you can write
additional code it's not only for assigning properties let's take user do user
count Plus+ to increment
328:29
it let's create some user objects const user one equals new user pass in a username
I'll pass in SpongeBob then let's [Link] user one's username which is
SpongeBob let's attempt to access user
328:55
one's user count with user one's user count we get undefined that's because our
user doesn't have user count as a property it's static that means it belongs to the
329:08
class not any objects created from the class to access user count we have to type
the name of the class user in this case we have one user let's see what happens
when I create a new user
329:23
object user 2 will equal Patrick our user count is now two let's display user 2's
name yep we have SpongeBob and Patrick the total user count is two let's create a
third user user three will be Sandy
329:46
[Link] user 3. username our user count is now three we have a static property
that's keeping track of the amount of users we create let's create a method the
first one will not be static say
330:04
hello all we're going to do is [Link] I'll use a template string hello my
username is I'll add a placeholder this do username let's have user one use there
say hello method
330:31
same thing with user two and user three hello my username is SpongeBob Patrick and
Sandy now we'll create a static method we'll get the user count get user count
[Link] I'll use a template
330:57
string there are I'll add a placeholder user. user count users online now in order
to access this method I have to type the name of the class user. getet user count
oops and I can't conso that log
331:24
that user. getet user count there are three users online all right everybody so
that is the static keyword it defines properties and methods that belong to a class
itself
331:37
rather than any objects created from that class in summary the class owns anything
static not the objects and well that is the static keyword in JavaScript hey what's
up everybody so in
331:52
today's video I got to explain inheritance inheritance allows a new class to
inherit properties and methods from an existing class these two classes have a
parent child relationship a child
332:03
will inherit properties and methods from a parent it's kind of like a family tree a
child will inherit genes from a parent inheritance helps with code reusability
because we don't need to keep on
332:14
repeating the same properties and methods if all the children share them here's an
example we'll create an animal class class animal will have a property of alive if
332:26
you're an animal you start off being alive all animals should be able to eat and
sleep we'll create methods for those we'll have an eat method all we're going to do
is [Link] I'll use a template
332:42
string this now I'll add a placeholder this do name is eating and a Sleep Method
sleep this [Link] name is sleeping animal will be the parent class we'll create
children classes that
333:07
inherit these properties and methods let's create a few children classes class
rabbit our rabbit class will inherit all the properties and methods of the animal
class to declare a parent
333:19
child relationship the child will extends the parent animal for the rabbit I'm
going to give this class A Name name equals rabbit this will be a property if
you're familiar with the
333:35
static keyword you can make the static now we'll create a fish class that also
extends animal class fish extends animal fish will have one property name equals
fish and a hawk class class Hawk
333:58
extends animal will have one name property Hawk all right let's see if this works
if we create a rabbit fish and Hawk object they should have access to these
properties and
334:15
methods let's create const rabbit equals new rabbit const fish equals new fish
const Hawk equals New Hawk all right let's see if our rabbit has an A Life Property
334:44
[Link] take the name of the object rabbit do access a property or method alive
that's our property the rabbit is alive but what if the hawk swoops in and kills
the rabbit let's change the alive
334:58
property of the rabbit rabbit. alive equals false the rabbit is no longer alive now
let's see if our rabbit has access to a eat and Sleep Method rabbit. eat this
rabbit is eating and sleep rabbit.
335:23
sleep the rabbit is sleeping Let's test this with fish fish. alive fish. eat method
fish. SLE method the fish is alive the fish is eating the fish is sleeping and Hawk
hawk. alive hawk. eat
335:41
method hawk. SLE method the hawk Is Alive the hawk is eating the hawk is sleeping
our children classes of rabbit fish and Hawk all inherited the properties and
methods of the parent
335:53
animal class this helps with code reusability because I don't need to declare all
of these properties and methods within each of the children classes like this we're
saving a lot of lines of code
336:07
it's not that apparent with just a few child classes but imagine if you had
hundreds of different child classes well by using inheritance you would be saving a
lot of time but not only that the
336:18
children can have their own unique properties and methods too for example rabbits
will be able to run but fish and Hawks can't run that's a method that only belongs
to rabbits within our
336:30
rabbit class let's create a new method a run method we'll [Link] I'll use a
template string this add a placeholder [Link] is running within our fish class
let's create a swim method
336:56
swim this this.n name is swimming and Hawks will be able to fly we'll create a fly
method this this do name is flying let's minimize these classes let's take our
rabbit object
337:18
display the alive property the eat method the Sleep Method and the run method
rabbit. run method the rabbit is eating the rabbit is sleeping the rabbit is
running
337:30
now let's do this with fish fish. alive fish. eat method fish. SLE method now does
the fish have a run method it does not fish. run is not a function run is a method
that belongs to the rabbit class
337:46
fish can't run because well they don't have legs we did not give our fish class a
run method they can swim though but they can't run fish. swim method the fish is
swimming let's do this with Hawk
338:03
our Hawk cannot swim but it can fly we'll use the fly method the hawk is eating the
hawk is sleeping the hawk is flying and of course our rabbit can't fly or Swim does
our rabbit have a fly method
338:19
it does not rabbit. fly is not a function all right everybody so that's inheritance
it allows a new class to inherit properties and methods from an existing Class A
Child inherits
338:31
properties and methods from a parent it helps with code reusability I don't need to
declare all of these properties and methods for each of these classes I can simply
reuse it that helps us follow the
338:41
dry principle don't repeat yourself and well everybody that is an introduction to
inheritance in JavaScript yo what's going on everybody so in today's video I'm
going to explain
338:57
the super keyword in JavaScript super is a keyword that's used in classes to call
the Constructor or access the properties and methods of a parent the parent is also
known as the super class it's very
339:09
similar to the this keyword this refers to this object super refers to the parent
of that object here's an example we'll use inheritance to create a parent class of
animal class animal our animal
339:24
class will have three children also known as sub classes class rabbit extends
animal class fish extends animal class Hawk extends animal we'll add an empty
Constructor for now for the animal
339:47
class then we need a Constructor for the rabbit class so rabbits they'll have a
name property a and a run speed we'll assign these properties within the
Constructor [Link] equals the name that we
340:07
receive this. AG equals age this. runp speed equals run speed let's copy this
Constructor now with fish fish don't have a run speed but they'll have a swim speed
let's replace run speed with swim
340:26
speed copy The Constructor again paste it Hawks in this example won't have a swim
speed they'll have a fly speed though replace swim speed with fly speed now let's
attempt to create some of
340:39
these objects const rabbit equals new rabbit we need a name for this rabbit you
could just say rabbit or if you want to be creative you could say something like
Bugs Bunny uh but let's just stick with
340:54
rabbit to keep it simple our rabbit will be Oney old and has a run speed of 25 mph
if you use kilm feel free to use kilom let's do this with fish const fish equals
new
341:11
fish the name of our fish will be fish our fish is 2 years old and has a swim speed
of 12 mil hour then with Hawk const Hawk equals New Hawk our Hawk will have a name
of
341:27
Hawk our Hawk will be 3 years years old and has a fly speed of 50 mph so when I run
this program we have an uncaught reference error must call Super Constructor in
derived class
341:39
before accessing the this keyword so what JavaScript is telling us is that before
we can use the this keyword we have to call the Constructor of the parent the super
class within each of
341:50
these respective Constructors we will invoke the Constructor of the parent the
super class with the super keyword so let's do that for for each of these
Constructors now our program actually
342:03
runs now so one of the benefits of using Constructors is that if there's any
properties that the children all share in common we can send them to the
Constructor of the parent as you can see
342:14
we're repeating ourselves a lot each of these children classes has a name and age
property that we're assigning to each we would like to follow the dry principle
don't repeat yourself so why
342:25
don't we write this code once and reuse it so within the Constructor of the parent
will accept a name and age property we'll assign [Link] equals name and this. AG
equals age now we can
342:40
remove that within each of the child classes so we don't repeat ourselves there's
less code to right now but we do need to pass in these arguments to the parent
Constructor name and age for each
342:59
and that's all there is to it in this example when we construct an object either a
rabbit a fish or a hawk we'll accept three arguments a name age and either a run
speed a swim speed or a fly
343:11
speed depending on the animal that we're creating any properties they share in
common we can send to the parent Constructor it helps with code reusability and
there's a lot less to
343:20
write it's not that evident with three children classes but imagine if you had
hundreds of different classes like what if this was Pokémon there's like what a,
Pokémon now we would have to copy and
343:31
paste those properties like a thousand times for each if we're constructing
individual Pokémon but since all of them share those same properties we can write
it in one place and make any changes
343:42
only in one place so let's test this to see if it works let's [Link] our
rabbit's name which is named rabbit let's [Link] the rabbit's age the rabbit
is Oney old
344:00
and let's see if the rabbit has a run speed 25 as in 25 mph let's do this with fish
fish. name fish. AG let's see if the fish has a run speed name is fish Age Two run
speed is
344:14
undefined because fish can't run because they don't have legs but they do have a
swim speed though swim speed 12 milph then Hawk hawk. name hawk. AG hawk. flyp
speed name is Hawk age 3 the
344:29
hawk has a fly speed of 50 mph so that's how you can use the super keyword in a
class to call the Constructor of the parent it helps with code reusability any
properties that the
344:40
children share in common in this case a name and Age The Constructor of the parent
can take care of that we don't have to repeat the set of code every single time for
each child we write it
344:50
in one place and reuse it another thing you can do too with the super keyword is
extend a method from the parent so what we're going to do within the animal par
class is create a move
345:01
method within this method we will [Link] the following message the at a
placeholder [Link] moves at a speed of add a placeholder speed mph for miles per
hour
345:23
or if you prefer you can use kilometers our move method will have one parameter a
speed that we need to pass in to use So within each of these children classes we'll
write a method that also extends
345:36
the move method of the parent rabbits will have a run method we'll output the
following message [Link] I'll use a template string this add a placeholder
[Link] can
345:56
run let's copy our run me method paste it for fish but change swim to run because
fish can't run this [Link] can swim then with Hawks they'll have a fly method
fly this this. name can
346:18
fly with our rabbit object let's invoke the run method this rabbit can run let's do
this with fish fish. swim this fish can swim and hawkfly Method this Hawk can fly
346:36
within each of these children classes we're going to extend the move method of the
parent animal within the run method of our rabbit class not only are we going to
Output this
346:47
message we'll also extend the move method of the parent and display that message as
well to refer to the parent class we use the super keyword it's very similar to
this but it means the parent
346:59
use the parents move method but we do have to send a speed argument let's send the
Run speed of the rabbit this. runspeed let's do this with our fish class we'll
extend the move method
347:15
super. move send in this. swim speed and Hawk super. move this. flype speed now
let's take our rabbit use the run method and we should extend the move method this
rabbit can run the rabbit
347:33
moves at a speed of 25 mph let's do this with fish fish. swim the fish can swim the
fish moves at a speed of 12 mph and hawk hawk. fly method this Hawk can fly the
hawk moves at a speed of 50
347:51
mph so that's how you can use the super keyword to extend a method of apparent all
right everybody so that's the Super Key word it's a reference to a parent it can be
used to call the Constructor of a
348:02
parent and or access the properties and methods of a parent and well everybody that
is the super keyword in JavaScript hey hello so uh today I'm going to explain
Getters and Setters in
348:19
JavaScript Getters are special methods that make a property readable Setters are
special methods that make a property writable we can use use Getters and Setters to
validate and modify a value
348:31
when reading or writing a property it helps with validation when creating an object
or updating one of its properties here's an example we will create a class of
rectangle we need a
348:46
Constructor we will have two parameters a width and a height we will assign this.
width equals width this. height equals height now let's create a rectangle object
const rectangle equals a new
349:13
rectangle for the width let's say -1 million something ridiculous and for the
height I want the height to be Pizza the word pizza then let's [Link] our
rectangles width and the rectangle
349:36
height we have created a rectangle object with the width of 1 million and a height
of pizza which doesn't make any sense we could use some validation when creating an
object we don't want people
349:48
to enter in garbage values like negative a million or string when we're expecting a
positive number for the width or height that's where Getters and Setters come in
we'll begin with set letters
349:59
when setting one of these properties either initially through a Constructor or
updating one of them later such as setting the width or height equal to some value
we can go through a Setter
350:11
first outside of our Constructor we will set a property we'll begin with width this
will be a special type of method the parameter will be new width what do we want to
check before
350:27
assigning this property using an if statement let's check to see if the new width
that the user sends us is greater than zero if it is we will assign this doore
width using an underscore prefix it
350:44
tells other developers that this is a private property you shouldn't touch it at
all you could say that this private property of width is different than our
standard width property we will assign
350:56
the private property of width equal to the new width we receive else let's console.
error not log we'll use error this time width must be a positive number all right
let's see what
351:18
happens width must be a positive number and our width is currently undefined which
is good okay let's do this with height let's copy our Setter for width paste it but
change every instance of
351:31
width to be height set height New Height be sure to use that Camel case naming
convention if new height is greater than zero assign the private property of height
equal to the new height else console.
351:52
error height must be a positive number and there we go that worked width must be a
positive number and height must be a positive number our width and height are
currently
352:05
undefined in order to set the width and height we have to pass in a positive number
for the width I will say three for the width four now when we access width and
height those numbers still
352:18
aren't showing up that's because these properties are writable via Setters but
they're not readable that's where Getters come in we'll create two Getters one for
352:31
width we'll need to use the get keyword get width this will be another type of
method all we're going to do is return this private width and that appeared to work
we have three for the
352:47
width let's do so with the height we will return this private height we have three
and four Now by using Setters we can even update those values later let's take our
353:06
rectangles width set that equal to be five take the height set it equal to be six
and that also appears to work but again if I try and update those values to some
garbage
353:20
values like negative a million and the word Pizza we get those errors again and our
our object retains its initial values that we previously assigned it three and four
with Getters we can even use the
353:35
property accessor that dot to access a property that doesn't necessarily exist for
example we will get area we'll perform a calculation we will return this private
width times this private height
353:59
so now we can access area as if it was a property we have three for the width
height four our width times our height gives us an area of 12 our area isn't a
property technically it's not found
354:13
within our Constructor but we can access it as if it was a property with a getter
with Getters you can even add additional logic I would like to preserve the initial
values of our width and height
354:25
when I return their value I will use the two fixed method to give each of these a
Precision of one let's do that with the width the height and the area but that's
going to
354:39
be a little more complex we'll enclose width time height then add to fixed one and
why stop there I'll add centimeters to the end of each I'll use a template string
add a placeholder then add CM for
354:58
M 3.0 cm and the area 12.0 CM let's make that centimet squared because it's area
Technically when you're assigning values even when you're initially creating an
object you
355:23
can go through the Setters for input validation when you retrieve values and try
and read them you can add additional logic too let's go over a second example we
will create a class of person we need
355:37
a Constructor we will accept a first name last name and an age this. first name
equals first name this. last name equals last name this. AG equals age let's
construct a person const person equals new
356:11
person let's enter in some values that don't make sense the person's first name
will be the number 420 their last name is the number 69 their age is the word Pizza
let's
356:26
[Link] our person objects first name which is the number 420 their last name
69 and their age the word Pizza we need to validate this input before assigning the
356:45
properties that's why we need Setters we will set the first name property this is a
special type of method the parameter is going to be a new first name we need to be
sure that this value
356:59
passed in is a string and the length is greater than zero we could write something
like this we need an if statement let's check the type of our new first name is it
strictly equal to a
357:16
string and is our new first nam's length property greater than zero if all of that
checks out we will assign this this private first name equal to the new first name
we receive else let's console.
357:42
error first name must be a nonempty string let's see if this worked I'm going to
save first name must be a non-empty string and currently our first name is
undefined okay that worked let's
358:00
copy our Setter for our first name paste it change every instance of first name to
last name new last name check if the type of our last name is equal to a string and
if our new last
358:19
name the length of it is greater than zero if it is assign the private last name
property equal to the new last name else last name must be a non-empty string that
also worked our first name
358:35
and last name are undefined let's do this with age set our age the parameter is
going to be new age using an if statement is the type of new age strictly equal to
a data type of
358:55
number and is our new age greater than or equal to zero if it is take this private
age equals our new age else we're going to console. error age must be a non
negative number
359:24
we can no longer assign pizza for our age unfortunately all right we have our
setter set up now let's work on the Getters let's assign some legitimate values for
the first name SpongeBob last name
359:38
SquarePants age 30 we don't have those errors anymore that means they're set but
those properties aren't readable that's why we need Getters let's get the first
name get first
359:53
name return this private first name there's SpongeBob his first name get last name
return this private last name there's his last name let's create a getter for a
full name too let's
360:16
[Link] a full name even though we have no property for that that's undefined
we'll use a getter to mimic a full name property by just combining the first name
and the last name properties
360:28
get full name return I'm going to use some string cination this private first name
plus a space character this private last name and there's his full name SpongeBob
360:50
SquarePants and the age get age return this private age and SpongeBob is 30 all
right everybody those are Getters and Setters Getters are special methods that make
a property readable Setters
361:10
are special methods that make a property writable by using a combination of both we
can validate and modify a value when reading or writing a property and well
everybody those are Getters and Setters
361:22
in JavaScript hey what's good everybody so in today's video I'm going to give you a
lesson in destructuring in JavaScript destructuring allows us to extract values
from arrays and objects then
361:38
assign them to variables in a convenient way we can use straight brackets to
perform array destructuring or curly braces to perform object destructuring I'll
give you five different examples
361:49
example one swap the value of two variables we'll have let a equal 1 let B equal to
to use array D structuring we need a set of straight brackets add the variables a
comma B
362:07
this will equal we're creating a new array on the right hand side B comma a on the
Le hand side of our equals we're using destructuring on the right hand side we're
creating an array let's see
362:20
what's within variables A and B [Link] variable a then variable B so if these
values are swapped we should have two then one not one and two that's example one
we can use destructuring to
362:36
swap the value of two variables example two we can swap two elements in an array
let's create an array of colors const colors equals an array pick some colors I'll
go with RGB so that would be red
362:56
green blue let's add black and white suppose I would like to swap the position of
the first element and the last element this first element has an index of zero this
particular last
363:12
element has an index of four again we're going to use array to structuring we need
a set of straight brackets we'll take our array colors at index of zero comma rray
at index of four we want
363:28
to swap red with white 0 1 2 3 4 that's the fourth index equals we're creating a
new array by using Straight brackets colors at index 4 comma colors at index zero
then let's print our array
363:49
[Link] R array of colors there we go we have white green blue black red that's
how we can use destructuring to swap two elements in an array example three we can
assign array
364:04
elements to variables we'll declare a bunch of variables const we'll use
destructuring we're destructuring an array we need a set of straight brackets we'll
create some variable names first
364:16
color Second Color third color I will assign this equal to our array Colors Let's
print these variables [Link] our first color we have red second color green
third color blue you could combine
364:45
array D structuring with rest parameters we have two colors left let's assign that
to a new array we'll use rest parameters I will name this array extra colors then
we will
365:03
[Link] extra colors and that should be a new array that has the remaining
colors black and white that's how to assign array elements to variables using
destructuring example for extract values
365:18
from objects we'll create two people objects const person one person one will have
a few few properties first name will be SpongeBob last name will be SquarePants age
will be 30 and a job meaning
365:43
occupation not John job his job is that he is a fry cook all right let's copy
person one looks like that n should be capital in last name all right let's copy
person
365:57
one paste it change person one to person two the first name of person two will be
Patrick last name star age will be 34 person two is not going to have a job
property he's
366:13
unemployed using destructuring I can extract values from these objects we'll create
a few variables const we'll use object destructuring we need a set of curly braces
this time
366:26
we'll create these VAR variables first name last name age and job now this equals
let's start with person one let's display these variables [Link] first name is
SpongeBob last name
366:54
SquarePants age 30 job fry cook let's do this with person two Patrick Star his age
is 34 person two does not have a job property person one does though our job
variable is
367:13
undefined as you can see here you can set default values when using destructuring
if somebody doesn't have a job property we'll set job to equal unemployed let's see
if that works yep
367:29
Patrick Star age 34 his job is he's unemployed that's how you can extract values
from objects values extracted can even have default values all right last example
we can
367:41
destructure in function parameters we can pass an object to a function and
destructure it when it's passed in let's create a function we will create a
function to display a person
367:58
with the parameters we'll use destructuring we're destructuring an object we need a
set of curly braces we'll receive an object such as this I'm going to invoke
display person we'll
368:11
pass in person one as an argument when we receive person one as an argument we'll
destructure that object right away we will create a first name parameter last name
age and job
368:27
all we'll do is print a few lines using [Link] I'll use a template string
let's say Name colon space I'll add a placeholder first name and last name let's
add a new
368:48
line age call in space add a placeholder age then lastly job job colon space add a
placeholder job we're passing in person one and D structuring it we should display
name
369:06
SpongeBob SquarePants age 30 job fry cook let's pass in person two as an argument
name Patrick Star age 34 job is undefined again we can set a default value when
destructuring if an object
369:22
doesn't have a job property we will set that equal to be unemployed Patrick Star
age 34 job unemployed then if we pass in person one again his job should not be
unemployed
369:37
he's a fry cook there is a job property so we do not use the default value all
right everybody so those are a few examples of destructuring there's a lot you can
do with destructuring you use a
369:48
set of straight brackets to perform array destructuring or curly braces for object
destructuring they allow you to extract values from aray and objects then assign
them to variables in a
369:59
convenient way and well that is destructuring in JavaScript so uh yeah we're doing
a thing today today I got to explain nested objects in JavaScript nested objects
are objects inside of other
370:16
objects they allow you to represent more complex data structures a child object is
enclosed by a parent object by using nested objects we have the cap capability of
creating some very complex
370:28
data structures for example a person object could contain an address object as well
as a contact info object or a shopping cart object each item in your shopping cart
is an individual object
370:40
such as a keyboard a mouse or a monitor each of these child objects would have
their own properties and methods for example a price a name specifications on the
item a shipping method nested
370:53
objects are just objects inside of other objects let me give you a basic example
we'll create a person object const person equals an object we need to set a curly
BRAC a person might have a full name
371:08
property I will set that to be SpongeBob in this example SpongeBob SquarePants an
age of 30 is SpongeBob a student is student he's in boting school so let's say
that's true objects can also contain
371:26
array we'll create an array of hobbies to declare an array you need a set of
straight brackets what sorts of hobbies does SpongeBob have he knows karate he does
jellyfishing I need one more uh let's
371:43
say that he enjoys cooking now we're going to create a nested object this person
object will have an address object so we need a set of curly braces a few of the
properties of the inner
371:59
address object could be a street SpongeBob has an address of 124 con Street his
City will be bikini bottom and a country we won't do a full address but I think
this is good enough
372:17
for this example so SpongeBob lives in the ocean let's say that his country is
international waters I'll just abbreviate International our person object has a
nested address object
372:29
inside of it to access some of these properties of our person object we would type
the name of the object use the property accessor which is dot then the name of the
property full name SpongeBob
372:44
SquarePants let's print his age 30 is SpongeBob a student that is true I'm going to
display the array of hob person. Hobbies this will give you an array but if you
need individual
373:02
elements you have to list an index number so Hobbies at index zero would be karate
one is jellyfishing index two is cooking let's [Link] our person object dot
the address
373:21
object this would return an entire object if you need one of the properties within
this object that's within the person object you would have to follow the inner
object with the property
373:32
accessor again that dot person. address. Street which would give you 124 con Street
the city person. address. city Bikini Bottom person. address. country international
waters so when accessing a
373:52
property within a nested object you have to use the property accessor t that dot if
you would like to Loop through the properties of a nested object you can write a
for Loop like this for const
374:08
property in person. address [Link] take our person object access the nested
object address then use the index of operator the straight brackets give me the
current
374:29
property and there we are all right let's make something a little more complicated
we're going to create a class that utilizes nested objects so we will begin with
class address our class will have a
374:48
Constructor for an address we need these three things feel free to add more if you
would like a street City and Country then we'll assign these properties this.
Street equals Street this. City equals
375:09
City this. Country equals country now we'll create a person class class person our
person class will also have a Constructor we'll need a name age and an address for
the address I'm going to use rest
375:35
parameters we can pass in different parts of an address and store it within an
array when we create a person object we will assign [Link] equals name this. AG
equals age now for the address
375:49
we're going to construct an address object this. address equals a new address we're
going to call the Constructor of our address class and pass in our address I'm
going to utilize the spread
376:05
operator to spread our address we'll send our address object a street City and
Country all right let's construct some of these person objects const person one
equals a new
376:21
person this will call the Constructor but we have to pass in arguments to match the
parameter a name we'll just do a first name to keep it short an age SpongeBob will
be
376:32
30 we also need an address a street City and Country 124 con Street City will be
Bikini Bottom his country will be international waters and just for readability I'm
376:54
going to put the address on a new line let's create person two person two will be
Patrick age 37 Patrick will live on 128 con Street he'll have the same city and the
same
377:18
country then let's make person three person three will be Squidward age 45
Squidward will live on 126 constr all right let's see if this all worked
[Link] let's start with person one
377:46
person one. name which is SpongeBob age 30 let's get his address address and this
returns an object which is good that's what we wanted we have a nested object an
address object for some of the
378:01
properties within that address object we have a street City and Country we use the
property accessor again of dot give me the street 124 con Street the city bikini
bottom and the
378:16
country international waters all right let's confirm this with person 3 just to be
sure it all works person 3 give me the name Squidward age 45 address gives me an
object we'll use
378:33
the property accessor again give me the street 126 con Street the city beini bottom
and the country international waters this will also all work for person two if it
worked with person one
378:50
and three all right everybody so those are nested objects they're objects inside of
other objects they allow you to represent more complex data structures a child
object is
379:01
enclosed by a parent object in this example our address is the child object of the
person object we're creating a new object within our person object and well
everybody those are nested objects in
379:20
JavaScript hey what's up everybody so in today's video I'm going to show you how we
can work with an array of objects in JavaScript what we'll do is create an array of
fruit objects we'll create five
379:31
fruit objects to create an object you need a set of krly braces each object will be
comma separated just for my own readability I'm going to place each object on a new
379:45
line objects can have their own unique properties and methods our first fruit
object will have a name of Apple a color of red and calories meaning calories per
serving of
380:03
95 this is our first object let's copy these properties paste them for object two
change name to be orange color will also be orange calories 45 object three name
will be banana
380:21
color yellow calories 105 object 4 coconut color white calories 159 then our last
object will be pineapple color yellow calories 37 all right and here is our array
of
380:47
objects there's a lot we can do with this if you ever need a property within one of
these objects of your array you would take the array in this cas fruits add an
index number dot the name
380:59
of the property for example name I need the name property of the first object which
would be Apple so let's test that [Link] what is the name property of our aray
fruits at index zero that would
381:16
be apple one is orange two is banana three is coconut four pineapple let's select a
different property let's go with the calories 95 45 105 159 37 that's how to access
a
381:38
property within an array of objects to add a new object you can use the push method
let's take our array of fruits use the push method we will push a new object into
our array the name will be grapes
381:57
Color Purple calories 62 then let's [Link] R array [Link] fruits so we
have six Apple orange banana coconut pineapple and grapes uh which I misspelled
grap you can use the pop method to
382:22
remove an element fruits pop this should remove pineapple Apple orange banana
coconut no pineapple or splice splice will remove elements at certain indices
fruits.
382:41
splice let's select indices 1 through two all we're left with is Apple coconut
pineapple you can use the for each method to Loop through the elements of your
array let's display each object's name
382:57
fruits. for each we need a call back a function expression or an arrow function
let's use an arrow function for every fruit do this [Link] each fruit this
will return entire
383:13
objects for one of the properties we'll select dot the property name we have all
the fruit names let's go with the colors and the calories there we are there's also
the map method the map
383:32
method will run each element through a function and return a new array let's create
an array of fruit names const fruit names equals take our array of fruits use the
built-in map method we'll
383:46
use an arrow function for every fruit Arrow return the fruits name then we will
[Link] our array of fruit names and here's our array of fruit names let's do
this with colors fruit
384:11
colors return every color property of each fruit then [Link] our fruit colors
red orange yellow white yellow let's do this with calories fruit calories return
each calories
384:31
property console. log our fruit calories array so the map method we'll return a new
array let's cover filter filter will return a new array after using each element
and checking a condition let's
384:47
return a new array where the color of each fruit is yellow there's two const yellow
fruits equals take our array of fruits use the filter method we have one parameter
a fruit Arrow then a condition
385:06
we'll return this fruit if the fruit's color property is strictly equal to Yellow
then [Link] our array of yellow fruits and there's two bananas and pineapples
385:24
they color are both yellow let's create a new array of any fruits that are low in
calories where the calories are below 100 const low cal fruits take AR array of
fruits use the built-in filter method
385:42
for every fruit Arrow check the calories of each fruit is it less than 100 if it is
put it within this new array and here we are we have three fruits that are low in
385:57
calories Apple orange pineapple the calories are 95 45 37 they're all less than 100
let's find any high calorie fruits change our rate to be high Cal fruits where the
calories of each fruit
386:16
is greater than or equal to 100 [Link] AR array of high Cal fruits there are
two banana and coconuts the calories are 105 and 159 let's use the reduce method
now I'll
386:32
admit this is going to be a little tricky but I'll try my best to walk you through
it the reduce method will return a single value in this case an object one of these
objects let's return the
386:43
object with the greatest amount of calories we'll store that within a constant
const Max fruit equals take array of fruits use the reduce method there's going to
be two parameters an
387:02
accumulator which keeps track of the greatest value during each iteration and the
next element but I think we should rename these let's rename our accumulator as Max
it's going to be the
387:15
current record holder of the object with the greatest amount of calories element
will be fruit meaning the next fruit here are the two parameters Arrow what are we
going to check is our
387:29
fruit the next fruit in line are the calories greater than our current record
holders calories max. calories just for readability I'm going to put this on a new
line we're going to use the trary
387:47
operator is this true does the next fruit have more calories than our record holder
if it does will return our fruit meaning the next fruit colon meaning otherwise
return the max again let's see
388:04
if this works let's [Link] our fruit with the maximum amount of calories which
is our coconut with 159 calories if you just need the calories you would type dot
calories
388:20
that will just give you the calories but in this case we're returning an entire
object object let's find the fruit with the least amount of calories let's copy our
code paste it and make a few
388:36
changes Min fruit change Max to be Min the condition will be is the calories of the
next fruit less than the calories of the minimum record holder then [Link] our
Min fruit
388:58
which is our pineapple with 37 calories all right everybody so those are a few ways
in which you can work with an array of objects there's a lot you can do with them
you can map you can
389:09
filter you can reduce you can splice you can pop you can push all sorts of things
and well that is an example of an array of objects in JavaScript yo so uh what's up
today I'm
389:24
going to be talking about about the sort method in JavaScript the sort method is
used to sort elements of an array in place however with the sort method we sort
elements as strings in
389:35
lexicographic order not alphabetical if I could summarize what lexicographic means
it means alphabet Plus numbers plus symbols as strings let me give you an example
with just alphabetical
389:46
characters I have an array of fruits to sort this array I can take the array name
fruits use the built-in sort method then [Link] my array of fruits let me
expand this and here's my array all
390:04
sorted when sorting we treat any elements as strings what if my array were numbers
I'll add the numbers 1 through 10 in a somewhat random order let's change our array
to be
390:22
numbers numbers. sort con cons. log numbers here's the result we have one then 10
then the rest seem to be in order we're not sorting this array numerically we're
sorting this array
390:37
lexicographically we're treating each of these numbers as strings that's why we
have one then 10 10 isn't at the end where we expect it would be there's a couple
extra steps we need to do
390:47
involving sorting numbers inside of the sort method we have to write a custom
comparison function this is normally a call back but you can write a function
expression
390:57
or even better yet an arrow function we'll write an arrow function in this case let
me zoom in with an arrow function we first need parameters we'll have parameters A
and B
391:10
we'll examine two contiguous elements 1 then 10 10 then two 2 then 9 9 and three so
on and so forth then we need an arrow then we'll write a minus B our function a
minus B will return
391:28
either a negative zero or positive value depending on what values we're examining
the sort method will sort those values into place depending on what the value
returned is our array should be sorted
391:41
you can see that 10 is at the end instead of right after one for reverse order you
could say B minus a now we're starting with 10 and ending with one you can even
sort objects by a given
391:57
property let's go over that example we will create an array of people const people
equals this will be an array will include four objects all comma separated the
first will have a name property of
392:20
SpongeBob age 30 and a GPA GPA 3.0 I'm going to zoom out for the next object just
going to put that on a new line let's copy all these properties change name to be
Patrick age will be 37 GPA
392:45
1.5 again for the next object we will have Squidward age 51 GPA 2.5 then lastly
we'll have Sandy name Sandy let's make Sandy 27 GPA of course it's going to be a
4.0 I would like to sort this array of
393:13
objects by each person's age we'll take our array of objects that's stored within
people use the built-in sort method use our Arrow function a comma B Arrow we'll
take parameter a that's
393:33
person one do access their age property minus parameter B access their age property
and that's all you got to do now let's [Link] R people there we are we have
Sandy who's the
393:57
youngest then SpongeBob Patrick Squidward for reverse order you'll just change a to
be B and B to be a Squidward Patrick SpongeBob Sandy or we can sort by a different
property let's do GPA this
394:17
time a. GPA b. GPA we have Patrick with the lowest GPA followed by Squidward
SpongeBob Sandy then reverse order would be b. GPA minus a. GPA Sandy SpongeBob
Squidward Patrick
394:39
let's try sorting by the name property and see what happens [Link] minus b.n name
we have SpongeBob Patrick Squidward Sandy but that doesn't seem to make sense these
aren't in alphabetical order
394:56
if you need to sort by a property that contains a string within an object there's a
different formula we will take [Link] do use the buil-in local compare method
compare to b.
395:15
name this method will examine two strings for lexicographic order now these are all
arranged lexicographically starting with Patrick then Sandy SpongeBob Squidward for
reverse
395:29
lexicographic order we would take b.n name. local compare then examine [Link] I've
just now realized that there's a lot of SpongeBob characters whose first name
starts with an S like
395:42
we have three right here Squidward SpongeBob Sandy Patrick all right everybody so
that is the sort method it's used to sort elements of an array in place it sorts
elements as strings in
395:53
lexicographic order not alphabetical and well everybody that is the sort method in
JavaScript hey everybody in today's video I'm going to show you how we can Shuffle
the elements of an array using
396:08
JavaScript this is an optional video you might find this topic helpful if you're
interested in making a game using JavaScript or any sort of application where you
need some Randomness in this
396:17
example we'll create a deck of cards our deck of cards will be an array we have an
a for Ace the numbers 2 through 10 let me finish typing those in J for Jack Q for
Queen k for King I'm not
396:32
going to include any suits for these cards such as Ace of Hearts Ace of clubs that
might be overkill for this example one method you might see floating around online
to shuffle the elements of an
396:43
array is to use the sort method then pass in an arrow function where you take math.
randomus 0.5 I would not recommend using this method just because the results of
this method aren't perfectly
396:56
uniform let me [Link] cards this array appears shuffled but it's not that
uniform but not only that the larger the array becomes this method becomes
increasingly more inefficient I would
397:08
not recommend using the sort method to shuffle an array instead I would recommend
using the fer Yates algorithm we'll create a dedicated function for this so we will
Define a function to
397:21
shuffle there will be one parameter and a array then to invoke this function we'll
type the function name pass in our array of cards so what do we want to do exactly
397:34
we're first going to Loop through the elements of this array we'll start at the end
and work our way towards the beginning we'll use a for Loop to decrement So within
our Shuffle function
397:44
we'll create a for Loop we will declare index of I let I equal R array do length
then minus one that's the first statement our array has 13 elements but the last
index is 12 because array start
398:02
with zero if the array's length is 13 we need to subtract 1 to get 12 which would
give us the ending index of 12 we'll continue this loop as long as I is greater
than
398:14
zero then iusus to decrement now we have to generate a random number between the
end and the beginning somewhere within this range we'll create const random random
will
398:27
store a random number take math. random method times I our index + one we'll need
to round this number we're now going to enclose this equation with math. floor to
round down math. floor and enclose
398:47
this equation all right during the first iteration of this Loop we should generate
a random number between the end and the beginning we'll swap our king with a random
element within this array
399:01
so to swap two elements of this array we can use destructuring in this context to
use destructuring we'll take our original position array at index of I during our
first iteration that will be
399:12
the king we'll swap our King with our array at a random index the one that will be
randomly generated equals our array at index IND of random comma array at index of
399:28
I then to finish using destructuring we need to enclose both sides of this equation
with an array there and that will swap two elements of your array now if I run this
program this
399:41
will Shuffle the elements of my array I would recommend using a dedicated Shuffle
function because in a game it's likely you're going to shuffle something more than
once throughout that game like
399:52
I said this isn't a necessary topic to continue on with the series but if you're
ever interested in making a game using JavaScript or need some element of
Randomness well then this function would
400:01
work great and that is how to shuffle the elements of an array using JavaScript
what's up everybody so in today's video I'm going to explain date objects in
JavaScript date objects are
400:14
objects that contain values that represent dates and times these date objects can
be changed and formatted to suit our needs here's an example we will create a date
object that
400:26
contains the current date and time to do so let's create a constant named date date
will be an object we will call the date Constructor with the new keyword date then
pass in no arguments for the
400:39
current date and time so I'm going to [Link] my date object which gives me my
current date and time as of right now I'm filming this video on a Thursday November
9th the year 2020 23 at about
400:55
7: in the morning so depending on when you're watching this video the date and time
is going to be different if you would like to create your own custom date and time
object you'll have to pass
401:04
in some arguments you can follow this order for the date Constructor the first
argument corresponds to a year then month day hour minute second and milliseconds
even so for the year let's say
401:18
2024 the month zero corresponds to January one is February then that means a month
of 11 is December let's say January so that will be zero for the day one for the 1
for the hour uh 2 2 in the
401:34
morning this is in Military Time by the way for the minute 3 minutes after the hour
for the seconds 4 seconds after the minute we can even add milliseconds if we would
like so for the milliseconds
401:47
let's say five and here's my new date object Monday January 1st 2024 about 2 in the
morning passing in a string representation of time to the date Constructor is also
valid let's say the year is
402:01
2024 January 2nd for the time you're going to type t for time 12 noon then add Z
for UTC time and there's my new date again Tuesday January 2nd 2024 6: in the
morning
402:18
another format you can use is within the date Constructor pass in a given amount of
time in milliseconds since epic if I could describe epic I would describe it as
when the date your computer thinks
402:30
time began if you were to pass in zero to the date Constructor you'll be given a
date and time around December 31st 1969 So within the date Constructor you can pass
in a given amount of
402:42
milliseconds since this date so if I was to pass in 1.7 billion milliseconds what
I'm telling the day Constructor is give me the date and time that's 1.7 billion
milliseconds since that epic
403:02
date when I pass in 1.7 billion milliseconds the date that I'm given is Tuesday
November 14th 2023 about 400 p.m. passing in milliseconds would be good for some
sort of timer now let's
403:16
use the current date and time I will pass in no arguments you can extract
individual values from a date object I would like the year const year equals take
our date object I will use the get
403:31
full year method to get the year then I will [Link] the year and this will be
a number 2023 let's get the month const month equals our date object use the built-
in get month method then I
403:52
will console without log the month currently for me it's November not October so
remember January is zero December is 11 let's get the day const day equals date get
date not day if you
404:13
get the day that will give you the day of the week like Sunday Monday Tuesday that
sort of thing let's [Link] the day so for me it's the the 9th let's get the
hour const hour equals date get
404:31
hours plural [Link] the hour for me it's 7 in the morning let's get minutes
const minutes equals get minutes [Link] the minutes it is 7:45 in the morning
get seconds get
405:07
seconds [Link] the seconds so 745 21 seconds after the minute now if you need
the day of the week here's what you can do const day of week equal equals date get
day that will give you
405:27
the day of the week [Link] day of week for me that is for Sunday is zero
Monday is one so that means it is Thursday now with the date object you can even
set the date with a method let's
405:46
[Link] the date I'm GNA set the Year date set full year I will set the year to
be 2024 yep Saturday November 9th 2024 let's set the month set month I will set the
month to be January
406:10
so I will pass in zero Tuesday January 9th let's set the day that would be with set
date not day I will set it to be the first January jary 1st the hours with set
406:29
hours let's go with two for two in the morning set minutes 3 minutes past the hour
set seconds 4 seconds past the minute you can even compare dates as well let's
create two date objects const date one
406:53
equals a new date I'll pass in a string representation of a date we won't include
the time though for the year let's say 2023 December that would be 12 31st New
Year's Eve basically and for date
407:10
two let's say date two is New Year's Day 2024 January 1st using an if statement
let's compare to see if date 2 is greater than date 1 if it is then let's
[Link] happy New
407:34
Year so date two is greater than date one we'll print happy New Year let's change
date two to be 2023 December 30th well nothing happens then but that's to be
expected all right everybody so those
407:52
are date objects they're objects that contain values that represent dates and times
these date objects can be changed and formatted to suit our needs and well
everybody those are date objects in
408:08
JavaScript hey what's going on everybody so in today's video I got to explain
closures in JavaScript a closure is a function defined inside of another function
the inner function has access
408:21
to the variables and scope of the outer function by using closures they allow for
private variables and state maintenance JS libraries and Frameworks such as react
View and angular use
408:33
closures all of the time you'll see closures fairly often with function-based
components you have functions inside of other functions let me give you a very
basic example we'll
408:44
have an outer function named outer within the outer function we'll have a function
named inner the inner function has access to everything within the outer function
409:00
this scope if I was to create a variable let message equal the word hello within my
inner function I can use this message variable [Link] my message now if I
invoke
409:18
the outer function nothing appears to happen when we call the outer function we're
now within the scope but then what there's one of a few things we could do if I
would like to call the inner
409:31
function from within the outer function I would need to call it somewhere here
let's call the inner function at the end there we go we have displayed the word
hello everything within the outer
409:43
function is part of a closure we have a function defined inside of a function this
inner function has access to everything within that scope includ cluding this
message variable one
409:55
benefit of using closures is that any variables are considered private outside of
the outer function I will attempt to update our message message equals goodbye now
this doesn't work as you can
410:08
see this message variable is in a different scope it's kind of like it's in another
dimension what we've done here is we have created a different message variable in a
different scope
410:20
outside of the outer scope I have no way of accessing the message M variable so
that's one of the benefits of closures you can encapsulate variables and make them
private let me give you another
410:30
example a closure can maintain the state of a variable we'll create a counter
program so I'm going to create a function to increment within the increment
function
410:44
I will set a count variable equal to 0o I will increment our count by one then
[Link] I'll use a template string count increased to I'll add a placeholder
we'll display our count
411:03
variable now anytime I attempt to call the increment function it'll increase our
count by one but if I was to execute this function again well we're redeclaring
this variable of count we're
411:16
resetting it every time we call this function I can't get the count to go past one
because we we keep on resetting it but by using a closure we can have state
maintenance we can maintain the
411:29
state of this variable and remember where this variable was previously I mean I
could take this variable and declare it outside of the function but then we don't
have any security for that
411:40
variable I will set the count equal to a million we're maintaining the state of
that variable but it's not private anybody and anything can access and change that
variable a closure maintains
411:53
the state of a variable and makes it private what we'll do is enclose all of this
code within another function we'll create a function to create a counter how do we
access the scope
412:16
within the create counter function here's another possibility we will return an
object we will need a set of curly braces our object will have a property of
increment and its Associated value
412:32
will be a reference to increment there is a shorthand version of this you can just
use the function name as a property we're returning an object with the method of
412:44
increment so now I'm going to create an object named counter counter equals invoke
the create counter function this will return an object that has an increment method
so I'm going to take our counter
413:00
object use the increment method count increase to one not only do we have an
increment method we have a count variable as well you could say that what we've
done with this outer
413:12
function it's very similar to creating a class we can use classes to instantiate
objects in this case we used a function to return an object so if I was to take my
counter and increment it again our
413:27
closure should maintain the state of that variable count count increase to two it's
not resetting every time we call the method count increase to three let's attempt
to access our count
413:40
variable counter. count equals z then I will [Link] our count reference ER
count is not defined let's attempt to display our count variable [Link] take
our counter object access the account
414:05
variable it is undefined we don't know what it is it's hidden your closure can have
more than one function so what we'll do is create a get count function we'll use
the get
414:19
count function to return our count if we need access to it function get count we
will return our count variable within the return statement we're returning an
object we will add
414:35
another property of a reference to the get count function so now within our counter
we have a method to get the count variable let's [Link] I'll use a template
string
414:51
the Curve current count is I'll add a placeholder take our counter object use the
get count method the current count is three if I was to increment our counter again
well that increased to
415:09
four all right last example we're going to create a closure for a game where we
keep track of points we have a score let score equal Z we'll Define the function
function increase
415:27
score we'll have one parameter points in order to score some points we have to pass
in some points as an argument take our score plus equals R Points then let's
[Link] I'll use a template string
415:47
plus add a placeholder R Points then I'll add pts meaning points it's shortened
let's create a function for decrease score change increase to decrease score minus
equals
416:05
points minus points and then let's get our score function get score return the
score if I need to increase the score I will invoke The increased score function
but I have to pass in points we scored
416:28
five points let's do this again we scored six points let's decrease the score I
will subtract three points minus three points let's get the current score console.
416:49
log I'll use a template string the final score is add a placeholder get score the
final score is eight I'm going to add points after that eight points all right
problem with this is that we
417:09
can take our score and set it to anything you scored like a kajillion points so for
some security let's enclose all of this code within a closure I'll create an outer
417:23
function function create game this will return an object let's cut all of this code
paste it within the outer function of create game and then at the end we will
return
417:40
an object that has references to these functions return an object we need curly
braces for that a reference to increase score decrease score and get score so now I
will use the create game function
418:04
to return an object const game game will be our object we will invoke the create
game function and return an object so now if I want to increase the score decrease
it or get the score I
418:22
have to use the methods of this object game. increase score game. decrease score
and [Link] score we have five points six points minus three points and then we
have the
418:39
final score of eight points well everybody those are closures think of them as a
function defined inside of another function the inner function has access to the
variables and scope of the
418:50
outer function these are used frequently with JS libraries and Frameworks such as
react View and angular especially when you work with function based components
419:00
and well everybody those are closures in JavaScript hey what's going on people so
in today's video I'm going to explain the set timeout function in JavaScript the
set timeout function allows you to
419:15
schedule the execution of a function after an amount of time in milliseconds the
times are approximate they vary based on the workload of your JavaScript runtime
environment I wouldn't recommend
419:26
using set timeout for anything precise like a stopwatch it's an approximation to
use the set timeout function you pass in a call back to a function and a delay in
milliseconds here's an example I will
419:38
create a function to say hello all we're going to do is window. alert the word
hello I will use the set timeout function pass in a call back we'll pass in a call
back to say
419:59
hello then execute it after 3,000 milliseconds so 3 seconds let's see if this works
1 2 3 hello an anonymous function works too so instead of a call back we'll use an
anonymous
420:17
function function parenthesis curly braces window. alert the word hello 1 1000 2
1000 3 1000 hello or even an arrow function we have parameters Arrow what are we
going to do window. alert the word
420:45
hello 1 1,000 2 1,000 3 1,000 hello you can use the clear timeout function to
cancel a timeout before it triggers but we have to pass in a time out ID so what
we'll do with this set timeout function
421:03
is assign it to an ID stored within a variable or constant const time out ID equals
our set timeout function that'll display the word hello I can clear this time out
with the clear time
421:22
out function but I have to pass in that ID as an argument immediately after calling
the set timeout function we will cancel it let's try it 1 1000 2 1000 3 1000 yeah
nothing's happening we
421:38
canceled it all right what we'll do this time is create a button using HTML when we
click on the button we'll set a timeout to display the word hello so let's clear
all of this go to our
421:53
HTML file we'll create a button the button will have text of start and I'm going to
zoom in I will set the onclick attribute to equal a function we will start a timer
then add a set of
422:15
parentheses when we click on the button do this function So within our Javascript
file we will create a start timer function function start timer we will set time
out I'll use an arrow function let's
422:39
window. alert the word we will display the word hello after 3,000 milliseconds all
right so nothing's going to happen until I click the button I'm going to click it
now 1 1,000 2 1,000 3 1000
422:58
hello let's create a second button to clear the timeout if we need to stop it let's
copy our first button paste it change the text of the button to be clear we will
clear the timeout but
423:13
we'll need another function clear timer so there's our second button we'll need a
timeout ID so outside of this function I will declare a variable of let timeout ID
when we start our timer we will
423:35
assign the set timeout function an ID of timeout ID then we can stop it using this
ID we will create a function to clear the timer we're going to use the clear
timeout function clear time
423:55
out we need to pass out a timeout ID as an argument which we will do and then just
to be sure that everything works within both these functions let's [Link]
something let's say the word
424:09
started within our start timer and within our clear timer let's display the word
cleared just so we know that these functions were called so I'm going to save
everything
424:22
I'm going to start the timer but not clear it let's start now 1 1,00 21000 3 1,000
hello let's go to our console and it says that we started well starter I clearly
can't spell today
424:40
started we're going to start then cancel start 1 1,000 to 1,000 clear and nothing
happened let's go to our console and expect console we started set timeout and then
we cleared
424:56
it all right everybody that is the set timeout function it's a function in
JavaScript that allows you to schedule the execution of a function after an amount
of time in milliseconds execution
425:08
time may vary based on the workload of the JavaScript runtime environment and well
everybody that is the set timeout function in JavaScript hey what's going on people
so
425:21
in today's video we're going to create a digital clock using JavaScript HTML and
CSS so let's get started the HTML for this project is going to be very minimal I
will create a develop the ID of the
425:35
development will be clock Dash container within this development we'll have a
nested development with an ID of clock we have a clock within a clock container as
a placeholder temporarily the text on
425:51
the clock will be 0 0 colon 0 0 colon 0 0 000000000000 0 and I'm just going to zoom
in temporarily and that is all the HTML that we need let's head to our CSS
stylesheet let's begin with the
426:10
body I will set all margin to be zero originally let's select our clock container
ID clock container I'll use flex box for the clock container display Flex I will
justify content in the
426:31
center justify content Center if you would also like to vertically align you'll
need to add the following two lines of code I will align items Center this CSS
property will vertically
426:49
align any elements but the clock container itself is kind of small for example I'll
add a border of two pixel solid the elements within the clock container are aligned
both horizontally
427:02
and vertically but the container itself is kind of small to vertically align this
element within the window itself we'll have to increase the height of the clock
container I will add height of 100
427:15
VH for the viewport height and we can remove the Border yep the clock is now within
the middle of the container both horizontally and vertically but if you prefer it
to be at the top you can
427:27
eliminate these last two lines it's up to you let's style the clock itself we are
selecting the ID of clock I will change the font family to be monospace this is the
normal size when
427:45
I'm zoomed in to 100% I will set the font size to be 6.5 RM then set the font
weight to be bold and text align Center if you would like a background image for
the body of your document I
428:08
just so happen to have one right here it's a picture of Central Park in New York
this is optional but if you would like to include a background image of this
project within your CSS stylesheet
428:19
you'll add the following CSS properties I will set the background image property to
be a URL so what is the name of that image I'm going to copy the name of it and
paste it within this URL
428:36
function I'll set the background position to be the center right now we're seeing
the top left of the image instead of the center background Position will be Center
428:53
if you're using a small image your image might be repeating itself to take up all
the available space to prevent that you can set the background repeat property to
be no
429:10
repeat mine already wasn't repeating though but yours might be then we'll set the
background size to cover by adding this property this image will cover the entire
window and maintain its
429:27
aspect ratio if you do have additional content besides this clock you can keep the
background in place when you scroll down by adding this property background
attachment to be
429:43
fixed this property isn't going to be apparent because we don't have a scroll bar
but if you did have a scroll bar the background will stay in place at least let's
head back to our clock element I
429:55
will change the color the font color to be white if you would like a background
blur effect you'll add this property we'll set the backdrop filter property to be a
blur
430:10
function the greater the number the more blur effect you're going to have so this
is five pixels if I were to increase this to 50 well there's a lot of blur then
I'll
430:21
set my blur to be five I would just like a little bit as if we're looking through
glass I'll increase the width to be 100% to take up 100% of the width of the web
browser width
430:36
100% to give this glass look a foggy appearance we can add a background color
that's slightly gray background- color let's select gray but I like using hsl
values
430:52
so for the lightness I'll set it to be 100% but I'm going to lower the alpha down
to like 10% now the background has a foggy glass appearance if you were to increase
the amount of
431:08
alpha that'll increase the lightness I'll keep mine as 10% 0.1 for the alpha all
right now we just need to get this clock to run so let's save everything go to our
JavaScript
431:22
file we will create a function to update our clock immediately when we begin this
program we will update our clock once immediately now we need to get the current
time let's declare a constant of
431:40
now what is the time right now this will be a new date object to get the hour we
will say const hours equals use the builtin get hours method then let's do this
with minutes con minutes equals
432:01
now. get minutes method and seconds const seconds equals now. get seconds I'm going
to change the text content of the clock to be a time string it will be a template
string how do we
432:21
want to arrange our numbers const time string equals a template string first We'll
add a placeholder for our hours colon minutes colon seconds then we will select the
ID of
432:45
clock document. getet element by ID the ID that we're getting is our clock change
the text content to equal our time string when we save the time on the clock should
update currently for me
433:05
it's 8:00 for each of these placeholders for hours minutes and seconds I would like
each to take up two digits We'll add some zeros for padding for example this time
will be
433:19
08006 there's a built-in string method for that so with hours minutes and seconds
we will convert these to Strings we'll use method chaining then add to string do
this for hours minutes and
433:33
seconds with strings there's a pad start method for the first two characters pad
them with a zero let's copy this method and paste it for minutes and seconds now
when I save
433:50
an up the time we have zero padding 08 01 54 in this case to get this clock to
update every second will follow update clock with the set interval function set
interval works like set timeout except
434:08
it will call a function repeatedly not just once but we need a call back the call
back will be update clock call this function after every 1,000 milliseconds and now
our our clock should
434:23
run currently this clock is in military time although I'm recording this at 8 in
the morning if you would like this clock to be a 12-hour clock then add am or p.m
434:33
here's the following changes we're going to make we'll declare hours with let
instead of const so we can change it and reassign it we'll create a new constant of
meridium 400 a.m. or
434:47
p.m. this will equal hours is ours greater than or equal to 12 we'll use the erary
operator to check this if ours is greater than or equal to 12 meridium will be PM
otherwise it will be
435:06
am then after our meridium we'll reassign hours hours equals hours modulus modulus
gives you the remainder of any division ours modulus 12 if this is zero we'll use
the or
435:23
logical operator or 12 after seconds We'll add a placeholder for our meridium
currently we lost our padding for the hours so we're going to cut this part of our
code to convert ours to a
435:39
string and Pad it we'll take ours equals hours to reassign it follow hours with
converting it to a string using the two string method and Pad it before displaying
it all right and that has appeared to
435:56
work all right everybody so that is a digital clock program you can make using HTML
CSS and JavaScript hey what's going on everybody in today's video I'm going to show
you
436:10
how we can create a stopwatch program using JavaScript HTML and CSS so sit back
relax and enjoy the show all right let's get started everybody we will create an H1
heading with textt of
436:24
stopwatch and I will give this H1 element a unique ID of my H1 then we'll create a
container for our stopwatch this will be a div element this div element will have
an ID
436:38
of container to contain everything our container is going to have two sections two
developments the First Development is going to be for our display ID display I'll
give this development some
436:57
initial text as a placeholder we'll have zeros for hours minutes seconds and
milliseconds then our next development will have an ID of controls for all the
control buttons within this development
437:12
of controls we'll create three buttons the first button will be start the ID of
this button will will be start button BTN short for button then I will set the
onclick event handler equal to a
437:28
JavaScript function we will eventually create a start function we still need to
Define it let's copy this button paste it twice the second button will be for stop
437:41
the ID will be stop button the onclick attribute will be for a stop function the
text on the button will be stop and then we have a reset button the ID is reset
437:55
button the onclick attribute will be for a reset function the text on the button
will be reset all right and that is all the HTML that we need let's go to our CSS
438:09
stylesheet I will first select the body of our document we'll use flexbox to
display everything because I like flexbox display Flex the flex Direction will be a
column then I will align items
438:28
Center I'll set the background color of this application background-color pick a
color again I like using hsl values I'll set the lightness to 90% our container is
going to be a
438:45
lighter color we will select the ID of my H1 that's going to be the heading I will
set the font size to be 4 RM the font family I will pick Ariel with a backup of s's
439:06
serif for the font color I will set the color property to be pick a color I'll pick
black but set the lightness to 25% all right now we are going to select the
container that contains everything
439:22
besides the heading this area we will select the ID of container I will use flex
box within the container display Flex the flex direction will be a column and
aligned item
439:47
Center let's add a border a border around the container 5 pixel solid and I will
round the corners border radius let's do 50 pixels and I'll add a little bit of
padding padding 30
440:10
pixels and I will set the background color to be white background color white we'll
work on the time display next select the ID of display I will set the font size to
be 5 RM for the font
440:34
family I'm going to set it to be monospace and the font weight I will set to be
bold I'll change the color I'll set the lightness to 30% I'll give a text Shadow to
the
440:54
display so it looks like it's somewhat 3D like it's popping out so text Shadow two
pixels and two pixels for the vertical and horizontal offset and a blur of two
pixels now for the color I'm going to
441:11
lower the alpha to 75% or so that's not bad bad then I'll add a little bit of
margin to the bottom margin bottom 25 pixels now we have to style the buttons we
will select the ID of controls but I
441:34
would like the button elements within the controls after selecting the ID of
controls select any buttons within that element we'll increase the font size of the
buttons font size 1.5 RM I will set
441:49
the font weight of the buttons to be bold I'll add a little bit of padding 10
pixels by 20 pixels I'll add some margin around the buttons 5 pixels I'll set a
minimum width of the buttons to be 125
442:12
pixels let me scroll down I'll remove the border border none set the Border radius
of the buttons to be 10 pixels change our cursor to be a pointer when we hover over
the buttons let's see
442:31
if that works yes it does then set the font color of the buttons to be white now
let's color the start button we will select the ID of start button set the
background
442:45
color pick a color I'll start with something green pick whichever color you would
like I'll pick this shade of green here are the values when we hover over the start
button we will access the hover
443:07
sudo class of our start button I'll decrease the lightness by 10% let's copy the
markup that we have for the start button paste it twice we'll add color to the stop
button and the reset
443:28
button I'll set the stop button to be red here are the hsl values that I picked
when I hover over this button I'll set the lightness to be 10% darker for the reset
button I'll set that to be
443:48
blue when we hover our cursor over the reset button I will set the lightness to be
10% darker not bad for all of the buttons I'm going to add a transition effect
transition select the background color
444:08
we will create an ease transition after 0.5 seconds we will ease so when you hover
your cursor over the buttons there's going to be a slow transition when we hover
okay and that is all the CSS that
444:27
we need we will now go to the Javascript file to add some functionality let's
declare all the variables we'll need we'll get the ID of the display and store a
reference to it const display
444:41
equals document. getet element by ID the ID that I'm selecting is display this ID
we will create a timer let timer equals null timer is going to hold the ID of set
interval so we can keep track of it
445:03
and stop it if we need to then we need a start time let start time equal zero let
elapsed time equal zero let is running this will be a Boolean which I will set to
be
445:21
false if the stopwatch is currently running we will flip this to be true and flip
it to be false to stop it what are the functions that we need we have a start stop
and reset function function
445:40
start function stop function reset We'll add one more function of update to update
the display function update we'll begin with the start method we'll enclose
everything within our
446:00
function within an if statement we need to check to see if our stopwatch isn't
running if our stopwatch isn't currently running if not running then start the
stopwatch we need to set the start time
446:15
the start time equals we will get the current date date do now minus the elapse
time which will be zero initially so just to demonstrate what the start time is I'm
going to [Link] my start
446:37
time so the start time is going to be in milliseconds since epic epic basically
speaking is when your computer thinks time began we will set our timer equal to the
set interval
446:56
function we will call the update function every 10 milliseconds so if I was to
display my timer [Link] timer this is what it is our timer stores a unique ID
to work
447:15
with this function if we ever need to stop it we'll take the Boolean variable of is
running set it to be true because our stopwatch is not running now we need to go to
the update function to actually
447:30
get it working we need to get the current time const current time equals access our
date use the now method what is the date right now we will calculate the elapse
time
447:51
equals the current time minus our start time whatever that was when we initially
pressed the start button so the current time minus our original start time gives us
the elapse
448:05
time and this is going to be in milliseconds we need to convert the elapse time
into a readable format using hours minutes seconds and milliseconds we'll begin
with hours let hours
448:20
equals take our lapse time divided by to convert milliseconds to hours we can
follow this formula elapse time divided by 1,000 milliseconds * 60 seconds times 60
minutes we don't want any decimal
448:39
portions with our hours we will enclose all of this with the floor method of math
now we're going to do something similar with minutes let minutes equals take our
lapse
448:55
time we need to convert milliseconds to minutes divided by 1,000 milliseconds in a
second times 60 seconds in a minute then modulus 60 modulus gives you the remainder
of
449:12
any division we don't want our minutes display to hit 60 or go above 60 once we hit
60 it'll reset back to zero enclose this formula with math. floor to round it math.
449:27
floor okay then we have to take care of seconds let seconds equals take our lapse
time divided 1,000 to convert milliseconds to seconds modulus 60 and close all of
this with math. floor to round it
449:52
now for milliseconds let milliseconds equals take the elapse time which is already
in milliseconds modulus 1000 milliseconds is normally four digits we're going to
450:06
divide it by 10 we only want the first two digits divided by 10 en close all of
this with math. floor math. floor then let's change the display we'll access our
display access the text content of the
450:29
display set it equal to a template string if you would like to display the hours
it's optional we will add a placeholder for hours colon placeholder minutes colon
placeholder seconds if you
450:46
would like to display the milliseconds we can add a placeholder for that colon
placeholder milliseconds let's see what we have so far I'm going to hit the start
button and here's what we
451:01
got so the stopwatch is running but we should add some zeros for padding so I'm
going to refresh to stop it we'll convert hours minutes seconds and milliseconds
into a string then add
451:13
some padding of zeros to it if the number is only one digit not two we will convert
our hours minutes seconds and milliseconds into a string before displaying it so
let's take hours equals
451:26
hours I will typ cast it as a string follow this with the pad start method for the
first two digits at a zero let's do this for minutes seconds and milliseconds
minutes seconds and
451:52
milliseconds we should have some zeros for padding to make each display two digits
and that does appear to work nice now we just need to get the stopwatch to actually
stop right now there's no
452:06
functionality going to our stop function we need to check to see if our program is
running is this variable is running true if is running if that that's true then
stop the
452:21
stopwatch we will use the clear interval function we need to pass in that unique ID
for the timer this will stop the stopwatch from running then we will calculate the
452:34
elapse time elapsed time equals the date right now date. now method minus the
original start time then set is running equal to false because the stopwatch is
stopped it's not running
452:55
anymore now we can start the stopwatch and we can stop it we can start it and we
can stop it the last thing we need to do is reset the stopwatch we can really just
copy everything that we have when we
453:09
initially assign these variables we need to clear the timer clear interval p pass
in our variable timer that contains the ID of the set interval function the start
time will be zero the
453:27
elapse time will be zero is running will be false change the text content equal to
all zeros this is for the hours minutes seconds and milliseconds all right let's
see if
453:47
everything works just fine we can start we can stop we can start we can stop we can
reset we can start and we can stop all right everybody so that is how you can
create a stopwatch program using
454:06
JavaScript HTML and CSS hey what's going on everybody so today I'm going to explain
es6 modules in JavaScript a module is an external file that contains reusable code
that
454:22
can be imported into other JavaScript files let's say you write a really difficult
program well any part of that program you can import into a different application
if you don't feel like
454:33
rewriting it modules can contain variables classes functions and more es6 modules
were introduced as part of the ecmascript 2015 update using modules we can create
some reusable code that can
454:45
be used in different programs different JavaScript files so what we'll do in this
example we will create a new file I'll create a module for some math utility
functions this file will be math
455:01
u.j it's a separate Javascript file from our index file we will import this module
mathu till. JS but in order to do so within our HTML file we have to set the type
attribute equal to
455:19
module we'll now treat our index file as a module we can Import and Export other
modules freely but we have to be sure to include this attribute and set it equal to
455:30
module So within our math util module we can write some reusable code for other
programs so let's define what Pi is Pi equal 3.14159 we'll create a function to get
circumference you have to pass in a
455:48
radius though that's going to be the parameter function get circumference we need a
radius we will return 2 * pi time radius then we'll create a function to get area
get area we still need a
456:17
radius we will turn Pi * radius * radius then get volume to get the volume of a
sphere function get volume again we need a radius we will return 4 * < * radius
*
456:43
radius I can reuse these variables and functions for any JavaScript program that I
have I can import them in order to do so though we need to be sure that we prefix
each variable function or
456:53
class or anything else with the export keyword so that we can import it elsewhere
so let's be sure we do that all right be sure to save everything we can close out
of this
457:08
module then from our index CSS file I will import then we're going to use object
destructuring we need a set of curly braces from the location of that module so
457:22
these files are right next to each other relatively speaking the right next to each
other I would need slash the name of that file math util and this is a Javascript
457:35
file now anything I would like to import I'll place within the set of curly braces
we're going to be using object destructuring from this JavaScript module I would
like Pi comma separate
457:49
each entity then I would like get circumference get area get volume I can now use
these variables and functions as if they were already part of my Javascript file
for example I'm going to
458:09
[Link] Pi and Pi does have a value because we imported it let's get the
circumference but we do need to pass in a radius this is a function that we have
imported
458:21
from that mathutils module I will store the result within a variable const
circumference equals we'll invoke the get circumference function from that module
I'll pass in
458:38
10 then we're going to display the circumference I'll use console. log I'll use a
template string include a placeholder display the circumference plus a unit of
measurement like
458:51
cenm 62.83 one8 CM this isn't necessary but I'm going to round this number to two
decimal places using the two fixed method of numbers let's round to two decimal
places let's create an area
459:06
variable const area equals get area I'll pass in 10 for the radius let's copy this
line and paste it because I'm lazy let's display our area variable with cm cubed
31416 cenm cubed then we'll create a
459:29
volume variable const volume equals get volume I will pass in 10 and then we will
display the volume volume cm cubed and our volume if we pass in a radius of 10
would be
459:50
1,256 64 cm cubed all right everybody so those are modules they external files that
contain reusable code that can be imported into other JavaScript files you can
write variables classes functions
460:04
and more that can be reused in other programs you just have to be sure to import
them and well everybody those are es6 modules in JavaScript yo what's going on on
people
460:19
so in today's video I got to explain what asynchronous code is in JavaScript
synchronous is code that executes line by line consecutively in a sequential manner
synchronous code waits for an
460:31
operation to complete for example if I were to use [Link] Let's Pretend We're
performing some task it doesn't matter what the task is we will pretend that task
one is complete then we'll move on
460:44
to task two then task three all this code is synchronous we're executing this code
line by line we can't move on to task two until we complete task one there is an
order of
460:56
events that we need to follow it's code that waits for an operation to complete now
on the other hand asynchronous code allows multiple operations to be performed
concurrently without waiting
461:10
asynchronous code doesn't block the execution flow and allows the program to
continue imagine that asynchronous code is kind of like a time traveler a time
traveler can move out of the flow of
461:22
time but the rest of the world continues time resumes normally asynchronous code
doesn't block the execution flow time moves on with or without it asynchronous code
is typically found with input
461:34
output operations Network requests and fetching data anything that could take an
indeterminate amount of time so for example I will use the set timeout function
after after 3 seconds I will execute a
461:51
function let's [Link] let's say task one we'll change these three lines to be
task 2 task three task 4 I will finish Task 1 after 3,000 milliseconds now check
this
462:08
out we've already completed task 2 3 and four but task one finished last that's
because set timeout is one of many asynchronous functions s the rest of the program
isn't going to wait around for
462:21
it to complete it runs concurrently with the rest of my code that's why task one
was completed at the end and not at the beginning there's different ways to handle
a synchronous code we're already
462:33
familiar with callbacks but there's also promises as well as a sync and a wait we
still need to discuss these topics in the future but we're already familiar with
callbacks if it's crucial that task
462:45
2 through 4 finishes after task one we can use a callback we don't necessarily know
how long this asynchronous function is going to take what we could do in this
example is
462:56
create a function function Funk one meaning function one I will execute this code
within function one then we will accept a callback as an argument then we'll have
function Funk 2
463:16
to do some synchronous code function two will have tasks 2 through 4 after task one
is complete I will invoke my call back to function two so with an arrow function I
have more than
463:31
one line of code I need to add a set of curly braces after task one I will invoke
that call back so then if I call function one I have to pass a call back to
function two so Now function one is
463:54
asynchronous but I need this synchronous code to execute after task one is complete
and now that should work one 2 3 there it is we have task one which is asynchronous
followed by
464:10
task two task three and task four so by using callbacks that's one way in which we
can handle asynchronous code but we still need to discuss promises a sync and a
wait which are future topics
464:24
all right everybody so that is what a synchronous code is synchronous code executes
line by line consecutively in a sequential manner asynchronous code allows multiple
operations to be
464:36
performed concurrently without waiting asynchronous code doesn't block the
execution flow and allows the rest of the program to continue asynchronous code is
commonly found with input output
464:49
operations Network requests and fetching data usually anything that takes an
indeterminate amount of time and well everybody that's what asynchronous code is in
JavaScript hey people so in today's
465:05
video I'm going to explain error objects in JavaScript and how to handle them an
error is an object that is created to represent a problem that occurs errors occur
often usually when we accept user
465:17
input or establish a connection it's an object that's created to represent a
problem so for example I am going to [Link] the word hello and then afterwards
I'm going to display a
465:31
message to indicate that we have reached the end of the program you have reached
the end this runs as it should right let's say I misspell log as leg well we
encounter an uncaught type error there's
465:47
many different types of Errors console. leg is not a function type errors tend to
happen when we try and access something within an object that doesn't exist one big
issue that we run into is
465:59
that we prematurely exit the program it never finishes executing we have not
reached the end errors when they're uncaught interrupt the normal flow of our
program another example of an error
466:11
would be a reference error I will [Link] X but X isn't defined we have an
uncaught reference error X is not defined and again it interrupts our program we
never reach the end errors
466:25
can be generated for all sorts of issues such as network issues promise rejection
which we still need to talk about and security errors when we encounter a problem
when doing one of these things
466:36
an error object will be generated and it interrupts our program there's a solution
though and that is to handle these errors when they occur we can do that with try
catch and find blocks with
466:49
the tri block we can enclose any code that might potentially cause an error such as
if we're trying to establish a connection to something if that connection fails an
error can occur if
467:01
we don't handle it it's going to interrupt our program so all of this code I will
place within a tri block we will try all of this code but we need a catch block
467:14
too the catch block has one parameter it will catch an error object then let's
[Link] the error object to see what it is so let's run this we have a
reference error a is not defined see now
467:33
we are reaching the end of the program the program is not being interrupted we have
gracefully handled this error before it was uncaught but now it's caught for
catching errors I wouldn't
467:44
recommend using [Link] rather I would use console . error this will highlight
any errors that occur and still handle them it's good for debugging we can clearly
see
467:55
the error reference error X is not defined and again it doesn't interrupt our
program we still reach the end now optionally you can add a finally block the
finally block always executes
468:09
regardless if an error comes up the finally block is usually used for closing files
closing connections or releasing resources usually when you open something or
establish a connection
468:20
you need to close it afterwards you don't want to leave it open that's where the
finally block comes in do any cleanup at the end whether or not an error occurs so
just to test this I'm going to
468:34
[Link] this always executes I'm going to [Link] X we have a reference
error it is caught so it doesn't interrupt anything we're still executing the
finally block and we
468:50
reach the end of our program if we don't run into any errors I'm going to
[Link] hello there are no errors that occur we don't end up catching anything
this
469:01
always executes the finally block and we reach the end of our program so any code
that is considered dangerous where it could cause an error you'll want to surround
with a tri block and then catch
469:12
them in the future if you ever open any files or establish a connection you'll want
to finally block two close those connections but we haven't discussed that yet
errors can also occur when
469:22
accepting user input because we don't know what the user is going to type in in a
worst case scenario a user could type in a malicious script in this next example
I'm going to create a constant
469:33
for a dividend and a advisor const dividend equals window. prompt enter a dividend
with division a dividend is the number that is being divided and we need a diviser
a divisor is the number we're
469:57
dividing by enter a divisor then I'm going to create a constant result result
equals our dividend divided by our diviser [Link] the result what is 1 / 2 0.5
now mathematically speaking we can't
470:24
divide a number by 0 if you attempt to do this in JavaScript I will divide 1 by
zero you end up with infinity we can intentionally cause errors then handle them
with try catch and optionally
470:38
finally blocks so this code is considered dangerous I'll place it within a tri
block we need to catch any errors catch an error object if it occurs then console.
error the error
470:59
object so just to test this instead of console. log I'll misspell log as leg I
should probably add a message just to confirm that we have reached the end you have
reached the end 1 / 0
471:19
type error console. leg is not a function but we still reach the end our program
isn't interrupted within a tri Block in certain situations we can intentionally
cause an error I'm going to use an if
471:34
statement if our divisor is equal to zero then I will throw a new error object
we're calling the error Constructor to constru conu a new error object within the
Constructor we have
471:51
one argument we can pass in a message what is the error going to say you can't
divide by zero okay let's try this enter a dividend one enter divisor I'll type in
zero then press
472:07
okay we have a caught error you can't divide by zero our program isn't interrupted
we still reach the end let's change console. Le back to log cuz I forgot to do that
what if somebody
472:20
attempts to type in something that's not a number enter a dividend one enter a
divisor I'll type in the word Pizza not a number you have reached the end I would
like to throw a new error
472:32
when somebody doesn't type in a number what I can do is that with our prompt I will
typ cast it as a number if somebody enters in some non-numeric characters for
either the
472:46
dividend or the diviser we will store within there not a number so let's check that
with an if statement if is not a number if our dividend is not a number or our
divisor is not a
473:05
number let's throw a new error throw new error values must be a number I will
divide one by the word Pizza error values must be a number we still reach the end
of our program with
473:26
error objects you can even create your own in certain situations and then you can
handle them however you want all right everybody so those are error objects and how
to handle them an error
473:36
is an object that is created to represent a problem that occurs they occur often
with user input or establishing some sort of connection to handle them you can use
try catch and
473:49
optionally finally blocks which are mostly used for cleanup if there's any code
that can cause an error place it within a tri block and catch any errors that
happen and well everybody that is
474:00
how to handle errors in JavaScript hey what's going on everybody in today's video
we're going to create a calculator program using HTML CSS and JavaScript so let's
get started all
474:15
right let's do this thing everybody we have a lot of buttons to create but we'll
need a container I will create a div element the div element will have an ID of
calculator within the div element we'll
474:29
create an input element the input element will have an ID of display to display the
numbers that we type in I don't want somebody to enter in some text for the display
I would like this display to be
474:45
readon I will add the read only property so we can't type in anything even though
I'm trying I will create a nested div element that has an ID of keys for all of the
keys we need to add a lot of
475:01
buttons we'll begin with the first I will create a button element the text on the
button will be plus I will set the on click attribute of this button to be a
JavaScript function we still need to
475:16
Define this fun function eventually we'll create a append to display function we
have one argument to pass into this JavaScript function a character of plus that's
our first button let's copy
475:34
this button and paste it 13 additional times if I counted right okay the second
button will be seven the character we're passing in is seven followed by 8 9 minus
4 5 six asterisk for multiplication 1
476:14
2 3 forward slash for division then zero and here are the new buttons I miscounted
we need to add one more a DOT for a decimal now we need an equals button we're
going to arrange that a little
476:35
different let's create a button with the text of equals the onclick attribute of
this specific button is going to be calculate then we need a button to clear our
screen the text on this button will be
476:57
capital c for clear the onclick attribute of this button is going to be clear
display and that is all the buttons we'll need so let's save everything and let's
go to our CSS
477:14
stylesheet I'm going to zoom back to 100 % first let's style all these buttons I
will select all buttons for each button I will set the width to be 100 pixels the
height to be 100 pixels so they're
477:33
even I would like rounded buttons I will set the Border radius property to be 50
pixels so they're circles let's remove the border border none I'll change the
background color of
477:51
the buttons background- color I'll use hsl values I'll set the lightness to be 30%
so they're darker for the text of the button I will set the color to be white for
the font
478:09
size I will set that to be 3 RM set the font weight to be bold then when I hover my
cursor over one of the buttons I would like my cursor to be a pointer cursor
pointer now we have to arrange these
478:32
buttons properly let's select the ID of keys keys is a development that's
containing all of the buttons this element all of the buttons are within to arrange
these buttons in a grid we
478:50
can set the display property to be a grid for this calculator I would like four
columns to do that I will set the grid template columns property to be we'll use
the repeat function of
479:09
CSS I would like four columns then to arrange these buttons evenly you can use one
f r f FR stands for fractional unit one F FR indicates that each column should take
up an even amount of space
479:25
so now we have Columns of four if I were to set this to three we would have Columns
of three but I'm going to use Columns of four because I would like all of the
operators on the left hand side
479:37
I'll set the Gap to be 10 pixels that is the gap between each of the rows then I'll
add some padding of 25 pixels that's padding around the keys let's select the ID of
479:56
calculator I'll add that to the top to keep everything organized with our
calculator I will select a font family of aiel with a backup of s serif let's pick
a background color for the
480:15
calculator I will select something darker I'll set the lightness to be 15% I'll
round the corners of the calculator border radius 15 pixels the corners of the
calculator are smooth
480:35
now then I will set a Max width of the calculator to be 500 pixels if any elements
overflow I will set that to be hidden this is mostly for our display if we have a
very long equation all right
480:53
next let's select the display right now it's kind of small we are selecting our ID
of display let's set the width to be 100% I'll add some padding of 20 pixels for
the text of the display I
481:14
will set the font size to be 5 RM let's text a line left I'll remove the border
border none and I'll change the background color I'll just copy this property
because I'm lazy let's increase the
481:38
lightness to 20% then we'll select the body of our document I will remove all
margin margin zero I would like the calculator to be in the middle of my window
right now
481:59
it's in the top left corner if you would prefer it up here you can leave it as is I
will set the display to be Flex for Flex box justify content in the center for a
horizontal
482:16
alignment M for vertical alignment we can set align items to be Center but we do
need to increase the height of the body of the document so it's 100% I will set the
height to be 100 VH
482:34
for 100% of the viewport height that should place the calculator in the middle of
the body of our document both horizontally and vertically for the background color
I'm going to decrease
482:45
the lightness slightly for the background color I will set the lightness to be like
95% okay let's go to the bottom of our CSS stylesheet when I hover over one of
482:59
these buttons I would like to increase the lightness so with all buttons with the
hover sudo class change the background color so the lightness is 40% instead of 30
now these buttons light up when we
483:17
hover our cursor over one of the buttons now when I click on one of the buttons
I'll increase the lightness further so it flashes we are selecting the active
pseudo class
483:29
now let's take our background color property increase the lightness to 50% when we
hover over a button it lights up when we click on it it flashes momentarily so with
all of these
483:44
operators I would like all of these op buttons to be a different color I'll pick
orange we're going to give each of these buttons a new class let's head back to our
HTML file beginning with the
483:55
plus button I will set the class equal to operator Das BTN for button so let's copy
this class paste it for our minus button multiply button divide button and the
clear
484:20
button now we will select the class of operator BTN for button let's change the
background color I'm going to set the background color to be orange I've already
pre-picked a
484:41
color when I hover my cursor over one of the operator buttons I would like the
color to be a lighter orangee instead of gray let's take our operator button access
the hover sudo class I'll
484:55
increase the lightness to 65% then when I click on one of these buttons I would
like the lightness to increase further with the operator button class with the
active pseudo class
485:10
increase the lightness to 75% so when I click on one of the operator but buttons
it's going to flash momentarily all right and that is all the HTML and CSS that we
need now we
485:23
just need to add functionality let's go to our Javascript file for our Javascript
file there's not a lot we have to write first we need to get the display element so
what was that ID
485:37
display const display equals document. getet element by ID get the ID of display we
have three functions to create a function for append to display calculate and clear
display these three
485:59
functions function append to display there is one parameter input because we were
passing in a character when we call this function then we have a function to clear
display then a function to
486:28
calculate we'll begin with a pen to display all we're going to do is take our
display this element access its value append it with plus equals our input and
let's see if this works seven
486:46
I forgot to change the font color of the display so let's do that within our
display element let's set the color to be white okay that's much better 7.13 + 5
equals okay we know that that
487:08
works when I click on the clear button I would like to clear this display let's
access our display element at access the value property set it equal to an empty
string
487:23
3.14159 when I hit clear it should clear the display lastly we have calculate let's
take our display elements value property set it equal to now we're going to use the
eval
487:39
function the eval function takes an expression such as 1 + 2 + 3 and evaluates it
and gives a result it's kind of like it's its own built-in calculator so to say
evaluate the value within our
487:55
display display. value so if I add 3.14 plus 1.01 I'm given a result of 4.15 now
for some reason if we get an error for example 7 + equal well we have a problem
let's go to our
488:19
console we've encountered an uncaught syntax error because we never finished our
equation in the last lesson we learned about error handling this is dangerous code
it can cause an error
488:32
let's surround this code with a try block we will try this code and catch any
errors that happen so we need a catch block now catch any errors we will change the
value of the display
488:50
to equal some text of error all right and that should work 3.14 times equals that
results in an error we can clear it and then start over what's 1 + 2 + 3 + 4 that
would be
489:13
10 all right everybody so that is is a calculator program you can make using
JavaScript HTML and CSS impress your friends all right what's going on people so
today I got to explain what the Dom
489:29
is in JavaScript the Dom is the document object model it's a JavaScript object that
represents the page you see in the web browser and it provides you with an API to
interact with it the web browser
489:42
constructs the Dom when it loads an HTML document and structures all of the
elements in a tree like representation within my HTML document we have our HTML
element as the root element the HTML
489:54
element contains a head element and a body element and many various elements can be
found within each of these they're arranged in a tree likee data structure but we
access this tree like
490:04
data structure from the document object in past lessons in order to select an
element by its ID we would type document dot then follow it with a method like get
l element by ID and then we would
490:18
select an element by its ID our document is an object it contains properties and
methods and other nested objects if I was to [Link] the document well then
it's going to display my HTML
490:36
document now you can also use dur meaning directory this will list all of the
properties of this object so here's my document object and all of the different
properties it
490:49
contains it's one gigantic object for example we have a title the title of the web
page that would be found right here near the bottom document but you can change
491:02
it I will access our document as if it was an object because it is access the title
property change it to something else like my website now if I display the title
491:17
that property has changed it's now my website dynamically after the page loads I
would like to change the background color of my document later on in the series
we're going to create a toggle
491:27
button to toggle between light and dark mode just to give you an example if I need
to change my theme to be dark mode I could access the document object access the
491:38
body access the style then change the background color property to some color let's
stick with black for now I'll use hsl the Hue will be zero saturation will be 0%
and the lightness will be
492:00
15% even though we have no CSS we're still able to dynamically change the
background color let me give you another example we'll create an H1 element this H1
element will say welcome
492:16
I will give this element an ID ID welcome- MSG meaning message and I'm just going
to zoom in a little I will create a constant of username type in your username or
your full
492:37
name I'm going to conditionally change the content of this HTML document I will get
this element by its ID our welcome message const welcome message I'm using camel
case naming convention for this so
492:54
I will access my document use the get element by ID method that ID was welcome-
message MSG for short I would like to update the text content of this element I'll
take my welcome
493:11
message access the text content of it then appen some text using stringy catnation
I'll use the tary operator to see if my username is strictly equal to an empty
string is our username empty
493:27
did somebody not type it in question mark If username is empty I will append our
welcome message with guest otherwise our username my username has a name it's not
empty it will display my name welcome
493:45
Thro code if it was empty if somebody didn't type it in it will display welcome
guest so that's an introduction to the document object model the document object
model is a JavaScript
493:57
object that represents the page you see in the web browser and it provides you with
an API to interact with it the web browser constructs the Dom when it loads an HTML
document and structures all of
494:08
the elements in a tree likee representation by using JavaScript we can access the
Dom dynamically after the page loads and change the content structure and style of
a web page and
494:19
well everybody that is an introduction to the document object model in JavaScript
hey it's me again so today I got to explain element selectors in JavaScript element
selectors are methods
494:34
used to Target and manipulate HTML Elements by using these methods they allow you
to select one or more multiple HTML elements from the Dom the document object model
these methods are built-in
494:47
methods of document the Dom we can select Elements by an ID a Class A tag name and
then there's query selector and query selector all these methods return something
different either an element an
495:00
HTML collection or a node list one method you're probably already familiar with is
get element by ID so in this example within our HTML document we will create an H1
element I will create a
495:13
heading for my sample web page I'm hungry so I'm going to talk about food my
heading is going to be food are us it's like Toys R Us but it's with food I'm going
to give this H1 element an ID
495:28
of my Dash heading so going back to our Javascript file I can select this element
by its ID I'll store a reference to it const my heading equals we're accessing the
Dom with
495:46
document. get element by ID that ID was my heading I can access this element this
H1 element using this reference so let's take my heading access its style access
its background
496:07
color so with CSS properties in JavaScript if you're accessing them through the Dom
they have a camel case nameing convention if you're selecting these properties with
496:18
CSS they have a hyphenated naming convention so do pay attention to that so with
the background color I will set it to be yellow as if we're highlighting it you
could also apply different CSS
496:31
properties let's take my heading access its style access the text align property
and set it to be Center and it's now centered now if I was to [Link] this
element of my heading
496:50
this is what we would see it displays my HTML element including its style if it has
style for some reason if this ID doesn't exist for example I'll misspell heading as
heading
497:06
with an extra G well this returns null if I were to eliminate these two lines of
code you can see that null get element by ID returns a single element if it finds
it or null if it doesn't the
497:22
next method is get Elements by class name this returns an HTML collection it's
similar to an array but it's limited in the built-in methods that it has So within
our HTML document I will
497:35
create three separate div sections this first development will have a class of
fruits my first fruit will be apple so let's copy this development paste it two
times I'll change the second to be
497:51
orange then banana all right going back to our Javascript file I will use this
method of get Elements by class name this will return an HTML collection it's
similar
498:04
to an array but it's not technically the same so const fruits this will be the name
of my HTML collection equals docu doent we're accessing the Dom get Elements by
class
498:21
name what is the class name that we're getting fruits let's console. log fruits
just to see what it is what are we working with so fruits is an HTML collection my
498:42
collection contains these three elements we have three objects within this HTML
collection if I was to take a look at some of these properties we should have text
content so for the first element we
498:54
have text content of Apple for the next div element which has an index of one the
text content is orange we can assume that the next element has text content of
banana to change something about one
499:07
of these elements let's begin with the first element we have an HTML collection of
fruits to select one of these elements you'll use an index so let's take our HTML
collection of fruits at
499:21
index zero that's going to return the first element our div element of Apple I will
access its style access its background color set it equal to be yellow as if we're
highlighting
499:35
it there we are Apple it's highlighted for the next element I will increase the
index to one that will select our orange and then two would be banana if I would
like to iterate over all of these
499:48
elements I can use an enhanced for Loop we'll say let fruit of fruits HTML
collections are iterable we can iterate them with an enhanced for Loop let's take
each fruit access its
500:07
style access its background color then set it to be yellow and that should
highlight all of them now HTML collections don't have a built-in for each method
HTML collections do allow for live updates
500:24
but unfortunately they have a limited amount of utility methods if I attempt to use
our HTML collection of fruits then attempt to use a for each method here's what
500:38
happens we have a type error fruits. 4 each is not a function HTML collections
don't have a for each method we're not able to use that what we could do is typ
cast our HTML collection as an array
500:55
let's access the class of array then use the from method this will return a new
array of fruits we'll typ cast our HTML collection as an array then you could
follow this with the for each method if
501:11
you so choose for each element within our array after type casting it let's take
each fruit I'll use an arrow function what would we like to do let's take each
fruit access its
501:25
style access its background color then set it to be yellow as if we're highlighting
it and that does work get Elements by class name will return an HTML collection of
all matching elements that
501:41
share this class if you would like to use array method me with this HTML collection
you would want to typ cast it to an array all right now we have get Elements by tag
name within our HTML
501:54
document we'll create two unordered lists I will create an H4 heading of root
vegetables let me scroll down I will create an unordered list with a few list items
three should
502:12
be good for my first list item that will be beets beets are a root vegetable
carrots and potatoes let's copy our unordered list and our H4 heading paste it
change the second H4 heading to be nonroot
502:36
vegetables my first list item within this other list will be broccoli celer and
onions I just picked three vegetables kind of at random with our next method of get
502:54
Elements by tag name I can select one of these elements by their tag name H4
unordered list list items take all matches within our HTML document stick them all
within an HTML collection I
503:08
will create const const H4 elements equal alss we're accessing the Dom use the get
Elements by tag name method let's select all H4 elements then I will [Link] my
HTML collection of H4
503:33
elements let's see what it is so it looks like this HTML collection has two
elements two H4 elements the text content of the first element is root vegetables
then we can assume that the
503:47
other element is non-root vegetables yes it is non-root vegetables we can access
individual elements of this HTML collection by an index let's take this reference
of H4 elements access the first
504:04
index access the style access the background color set it to be yellow as if we're
highlighting it and that should highlight root vegetables the next index of one
would be non-root vegetables to
504:20
apply CSS properties to all of the elements I can use an enhanced for Loop for let
H4 element singular of H4 elements plural take each H4 element access its style
access its background
504:40
color set it to be yellow and that will highlight all of the H4 elements let's
create another HTML collection of all the list item elements we'll create another
reference to all
504:52
list item elements so that'll be beets carrots potatoes broccoli celery and onions
const Li elements equals document. getet Elements by tag name the tag that we're
selecting is all list item elements
505:15
so using a for Loop let's iterate through them let Li element singular of Li
elements plural for each list item element access the style access the background
color then set it to be a
505:34
different color let's say light green and now all list item elements will be a
light green color and again since the these are HTML collections not arrays they
don't have any array methods
505:49
but we can typ cast them so that they do if I wanted to change the background color
of these with the for each method of arrays I'm going to typ cast our HTML
collection of H4 elements as an
506:01
array I will access the class of array use the from method pass our HTML collection
of H4 elements as an argument if I wanted to use the for each loop I can method
change
506:15
follow this with for each what do we want to do for each of these elements take
each H4 element use an arrow function do this take each H4 element access its style
access its background
506:31
color set it to be yellow and that does work so let's do this with our list item
elements I'll just copy this because I'm lazy we'll type cast our list item
elements HTML
506:46
collection for each list item element take each list item element access its style
access its background color set it to be light green and that does work to that is
the get Elements by tag name
507:03
selector it will select all elements with a matching tag name throughout your
document it returns an HTML collection now we're going to talk about query selector
query selector will
507:15
return the first matching element or null if it doesn't find any matches I will
create a const of element equals document. query selector query selector will
return the
507:31
first match to select an element by a class name we'll use dot the name of the
class these three elements have a class of fruits let's select that dot fruits if I
was to take this element access its
507:48
style access its background color set it to be yellow which element do you think is
going to be selected the first Apple it's the first matching element Cory selector
only returns a single element
508:03
the first match if I selected a tag name of H4 that would select root vegetables
even though we have two H4 elements the first matches selected if I selected the
first list item element that would
508:19
select beats that is the first list item element on my web page if I changed this
to UL meaning unordered list it would select the first unordered list if I attempt
to select something that doesn't
508:33
exist like any ordered lists well they don't exist there's no matches if I was to
[Link] my element it would return n there's no matches so query selector
selects the first
508:53
matching element or null you can select a class or a tag name then the last method
we'll discuss is query selector all this returns a node list a node list is similar
to an
509:08
HTML collection except it has built-in methods similar to arrays however no lists
are static HTML collections are live since node lists are static they do not update
automatically in the Dom HTML
509:23
collections are live they will I'm going to select all elements that have a class
of fruits I'll create a reference to this const fruits equals document. query
selector
509:40
all we are getting a class of fruits I can access this node list by an index number
let's select the first element access the style access the background color set it
to be
509:59
yellow and that will select Apple let's select the next element that's orange the
next would be banana let's select all list item elements I'm going to rename this
though let's rename fruits as
510:17
Foods let's select the first element that would be beets the next element would be
carrots then potatoes broccoli celery onions so if I was to [Link] Foods this
would give me a node list with six
510:41
elements node lists do have a built-in for each method let's use that we don't need
to typ cast it as an array take our node list of foods use the built-in for each
method what do we
510:55
want to do take each food use an arrow function do this take each food access its
style access its background color set it to be yellow this will take all list item
511:12
elements change the background color to Yellow as if we're highlighting them all
right everybody so those are different element selectors get element by ID get
Elements by class name get Elements by
511:23
tag name query selector and query selector all there is a lot of overlap where you
could select any number of these to select something but they each return something
different personally I
511:33
like using a combination of get element by ID and query select all but that's just
my personal preference in conclusion element selectors are methods used to Target
and manipulate HTML
511:46
elements they allow you to select one or more multiple HTML elements from the Dom
once you select your element or elements you can make any sort of changes that you
would like and well everybody those
511:57
are element selectors in JavaScript yo what's going on people so today I got to
explain Dom navigation in JavaScript Dom navigation is the process of navigating
through the structure of
512:13
an H HTML document using JavaScript HTML elements include but are not limited to
the following properties for D navigation we can get the first child the last child
the next sibling the
512:25
previous sibling a parent or all the children of an element so for this exercise
within our HTML document we're going to create a few unordered lists of course
these unordered lists are going
512:37
to be for food because I like food the first unorder list will have an ID of fruits
let's create a few list item elements an apple an orange and a banana we'll need a
few unordered lists
512:57
to work with let's copy this unordered list and paste it twice the second list will
be for vegetables pick some vegetables I'll pick carrots onions potatoes the third
unordered list will be for
513:18
desserts I'll pick cake pie ice cream that is good enough for now heading back to
our Javascript file I will now discuss the property of first element child our
unordered lists are
513:37
elements they each have their own children a child element is any element found
within this element our unordered list of fruits has three children Apple orange
banana vegetables has three
513:52
children carrots onions potatoes desserts has three children as well cake pie and
ice cream let's say that our unordered list of fruits is a parent well Apple would
be the firstborn orange
514:05
would be the middle child and banana would be the last born if these were actual
children so think of it that way so so I'm going to create a constant of element
I'll be using this as a
514:18
reference document. getet element by ID I will get that unordered list of fruits
I'm storing this unordered list within this element I will create a reference for
514:32
the first child equals take our element access the first element child if I was to
take this element change its style access its background color set it to be yellow
which element is going to be
514:54
highlighted Apple if I selected a different element like my Ida vegetables the
first child would be carrots then desserts the first element child of desserts is
cake they are the firstborn
515:11
children they're at the top Within These un ordered lists if you used query
selector all I'll give you a demonstration I will select all unordered lists const
UL elements equals
515:27
document dot query selector all select all unordered lists this will return a node
list node lists do have their own built-in for each method take all UL elements use
the
515:45
built-in for each method what do we want to do iterate over every unordered list
element do this let's create a reference to the first child equals take our
unordered list
516:06
element access its first element child then store it as a reference let's take our
first child access its style access its background color property set it to be
yellow that will highlight all of the
516:26
first element children of all the unordered lists so that's how you can use Query
selector all to select all of the first children of all matching elements now we're
going to access last
516:39
element child with our unordered lists if we're select ing our elements of fruits
vegetables and desserts this would return the last child banana potatoes or ice
cream depending on what
516:52
we're selecting if these were actual children these three elements are the last
born they're the youngest I'm going to create a reference to an element equals
access the Dom get element by ID
517:08
I will get my ID of fruits I will create a reference refence to the last child
equals take our element get the last element child take our last child element
access its style access its
517:31
background color set it to be yellow so that will highlight banano if I change the
selected element to vegetables that would select potato es if I selected desserts
that would select
517:47
ice cream they are the last element children found within each of these elements if
I were to use Query selector all to select all unordered lists let's create const
UL elements equals
518:03
document. query selector all select all unordered elements this returns a node list
they have their own built-in for each method take our node list of unordered
elements use the built-in for each
518:22
method take each unordered list element use an arrow function to do this I will
create a reference to the last child equals take each unordered list element access
the last element
518:41
child take the last child during each iteration access its style access its
background color set it to be yellow and that will select banana potatoes and ice
cream select all unordered lists take
518:59
each of their last children change the background color to be yellow so that is the
last element child property in this next example I'll demonstrate next element
sibling but we're going to make
519:11
a few changes going back to our h HTML file we will give each of these list items a
unique ID so let's start with the first the ID will be Apple for the first list
item element I'll copy this
519:24
ID for each of these elements and then change them in a moment so we have apple
followed by orange banana carrots onions potatoes cake pie then ice cream if I'm
selecting my unordered list of
519:47
fruits Apple orange banana or the children they are all siblings to each other if I
were to select Apple then get the next sibling that would be orange if I select
carrots the next sibling would
519:59
be onions if I selected cake the next sibling would be pie so let's create a
constant of element equals document. getet element by ID the ID that I'm going to
select is
520:16
Apple I will create a reference to the next sibling equals take our element access
its next element sibling take our next sibling access its style access its
background color set it to be
520:38
yellow if I'm selecting Apple the next sibling to that would be orange if I were to
select orange the next sibling would be banana if I were to select banana well
banana doesn't have a
520:50
next sibling it's the last in line we wouldn't be selecting anything there is no
next sibling for banana if I were to select carrots the next sibling is onions if I
selected onions the next
521:03
sibling is potatoes if I selected cake the next sibling is pie if I selected pie
the next sibling is ice cream what if I SEL selected fruits vegetables or desserts
what would be highlighted I
521:17
will select the ID of fruits that would highlight my unordered list of fruits these
three unordered lists of fruits vegetables and desserts they're all children of the
body they're all siblings to one
521:33
another it's kind of like if the list item elements of Apple through ice cream are
all children the unordered lists of fruits vegetables and desserts are the parents
521:43
and the body is the grandparent if I select the unordered list of fruits the next
sibling would be vegetables by accessing the next element sibling of my unordered
list of fruits
521:56
that selects my unordered list of vegetables if I selected vegetables then get its
next sibling that would give me this unordered list of desserts all right then we
have previous
522:09
element sibling if I select an element we'll get the the previous element sibling
so if I were to select orange that would give me Apple if I selected banana that
would give me orange if I
522:20
selected onions that would give me carrots I will create a constant for element
equals document. getet element by ID I will select orange const prev meaning
previous
522:39
sibling equals take our element access the the previous element sibling if I were
to take my previous sibling access it style access its background color set it to
be
522:55
yellow the previous sibling of orange is Apple the previous sibling of banana is
orange if I selected onions the previous sibling is carrots the previous sibling of
potatoes is
523:15
onions the previous sibling of pie is cake the previous sibling of ice cream is pi
if I selected the first sibling then attempt to get the previous sibling well we
don't select anything
523:33
the previous sibling of a first child doesn't exist if I selected the previous
sibling of my unordered list of vegetables that would select my unordered list of
fruits if I selected
523:47
the unordered list of desserts that would give me vegetables now we have the parent
element property whichever element I select will get the parent the parent is the
element that contains
524:02
it const element equals document. getet element by ID I will select Apple const
parent equals access our element access the parent element let's take our parent
access its style access
524:28
its background color set it to be yellow that will highlight my unordered list of
fruits if I selected orange well that wouldn't change the parent is still fruits
same thing goes with banana
524:43
if I selected carrots well the parent is vegetables that unordered list if I
selected ice cream while the parent is desserts so that's how to get the parent of
an element you can access the parent
524:58
element property the last property we'll discuss is children we can return all of
the children of a selected element I will create a const element equals document.
getet El element by ID I will
525:15
select my ID of fruits I would like all children of this element I'll create a
reference to Children equals take our element access the children property if I was
to [Link]
525:31
Children this is what we're working with by accessing the children of an element
that returns an HTML collection this HTML collection has three list item elements
HTML collections don't have a
525:48
built-in for each method I would need to typ cast it as an array using the from
method of arrays let's take all of our children convert it to an array then method
chain the for each
526:01
method let's take each child from children then do this take each child during each
iteration access its Style access its background color set it to be yellow so this
will highlight all
526:20
children of a selected element Apple orange then banana if I selected vegetables
that would highlight carrots onions potatoes if I selected desserts that would
highlight cake pie then ice cream
526:37
you can even access these children by an index number let's say you would like to
highlight a middle sibling orange onions or pie let's take our children it's an
HTML
526:52
collection access it by an index number so let's access children at index one of
desserts that would highlight pie let's select vegetables that would highlight
onions then fruits would highlight
527:08
orange all right everybody so that is an introduction to Dom navigation it's the
process of navigating through the structure of an HTML document using JavaScript
there are several different
527:19
properties that you can use to navigate through HTML elements and well everybody
that is an introduction to Dom navigation in JavaScript hey everybody in today's
video I'm going to show you how we can
527:33
add and change HTML elements using JavaScript so sit back relax and enjoy the show
I'll break down creating an appending element El to the Dom in three simple steps
we'll create the element
527:46
add any necessary attributes or properties and then append the element to the Dom
will be the final step but before we do begin within our HTML file we'll create a
few boxes for this
527:56
exercise these will be developments with an inner paragraph the first will have
text of box one with this development I will give it an ID of box one and a class
of box
528:13
let's copy the div element paste it three times for a total of four boxes we'll
create box two box three and box four I'll apply the following CSS properties we're
selecting the Box class
528:32
add a border 3 pixel solid set a width to be 100% and a height of 125 pixels and we
are ready to begin step one we need to create the element in order to work with it
right I will
528:46
create a constant of new H1 H1 equals we will select our document use the create
element method then as a string pass in the type of the element we would like to
529:00
create we'll create an H1 element we now have an H1 element to work with which
we're referencing as new H1 let's add some attributes and CSS properties let's do
one for now now I will take my new H1
529:15
element access its text content set it equal to I like pizza and then we just have
to append this element to the Dom to do that we will access our Dom with document
what element would we like to
529:35
select let's select the body element of our document and then we will use the
append method pass in our HTML element as an argument and there we go there's our
H1
529:47
element when you append an element to a parent this new element is the last child
you could prepend if you would like it to be the first child so let's use the
prepend method change aend to
530:03
prepend and it's now at the beginning let's add an additional attribute we will
take our new H1 element set the ID attribute equal to my H1 and let's see if that
worked I will
530:18
rightclick on this element inspect it here's our H1 element it's the first child
because we're prepending it this H1 element has an ID attribute set to my H1 let's
change the CSS properties of
530:34
this element I will access new H1 access its style access its color the f color
let's set it to be red but better yet let's set the color to be tomato because I
like tomatoes I
530:50
think that's a better looking shade of red let's also Center the text new H1 access
its style access the text align property set it to be Center and the text is now
centered when
531:07
I append this element I would like to append it to within box one I will select box
one as the parent rather than the body we will access our document we need to
select an element we will select box
531:22
one we could use document. getet element by ID the ID that I'm going to select is
box one I will then follow this with append append our new H1 element so our H1
element is now within
531:43
box one and not outside of it like it was previously I could append this H1 element
to box two but I would have to select it we will get element by ID select box two
to put it within box two
531:57
box 3 and box four when I'm appending this element to box one it is the last child
of box one if there are any child elements within this box which there is we have a
paragraph element
532:12
that H1 element will come after and not before so if you would like this H1 element
to be the first child we can prepend it I'm going to copy this because I don't want
to rewrite it we will
532:29
prepend prepend my new H1 element take box one prepend the new H1 element so my H1
element is now at the top it's the first child the paragraph element comes after
let's do this with box two box 3
532:46
and box four what if we would like to take our H1 element and sandwich it between
box one and box two I could select box two and insert that new H1 element before it
here's how I will
532:59
create a reference to box 2 equals document. get element by ID we will select the
ID of box two access our document access the body because box two is a child
element of
533:20
the body use the insert before method there's two arguments the new element and the
current element the new element is going to be new H1 that's what we're trying to
add
533:37
the current element is the target we're selecting box two in insert the new H1
element before box two and this is what that looks like this H1 element is now
between box one and box two take the new
533:51
H1 element insert it before box two if we were to do this with box one well then
it's going to be before box one let's try this with box three our H1 element is
before box three and box
534:10
four what if these elements don't have IDs how do we select them then here's how we
will use Query selector all to select everything that has the Box class I will
create a constant of boxes this
534:29
will be a node list access our document use Query selector all select everything
that has a box class we will use the the insert before method access our document
access the body insert
534:50
before we have the new element to add and the current element the new element is
new H1 the current element is our node list of boxes we can access a specific
element from this node list
535:06
with an index if I accessed boxes at index zero that would give me box one boxes at
index one that's referring to box two box three and box four so you could use Query
selector to select many
535:23
elements store it within a node list then select those specific elements with an
index number this is optional but at any time if you need to remove an HTML element
here's how let's append our new H1
535:38
element we need to select the location in which we can find that element it's
within the body of our document [Link] use the remove child method we will
remove our new H1 element
535:57
and it's gone what if this H1 element was within box one all right I will append
our new H1 element to box one and we need to add the IDS back to these boxes
because I forgot to do that we're
536:10
pending our new h one element to box one when I try and remove it it doesn't work
it's still there we need to select box one and not the body of our document because
box one is the direct parent of
536:24
our H1 element not the body the body in this case could be like the grandparent
instead of selecting our body we will get the ID of box one or some other element
selector to get box
536:36
one I'll use get element by ID because it's easy get element by ID the ID that I'm
selecting is box one remove the new H1 element that's found within it and it's gone
if at any time you need to remove
536:53
an element select the parent of that element then follow it with the remove child
method pass in the element you're trying to remove as an argument in this last
example we're
537:04
going to work with ordered lists so going to our HTML file we will create an
ordered list with a pair of of O tags I will give this ordered list an ID of fruits
we'll add a few list items the
537:19
first list item will be for an apple the ID will be apple we'll create a list item
element for an orange ID will be orange and a banana ID banana I'll add a little
bit of CSS
537:41
styling going to the CSS stylesheet I will select the ID of fruits I'll add a
border of three pixel solid for this demonstration and increase the font size to 2
RM all right and that's what we need to
538:01
work with we'll now be creating a list item element I will create a constant of new
list item equals document. create element what is the type of element we're trying
to create a list item
538:21
element let's set any attributes or properties that's step two let's take our new
list item set the text content to equal coconut we'll append this element if I
538:37
were to append this new list item to the body of my document it's the last child of
the body we're not adding it to this ordered list now that we can see it I'm going
to add a
538:48
few more attributes and properties let's take our new list item access its ID
attribute set it to be coconut let's change the font weight new list item access
the style access the font
539:08
weight set it to be bold and the background color access the style access the
background color I'll set the background color to be light green we have our list
item element if I
539:29
append it to the body it's now the last child of the body of my document not this
ordered list found within the body if I were to prepend it this is what would
happen prepend the new list
539:42
item it's now the first child now we'll select our ordered list of fruits get
element by ID fruits append the new list item and it's now at the end at number
four let's prepend to the ordered
540:03
list get element by ID fruits prepend our new list item our coconut is now at
number one how can we insert our coconut between Apple and Orange here's how since
these
540:18
list item elements have an ID I could use that let's get the ID of orange const
orange get element by ID orange instead of selecting the body we're going to select
the ordered list
540:36
that has an ID of fruits document. getet element by ID the ID that I'm selecting is
fruits select the ordered list of fruits insert the new list item before the orange
our coconut is now at number
540:54
two let's insert the coconut before the banana the ID was banana const banana
insert the new list item before the banana our coconut is now at number three you
could insert before Apple too
541:13
I will get the ID of apple const apple insert the new list item before the apple
and it's back at the beginning what if these list items don't have IDs let's
eliminate those we would need to use Query
541:33
selector to select all list items from the ordered list of fruits so I'm going to
use Query selector all select the ID of fruits then select any list item
descendants within this ID
541:53
this will return a node list that stores all of the current list items within this
ordered list we need to select our ordered list of fruits not the body document.
getet element by ID I will
542:09
select our order ordered list of fruits insert the new list item before list items
at index zero now will'll insert the coconut before the Apple let's increment our
542:24
index to one our coconut is now before the orange now it's before the banana and
now it's after the banana if I need to remove this list item I would need to select
it first so let's append the new
542:39
list item to fruit I will get the ID of the ordered list of fruits remove the child
of new list item and it's now gone all right everybody so that is how we can add
change and remove HTML
542:57
elements using JavaScript hey everybody in today's video I got to explain Mouse
events in JavaScript so sit back relax and enjoy the show the first thing I need to
discuss is event listeners an event
543:13
listener listens for specific events to create interactive web pages a few types of
events we'll discuss are click events when we click on something Mouse over is
543:23
when we hover over something and mouse out is when we're hovering over something
and then leave that element to add an event listener you'll use the add event
listener method pass in an event
543:33
type including but not limited to this could be clicking on something hovering over
something or leaving the confines of an element and then a call back to a function
what do you want to do when you
543:44
interact with something for example I could use the click event and then change the
color of something when I click on it going to our HTML file I will create a
development for a box the
543:56
ID of this development will be my box the text on the box will be click me then for
fun I'll add an emoji because I like emojis let's apply some CSS styling because
it's kind of small
544:11
let's select the ID of my box change the background color to light green or some
other color of you're choosing set a width of 300 pixels a height of 300 pixels
I'll increase the font size to
544:31
something large like 4.5 RM I'll set the font weight to be bold I'll use flex box
display Flex align items in the center and text align center that is good enough
for now be
544:53
sure to save everything we're going to select the ID of my box we'll store that as
a constant const my box equals we'll need to select it by accessing the Dom
document. getet element by ID I will
545:10
select select the ID of my box and then we can work with it easily we'll take my
box add an event listener that's a built-in method my box. addevent listener we
need to pass in an event
545:27
type and a call back to a function I want to do something when I click on this box
the event type is going to be click and now we need to call back to a function
we'll Define a function to
545:40
change the background color function change color there's going to be one parameter
an event then we will pass in a call back to change color now the event parameter
event is
545:54
an object it's provided to us automatically by the web browser when something
happens when an event occurs like when I click on something event is an object that
contains information
546:05
about something that happens that event for this demonstration temporarily I'm
going to to [Link] my event so let's click on the box then go to inspect
console and here's my event when
546:21
we clicked on that box the web browser provided us with an event object it's a
pointer event this object contains details about what happened exactly for example
we have the target
546:34
what did we click on WE clicked on the div element with an ID of my box and here
are all the properties and methods of that box that's the target we have a time
stamp of when the click occurred
546:45
the type of the event click which matches up with the event type and coordinates of
where we clicked on the screen event is an object that's going to be provided to us
through the web
546:57
browser automatically we don't need to explicitly pass in an event object with this
call back it's provided to us behind the scenes I'm going to change the background
color of our box when we
547:08
click on it we will access our event op object that's provided to us access the
target the target is what we clicked on there's information about our Target within
the event object then I will take
547:20
the style of the target set the background color property to be a different color I
will set it to be red but I prefer the shade of tomato because I like that color
now when I click on
547:33
the box the background color changes but why stop there let's also change the text
content I'll add one more statement to the change color function again we will
access our event
547:45
access its Target access the text content of the target to be ouch and then I'll
add an emoji that's a good one when I click on this box not only does the color
change but the text too
548:06
now you don't necessarily need to pass in a call back you can also pass in an
anonymous function or even an arrow function so let's copy these two lines of code
we'll reuse it later we no
548:18
longer need to define a function within the event listener instead of passing in a
call back we'll pass in an anonymous function we have one parameter and event
that's going to be provided to us when
548:33
we click on my box do this change the background color and the text now we could
even use an eror function I have a preference for Arrow functions because they're
concise with their syntax with
548:45
an arrow function we have one parameter an event if you have a single parameter you
don't need to enclose it within a set of parentheses we have one parameter of
548:55
event then do this do all this code and that should still work when I click on the
box the color changes as well as the text so when you add an event listener you can
pass in a call back or an
549:09
anonymous function or an arrow function it depends on what your preferences are
personally I like Arrow functions we have a few other Mouse events to discuss Mouse
over and
549:22
mouse out Mouse over is when you hover your cursor over something so let's take my
box add a new event listener an element can have more than one event listener add
event
549:36
listener we have an event and a call back as arguments the event is going to be
Mouse over for the call back I'll use an arrow function we have one parameter of
event
549:52
Arrow do this let's copy these two lines of code I'll change the background color
to be yellow like it's a warning and the text content to be don't do it that's a
good face when I hover my
550:10
cursor over this element the background color and the text is going to change the
event that occurred is mouse over it's when you hover your cursor over something
Mouse out is when you leave a
550:21
specified element so when I leave the box I would like to change back the
background color and the text content We'll add an additional event listener my box
add event
550:36
listener the event type is going to be Mouse out then I'll write an arrow function
we're provided with an event Arrow do this let's change the background color and
the text content I will revert the
550:51
background color to be light green and the text to be click me whatever the text
content originally was when I hover my cursor over this element we get that Mouse
over event but
551:05
when I leave we get the mouse out event when I click on the this box we get the
click event when I leave the Box we get the mouse out event again to reset it
essentially for the last part
551:18
of this demonstration we're going to create a button when we click or interact with
the button then we'll change a separate element this box so within our HTML file
let's create a
551:30
button with text of Click me I will give this button a unique ID of my button and
I'll increase the font size with CSS we will select my button I will increase the
font size to be 3
551:50
RM just so it's not so small let's select the ID of my button const my button
equals document. getet element by ID my button I'll add the event listener to my
button not my box
552:11
if I was to interact with this button with the way it is now when I hover over the
button we've created a mouseover event and the button changes when I click on the
button we're changing the
552:22
HTML and CSS of the button because the button is what has the event listener we're
selecting the target of the event to change which is the button that is what we
interacted with when we interact
552:32
with our box it doesn't do anything it doesn't have any event listeners the button
does though we're going to replace the event Target with my box when we interact
with the button change
552:43
the background color and the text content of my box so then when I hover over the
button the Box changes when I leave it reverts back to normal when I click on the
552:57
button then we've created a click event all right everybody so that is an
introduction to Mouse related events you'll need to add an event listener an event
listener listens for specific
553:07
events to create interactive web pages a few events we've covered include click
Mouse over and mouse out to add an event listener take an element use the built-in
add event listener method pass
553:19
in an event type and a call back Anonymous function or an arrow function to do
something and well everybody those are Mouse related events in JavaScript hey
what's going on everybody
553:34
in today's video I'm going to give you an introduction to key events in JavaScript
so sit back relax and enjoy the show so what we've discussed in the previous topic
is event listeners an
553:45
event listener can be added to an HTML element they will listen for specific events
to create interactive web pages we'll be discussing key down and key up there is a
third type of key event
553:57
called key press however according to the official documentation this event isn't
compatible with all web browsers so you should avoid using key press a key down
event occurs when you press
554:08
down on a key a key event occurs when you release a key by adding an event listener
to the Dom document we can detect when we press down or release a key here's how we
will access our Dom
554:21
then add an event listener add event listener we have two arguments the event type
and a call back when we press down on a key let's do something doesn't matter what
key it is any key for this
554:37
next argument I can either pass in a call back an anonymous function or an arrow
function I like Arrow functions so I'm going to use an arrow function we're
provided with an event parameter when
554:47
something happens within our web browser an event object is created we can access
it so I'm going to [Link] this event object and we'll see the details of it be
sure to select
554:59
your web browser I'm going to press the q key then let's go to inspect console and
here's that event the web browser provided us with a keyboard event the key pressed
was Q there's a
555:17
relevant key code of 81 and there's other properties too like was the ALT key being
held down at the time it wasn't same thing with the shift key and the target which
is the body of our
555:30
document I'm going to Output the key property of the event we'll press a different
key I'm going to hold down the F key I'm not releasing it I'm holding it down we're
going to consistently fire
555:46
key down events I would like to detect when I release a key I will use the key up
event so let's copy this paste it the event is going to be key up I'll display
something else I'm going to use a
556:00
template string I will display key down equals then I will display this events key
let's do this with key key up too I'll just copy this key up equals event. key
let's go back to our
556:19
console I'm going to hold down the S key then when I release it we'll have a key up
event key up equals s oh one more important thing the arrow keys we have Arrow up
arrow down arrow
556:37
left and arrow right if you ever would like to make some sort of game the arrow
keys are also accessible now what we'll do on key down and key up is change an HTML
element so to make this simple
556:50
within our HTML document I'm going to create a div element this div element will
have an ID of my box I'll add some text an emoji all right let's add a little bit
of CSS we will select my
557:08
box I will set the background color to be light blue we haven't picked light blue
yet I will set a width of 200 pixels a height of 200 pixels a font size of 7.5 RM
I'll use flex box display
557:33
Flex justify content Center aine item Center this part is important for the next
exercise we are going to set the position to relative for relative positioning I'll
557:54
set the body of my document to have no margin margin zero all right we are ready we
are going to select the ID of my box const my box equals document . getet element
by ID the ID that I'm going to
558:14
select is my box when I press a key down I'm going to change the text content of my
box mybox do textcontent equals I'll pick a different Emoji let's do that one and
I'll change the CSS mybox
558:38
dostyle do background color equals tomato or some other color of you're choosing so
when I press down on any key the HTML and CSS is going to change I'm going to
release that key but we don't
558:54
revert back to normal our HTML element stays that way what we'll do is that when we
release a key we'll revert these changes by going back to the original so let's
take my box change the text
559:07
content to equal an emoji because I like emojis we'll use the original one then I
will set the background color to be light blue now if I were to hold down a button
the HTML and CSS is going to change
559:24
until I release that button which I am about to now in 3 2 1 go I'm going to try
and press the space bar as fast as I can seizure warning let's go okay it's about
time we move on what
559:40
we're going to do now is using the arrow keys move this element we're going to
create a const of move amount when pressing an arrow key how far do we want to move
this element let's say 10 for 10
559:55
pixels I will create a variable for X think of these as coordinates I will set that
to be zero and y y will also be zero X for any horizontal movement and Y for any
vertical movement document.
560:12
addevent listener when we have a key down event I would like to do something I'll
write an arrow function we're provided with an event do all this code I only want
to do
560:26
something if a user uses an arrow key so if I was to [Link] my event then
access the key property let's go to inspect console select your document I would
like to do something
560:41
only if the key pressed is Arrow up arrow down arrow left or Arrow right I don't
want any of the other keys I can write the if statement if access our event access
its
560:56
key follow this with the starts with method does this key start with arrow will
only enter the SI statement if the key of the event is Arrow up Arrow down arrow
left or Arrow right then we'll
561:12
write a switch we haven't written any switches for a while we will examine the key
of our event with switches we examine a value against matching cases if we have a
case of Arrow
561:28
up if the key of our event matches the case of Arrow up then do this we'll take our
y-coordinate subtract our movement amount which is 10 Yus equals the movement
amount and
561:44
then be sure to break to break out of the switch then we need a case for arrow down
arrow down y+ equals our movement amount Arrow left Arrow left X for the horizontal
axis minus equals the movement
562:11
amount and then Arrow right arrow right X plus equals the movement amount then
outside of the switch but within our if statement we're going to access my box
access the
562:30
style access the top property set it equal to a template string we're going to take
our variable of Y for the y-coordinate then add pixels take the top property of my
box
562:46
set it equal to the y coordinate we're going to copy this and do this with the left
property set it equal to X in pixels be sure to select the body of your document
562:58
we can move right with the right arrow key down left and up or diagonal if I hit
two keys at once the arrow keys have a default Behavior to scroll you can see that
if
563:16
we go down too far we have a scroll bar on the right hand side we can prevent the
default behavior of a key we just have to add this line of code take our event then
follow it with the prevent default
563:32
method so when my element Scrolls off screen it'll disappear we're not going to
scroll with it to increase the distance in which this element moves we can increase
the move
563:45
amount let's set it to be 100 now we're moving a lot further with each key press
hey this is bro from the future there's one more thing I would like to add to this
project when pressing down
563:58
on a key let's change the text content and the background color much like what we
did with the first exercise then when we release a key we'll revert the HTML and
the CSS back to normal we're
564:09
combining the first exercise and the second one and this is the result when I move
the arrow keys this guy's going to freak out until I Let Go pretty exciting all
right everybody
564:25
so that is an introduction to key events in JavaScript you're going to add an event
listener to the document when you select your document and press a key when the key
is pressed down that will
564:35
create a key down event when you release a key that creates key up event and well
everybody that is an introduction to key events in JavaScript hey everybody in
today's
564:50
video I'm going to show you how we can show and hide an HTML element using
JavaScript in this video you'll need an image to work with once you find your image
add it to your website folder then
565:01
we are ready to begin we're going to create a button and an image element let's
start with the button the text on the button will be initially hide to hide an
element I will give this button a unique
565:15
ID of my button I'll add a break then we'll create an image element this is a self-
closing tag with this image I will set the source equal to either the relative file
path or the file
565:33
name so my file is [Link] it's a little too big I'll set the width attribute to be
like 400 pixels that's a decent size I will give this image a unique ID of my image
my IMG and just so
565:53
we can see this button I'm going to apply a little bit of CSS to the button let's
select the ID of my button take the font size I will set it to be 2 RM that's
decent enough all right let's
566:08
go to our J Javascript file I'm going to create a reference to my button and my
image let's start with the button const my button equals document. getet element by
ID the ID that I'm selecting is my
566:27
button let's create a reference to my image as well my IMG the ID was my IMG when I
click on this button I would like to do something we will take my button and add an
event listener add event
566:47
listener there are two arguments an event type and a call back to a function the
event type is going to be click when we click on the button we're going to do
something for the call back
567:00
we'll write an arrow function we are provided with an event parameter by the web
browser Arrow do this when when we click on the button what code do we want to
perform we're going to take my image
567:14
access its style access its display property set it to be a string of none so when
you click on the button it's going to hide the image the display property is set to
none not only that
567:28
let's change the text on the button after we hide the element let's take my button
change the text content equal to be show because now I want to show the element so
hide become
567:45
show when we click on the button a second time nothing happens we would like to
toggle between hiding and displaying this element we'll write an if statement let's
check to see
567:57
if the display of my image is strictly equal to none is the display of my image
currently none if so we're going to set the display to Black block because it's a
block level element take my image
568:13
access its style access its display property set it to be block then within an lse
statement place these two lines of code and we will change the text content of my
button to be
568:35
hide now when clicking the button we can toggle between hiding and showing this
element the image now let me demonstrate something if we were to take my button
then add it after the
568:49
image here's what would happen let me add a break too so by setting the display To
None we don't Reserve any space for that image my button moves up near the top of
the
569:04
window until I show it again another option if we would like to reserve some space
for the image is to toggle the visibility not the display property replace display
with
569:20
visibility we're going to check if the visibility is hidden set the visibility
equal to be hidden if we would like to show the image the visibility is going to be
set to
569:36
visible when we toggle the VIS ility of this image we at least reserve the space
for it the elements that come after aren't going to shift near the top of the
window you can use visibility or
569:48
display depending on the project you're creating all right everybody so that is how
to show and hide HTML elements using JavaScript so uh yeah I should probably talk
about nod lists today a no list in
570:04
JavaScript is a static collection of HTML elements they can be created by using
query selector all we can select Elements by an ID a class or an element type nod
lists are similar to an array
570:17
but they don't have a built-in map filter or reduce method they do have a for each
method at least though an important thing to note with node lists is that they
won't update automatically
570:26
to reflect changes to the Dom for example if you were to remove an element from the
Dom and it's within a node list you would also have to separately remove that
element from the node list so what
570:36
we'll do in this example is create four buttons they'll all have the same class
we'll have button one with a class of I don't know what's a good name my buttons
the class all
570:50
right let's copy this button paste it three additional times we'll have button two
button three button four and I'm going to add a little bit of CSS to these buttons
let's select the class of
571:03
my buttons I'll increase the font size so you can see it font size for RM add a
little bit of margin 10 pixels remove the border border none smooth the corners
with border radius 5
571:22
pixels add some padding 10 pixels by 15 pixels I'll change the background color to
something blue background color blue but I'll select hsl values I'll turn the
lightness to like
571:41
60 okay that's decent and the font color will be white okay that's good enough for
now one way in which we can create a node list is by using query selector all we've
talked about this in a previous
571:55
video but I'll show you a few more advanced things we can do with node lists we can
select Elements by an ID a class or an element type we will create a node list of
let buttons equals
572:09
document. query selector all let's select all elements by a class we need to use
dot then the class name my buttons we could select Elements by an element type if I
would like to select
572:24
all buttons I would just type in button the element type but I would like to select
only elements by this class now that we have our node list I am going to
[Link] my node list of buttons and
572:37
we'll take a look at it here's my node list it contains four elements button one
button two button three button four we do have a length property a few methods
entries for each
572:54
item Keys these are all different methods for each is what we're going to be using
a lot here's how we can change the HTML and CSS properties of all elements within a
node list we can use
573:07
the for each method of a node list and iterate through all of the elements so we
will take our node list of buttons use the built-in for each method then write an
arrow function we are provided
573:19
with an element Arrow do something but I'm going to rename element as button just
so it's more easily understandable during each iteration we're provided with a
current button what would we like
573:31
to do to that button well let's change the background color button. style do
background color I'll set it to be green that should update the color of all the
buttons not just one of them
573:47
we're iterating through all of the buttons within this no list change all of their
background colors to be green let's change the text content too take each button
access the text content I
574:00
will set it equal to be I don't know an emoji or something let's do that the text
content and all the buttons is is going to change maybe let's append an emoji not
replace the text
574:13
content that's better that is how you can add and change HTML and CSS properties
with a node list use the for each method then write an arrow function to do
something in a similar way we're
574:25
going to add an event listener to each button that will listen for a click so again
we're going to take our node list of buttons use the buil-in for each method for
each button Arrow do
574:39
this we need to add an event listener to each button we will take the parameter of
button add an event listener within our event listener we have an event type and a
call back to do
574:55
something the event type is going to be click instead of a call back we'll write an
arrow function we are provided with an event Arrow do this event is proved provided
to us through the web browser
575:10
when something happens we will access the event objects Target meaning the button
that we click on that's going to be our Target access the style access the
background color
575:24
property let's set it to be red or better yet tomato because I like tomatoes each
button has an event listener it will listen for click events when we click on a
button the background
575:37
color is going to change we're going to add an event listener for Mouse over and
mouse out let's begin with mouse over again take our node list of buttons use the
for each
575:50
method for each button Arrow do this take that button add an event listener with
event listeners we have an event type and a call back the event type Tye is going
to be Mouse
576:10
over when we hover our cursor over something what would we like to do we will write
an arrow function event Arrow do this let's access the events Target that should
equal our button that we
576:25
click on access the style access the background color so with the current color I'm
going to go back to my CSS I will copy this color paste it but make the lightness
10% darker now when we hover
576:41
over one of the buttons the background color is going to change I'll set the
lightness to like 40% to make it much more apparent there that's better now when I
leave one of
576:52
these buttons I need to revert that color back to the original really we can just
copy all this code replace Mouse over with mouse out and set the background color
back to the original
577:11
each button now has a mouse over and mouse out event listener here's how you can
add an element to a node list I will create a new button const new button equals
document. create element what element
577:30
are we creating a button so with creating an appending HTML elements there's three
steps this is step one we need to create that element first step two is to add any
necessary
577:46
attributes or css properties so let's take our new button change the text content
of the button equal to be button 5 I would like to give my new button a class of my
buttons we're going to
578:04
access the class list property new button. class list when working with an
element's class we work with class list not class so the class list equals the
class of my
578:22
buttons then we have step three now we have to append this element to the Dom what
is the parent element of this new button going to be well in this case it's going
to be the body of my
578:34
document we're going to be adding a new button right here the parent the enclosing
element is the body in this case access our document select the body append Child
new
578:48
button and there's button five since we added our class of my buttons that's why it
has all these CSS properties if I were to remove this line of code we get the
default appearance for a
579:01
button I'll talk more about class lists in the next video there's a lot you can do
with them now if I was to [Link] my node list of buttons here's what we have
we have five buttons
579:13
within our Dom but within our node list we have four buttons button one 2 3 four
button five isn't within this no list no lists are a static collection they won't
update automatically to
579:32
reflect changes to the Dom even though button five is within the Dom we would need
to manually add it to our no list if we want to work with it so to do that we can
just use Query selector again and
579:44
select all elements by the class so let's reassign buttons since we're reassigning
buttons that's why I declared buttons with let instead of const so we're able to
reassign it
579:55
because if this was a constant we couldn't change the elements within it so buttons
equals document. query selector all select All Elements by a class class my buttons
and then again let's
580:15
[Link] my node list of buttons inspect console and there we go our node list
has five elements button 1 2 3 4 5 even if you were to add an element to the Dom
that same element isn't going to
580:34
be automatically added to your node list I would recommend using query selector all
again just to update it here's how to remove an element from a node list when you
click on it we'll have to give
580:44
all of these buttons an event listener they will listen for a click event when we
click on one of these elements remove it from the Dom and the node list here's how
again we will take our node list of
580:56
buttons use the built-in for each method for each button within our node list do
this take each button add an event listener we are provided with an event type and
a call back to a
581:12
function the event type that we're listening for is click the call back is going to
be an arrow function we're provided with an event Arrow do this to remove an
element
581:25
from the Dom when you click on it we will access our event object access the target
use the built-in remove method to remove it so let's see if this works currently
let's remove button 2 1 4 3 so
581:41
those buttons are gone but let me show you something I'm going to [Link] my
node list of buttons after each click even if I were to remove these buttons from
the
581:59
Dom they're still within the node list even after all the buttons are gone our node
list still has four buttons so we do have to update that manually here's an easy
way how to do
582:11
that we're going to use Query selector all again we'll reassign buttons equals
document. query selector all select all elements from the Dom that have a class of
my
582:28
buttons then just to see if this works let's [Link] my node list of buttons
now when we click on a button it should be removed from the Dom and the node list
when I remove all the buttons our
582:48
no list is then empty all right everybody so that is an introduction to node lists
they're a static collection of HTML elements they can be created by using query
selector
582:59
all we can select Elements by an ID a class or an element type they're similar to
an array but there's no map filter or reduce method and do remember that nod list
won't
583:09
update automatically to reflect changes to the Dom and well everybody that is an
introduction to node lists in JavaScript hey everybody so in today's video I got to
explain class lists in
583:25
JavaScript class list is an element property it's used to interact with an elements
list of classes meaning CSS classes by accessing the class list property of an
element we can make
583:36
reusable classes for many elements across your web page if I have a CSS class I can
dynamically add remove toggle replace or check to see if an element contains a
certain class so what
583:50
we'll do in this example in our HTML document is create a button the button will
have text of my button the ID of this button will be my button we'll apply a little
bit of CSS
584:04
initially let's select the ID of my button we'll be applying just a few properties
let's increase the font size to for RM oh not 43 four go back go back go back I'll
add a little bit of margin of
584:21
10 pixels remove the border with border none border radius to smooth the corners 5
pixels and add a little bit of padding 10 pixels by 15 pixels that's good enough
for now we're going
584:39
to create a CSS class of enabled we won't apply it right away though we'll apply
this class to this button using JavaScript if an element is enabled let's change
the background color to be something
584:55
blue I'm going to use hsl values though and I will set the font color to be white
so this button doesn't doesn't have this class yet we'll add that in dynamically
using JavaScript we'll
585:12
create a reference to this button const my button will be the name then we need to
select it document. getet element by ID the ID that I'm selecting is my button to
add a class to an element take
585:29
that element my button access the class list property follow this with the add
method we will add the name name of the class enabled and now my button is enabled
we have appended the CSS properties
585:45
dynamically so if I were to inspect this element I'll rightclick inspect we have
added that class of enabled to the element so my button has an ID and a class of
enabled to remove a
586:00
class again take that element of my button access the class list we will use the
remove method method we will remove the class of enabled and it's gone let's right
click on the element
586:15
inspect so our class list is empty we have added and then removed that class of
enabled we're going to create a new class now of hover when we hover over an
element apply these CSS properties it's
586:29
kind of like we're using the hover sudo class but we're using it a little bit
different we can add or remove this class dynamically at will if we apply this
class let's set a box Shadow to
586:41
give the element a 3D pop effect for a horizontal and vertical offset let's set
those to be zero each let's add 10 pixels for the blur effect and I will set the
color to be I don't know let's
586:53
set it to be black but set the alpha down to like 20% and then when I hover I would
also like to set the font weight of that element to be bold let's add the hover
587:10
class so the appearance of this button changed I would like to apply this class of
hover only when I hover my cursor over the element We'll add a mouse over event
listener we will take my
587:23
button add event listener we have an event type and a call back to a function the
event type will be Mouse over when we Mouse over this element we are provided with
an element object
587:40
event Arrow do this we will access our event objects Target meaning the button take
our class list and add the class of hover and let's see if this works if I hover my
cursor over the button we apply
587:59
the hover class now when I leave the button I would like to remove it really we can
just copy the code for the event listener paste it replace Mouse over with mouse
out then we will remove that
588:12
class so now we can apply that class and then remove it with mouse over and mouse
out there's also toggle if we toggle a class we'll remove it if that class is
present add that class if it's not so
588:28
let's replace add with toggle do this for both Mouse over and mouse out and that
should work the same when we hover our cursor over the button we will toggle the
class of hover if we
588:40
have a mouse out event we will toggle it again to remove it now we're going to use
the replace method to replace one class with another we'll create a new class of
588:55
disabled we'll be replacing the enabled class with the disabled class when we click
on the button so with the background color of the disabled class let's set the
background color to be Gray
589:07
again I like using hsl for the colors I'll set the lightness to be like 60% I'm
trying to get a faded appearance and for the color let's pick a light shade of gray
using hsl
589:24
values I'll set the lightness to be 80% going back to our Javascript file let's add
the class of enabled my button access the class list use the add method we will add
the class of
589:41
enabled then we'll add an event listener to the button we will take my button add
an event listener we have an event and a call back the event is going to be click I
589:55
would like to do something when we click on the button we will receive an event
Arrow do this take our events Target access the class list we will will use the
replace method replace the
590:09
old class with the new class replace the enabled class with the disabled class
there's two arguments the old class and the new class replace the old class with
the new
590:21
class then when we click on this button we'll replace the enabled class with the
disabled class then we have the contains method if an element contains a class this
will return true and if it doesn't
590:35
it returns false So within our event listener let's add an if statement and an else
statement we'll check to see if our events Target access the class list we will use
the contains
590:54
method if we click on the button and the class contains disabled what do we want to
do does the class list contain disabled let's change the text content take our
vents Target access the text content
591:11
I'll append an emoji what's a good one that one else replace enabled with disabled
let's click on the button we'll replace the enabled class with the disabled class
our button is now
591:30
disabled if I were to inspect this element the class is now disabled if I were to
click on this button again well our class contains disabled that was true so we end
up
591:43
doing this code where we append to the text content of the button now the nice
thing about using class lists HTML elements have a class list property we can reuse
CSS classes amongst many HTML
591:55
elements we'll create an H1 element now the text of this element will be hello I
will give this element a unique ID of my H1 I'll increase the font size so we can
see
592:12
it select the ID of my H1 I'll increase the font size let's try five RM let's
create a reference to my H1 const myh1 equals document. getet element by ID the ID
that I'm selecting is my H1
592:36
we'll add the enabled class to myh1 myh1 do classlist do add not ass add enabled
and there we go we have added these CSS properties to this element and because I'm
lazy I'm going
592:57
to copy all this code where we add an event listener to my H1 so let's replace my
button with my H1 now when we click on this H1 element we can disable it we'll
replace the enabled
593:12
class with the disabled class and if you don't believe me let's take a look the
class of my H1 is now disabled if I were to click on this element again while the
class list
593:24
contains disabled so we execute this if statement where we change the text content
of that Target now here's a challenge round we're going to create four buttons and
593:35
store all of those buttons with then a node list so let's create a button with the
text of the first button being button one I will give this button a class of my
593:47
buttons let's copy this button paste it three times button one button two button
three button four let's remove the CSS from my H1 select the class of my buttons
keep these three classes of
594:06
enable hover and disabled okay let's eliminate all this code we'll create a node
list to contain all these buttons we can use const if we don't plan on adding or
removing buttons
594:20
or let if we do let buttons equals document. query selector all select all elements
that have a class of my buttons we'll apply our enabled class to all the buttons so
we will take our node list of
594:40
buttons use the for each method for each button within our node list do this take
each button access each button's class list property I will add a class of enabled
and we have applied that class
595:00
to all the buttons If you need to remove a class you can do the same but replace
add with remove move now when we hover a cursor over one of these buttons we will
toggle the
595:14
hover class we need to iterate through our node list of buttons take buttons use
the built-in for each method for each button within our node list do this take each
button add an event
595:32
listener the event listener has an event type and a call back to a function the
event type will be Mouse over when we hover a cursor over it we will be provided
with an event
595:45
argument Arrow do this access the event object access the target meaning the button
that we hover over access the class list property we will toggle the hover class so
when we hover
596:02
our cursor over one of these elements we will apply the hover class now when our
cursor leaves one of these elements we would like to toggle that class again let's
copy everything we
596:15
have here paste it replace Mouse over with mouse out when we leave one of these
elements toggle the hover class again to remove that class now when we click on one
of the
596:30
buttons we're going to replace the enabled class with the disabled class take our
node list of buttons use the for each method with each button Arrow do this take
each button add an event
596:51
listener we need to select the event type and a call back to a function the event
type is going to be click the parameter is event Arrow do this when we click on one
of these buttons
597:06
we'll replace the enabled class with the disabled class take our event object
access its Target access the class list property we will replace replace the old
class with the
597:20
new class replace the enabled class with the disabled class and let's see if this
works when I click on a button we'll replace the enabled class with the disabled
class
597:38
the last thing we'll do is that when we click on a button that's disabled we'll
change the text content we'll have to use the contains method So within our event
listener I'll add an if
597:49
statement if access our event access its Target access the class list property use
the contains method does the class list contain the class of disabled if it does
we'll
598:04
access our event access the target of that event change the text content of that
element I'll append an emoji that one I like that emoji if the class list of that
element isn't
598:19
disabled it doesn't contain the class of disabled we'll execute an L statement
where we disable it by replacing the enabled class with the disabled class we have
three event listeners Mouse over
598:32
Mouse out and click we're utilizing all three of these custom classes enabled hover
and disabled we can hover over these elements then we'll have Mouse over and mouse
out events then when I click on
598:45
one of these buttons we can apply that disabled class within our click event
listener we have an if statement if we click on an element that's already disabled
append the text
598:59
content all right everybody so that is the class list property it's used to
interact with an elements list of classes their CSS classes they allow you to make
reusable classes for many elements
599:11
across your web page and well everybody that is the class list property in
JavaScript hey what's going on everybody in today's video we're going to create a
game of rock paper scissors using
599:25
JavaScript so sit back relax and enjoy the show all right let's do this thing we're
going to create an H1 heading with text of rock paper scissors for a title we'll
create three buttons the
599:41
first one will be for rock you can add some text of rock but you know what I like
using emojis I'm going to use an emoji instead I would like an emoji of a fist and
I'm going to zoom in until we
599:55
add some CSS let's create a button for paper that'll work and scissors maybe a p
sign with each of these buttons I will set the onclick event handler equal to a
JavaScript function we'll name the
600:17
function play game now with these functions we're going to pass in an argument the
first will be a string of rock now if you use double quotes HTML is going to be
confused where this event
600:29
handler ends our argument is going to be a string but it's going to be within
single quotes because we're already using double quotes let's copy this attribute
cuz I don't
600:38
feel like typing it again the second argument will be for a string of paper and
then scissors let's enclose our buttons within a div element this div element will
have an ID of
600:57
choices let's cut our buttons and paste them within the div element outside of the
div element we'll create create another div element we will display the Player's
Choice player colon
601:13
space the ID of this development will be player display this will display the word
rock paper or scissors depending on which button we pick let's do this for computer
text will be computer ID computer
601:32
display we should display a result who won the ID will be result display just for
some temporary text I'm going to add it's a tie when we style this with CSS I would
like to be able to
601:51
see the updates we'll get rid of this pretty soon eventually we'll add in a score
tracker but we'll do that after our game is at least working okay let's head to our
CSS
602:01
stylesheet I'm going to zoom back to 100% let's select the body of our document I
will set the font family to be aial with the backup of s serif let's set the font
weight to be bold throughout this
602:22
application I will set any margin to be zero around the body use flex box to
display the elements display Flex the flex direction will be a column and align
items Center let's select our H1 element I
602:46
need to increase the font size font size 3.5 RM for a color pick a color for me
I'll set the lightness to 20% now we're going to select our development of choices
actually let's
603:10
make this a class class choices select the class of choices add margin bottom of 30
pixels within this development we need to select all the buttons we will select the
class of
603:33
choices select all buttons within this class we increase the font size to 7.5 RM
these buttons need to be big I will set a minimum width of 160 pixels at a little
bit of margin between each
603:54
button zero pixels on the top and bottom 10 pixels on the sides for the buttons I
would like rounded Corners I would like these buttons to be a circle I can set the
Border radius to
604:07
something massive like 250 pixels that will give us some rounded buttons and pick a
background color background color I want something blue I've already pre-picked a
color so I'm going to use
604:27
this now when I hover my cursor over one of the buttons I would like my cursor to
change into a pointer and that does work let's also add a transition effect let's
change the background color
604:43
to e after half a second let's access the hover sudo class of all the buttons of
choices take the background color I'll set the lightness to be 20% lighter each
button is going to light up
605:02
when you hover your cursor over the button then we'll work on the display displays
next we're going to select the player display and the computer display these are
ideas player display and computer
605:19
display let's set the font size to be a 2.5 RM and for the result display where it
says it's a tie that's the ID of result display set the font size to be 5 R and
I'll add some margin to the top
605:42
and bottom 30 pixels to the top and bottom zero on the sides okay that is good
enough for now so we no longer need this placeholder for the result display let's
add some
605:55
functionality we have a lot of constants to declare const choices choices will be
an array of strings we'll have Rock paper and scissors we need to get the player
606:10
display and the computer display so we can update them const player display equals
document. getet element by ID the ID that I'm selecting is player display then we
have computer
606:32
display computer display and a result display this one it's empty currently const
result display equals document. getet element by ID result display we'll factor in
scoring later we
606:54
need a function of play game that accepts one argument the Player's Choice function
play game we have one parameter player choice when we play a new game we have to
pick a choice for the computer
607:14
between rock paper or scissors what we could do is generate a random number between
zero and two rock is index zero paper is index one scissors is index 2 we'll create
a constant within play game
607:26
of computer Choice I'm declaring it within the function so we can update it every
time we play a new game equals take our array of choices at index for the index
we'll
607:41
generate that random number using the random method of math math. random method * 3
then we need to round it because it's not going to be a whole number math. floor to
round it
607:57
down so the computer's choice will be a random index between 0 through two which
will give us randomly either rock paper or scissors hey this is bro from the future
one thing that would be good for
608:09
us to do is along the way use [Link] just to be sure that what we've been
writing has been working so within our computer's Choice let's [Link] whatever
that
608:21
is so if this does work after clicking one of these buttons the computer is either
going to pick rock paper or scissors the computer picked scissors just now scissors
scissors it really
608:33
like scissors apparently so yeah the Player's Choice is being populated with the
string of rock paper or scissors I just wanted to confirm that and we need a result
what are we going to display to the
608:46
screen result will be an empty string for now first let's check to see if the
Player's Choice is equal to the computer's choice that means it's a tie if Player's
Choice is strictly equal to the
609:01
computer's Choice maybe we both pick rock well well then we'll take our result to
be displayed and set it equal to be it's a tie else somebody is going to win let's
add an else statement we can use a
609:20
switch we can examine a value against matching cases we'll examine the Player's
Choice does the Player's Choice match the case of rock do these two Val use match
if so we'll use the tary
609:41
operator we'll check the condition of if our computer's choice is strictly equal to
scissors if so question mark That's the tary operator if we pick Rock and the
609:58
computer picks scissors we will return U win otherwise if this condition is false
well that means the computer picked paper if our choices already don't match and we
picked rock that means they
610:11
either picked scissors or paper if they didn't pick scissors that means they picked
paper so they win that means we lose you lose whatever string is returned we're
going to assign it to result result
610:27
equals whatever is returned either you win or you lose then we should add a break
after this case all right let's copy this case and everything within it let's paste
it if the Player's Choice
610:44
matches the case of paper and the computer's choice is strictly equal to rock that
means if that's true you win else you lose let's copy this case and everything
within it case scissors
611:06
if the computer's Choice equals paper then you win otherwise you lose after we move
beyond the IFL statements we need to update the text on the screen so we will take
the players
611:23
display set the text content to equal a template string of player col in space add
a placeholder the Player's Choice did we pick rock paper or scissors then let's do
this with the computer's
611:42
Choice select the text content of the computer display the text will be computer we
will display the variable of computer Choice the one that was picked randomly and
take our result
612:00
display which has no text content currently set it equal to be result okay let's
see what we have currently let's pick Rock it's a tie paper you win scissors you
lose what
612:19
we'll work on next depending on the result that's displayed if we win I would like
the text to be green if we lose I want the text to be red going to our CSS
stylesheet we're going to add three
612:32
classes green text red text pick a font color pick something green and for the red
text pick a red font color if we win or lose we're going to add one of these
classes to the class
613:01
list of our result display so going back to to our Javascript file after we display
the result now we're going to add a switch we're going to examine our result we
will add a case of you
613:19
win if our value matches this case let's take our result display access the class
list use the add method add the class of green text then break let's copy this case
paste
613:41
it we will add a case for you lose add the class of red text if we lose let's see
what we have currently if we win you get green text if you lose you get red text
but now if
614:00
it's a tie we have red text with each new game we should reset the color back to
the original so before updating the color and displaying it let's take our result
display access the class list use the
614:16
remove method remove any class of green text and red text let's see if this works
you lose it's a tie that's black you lose you win the colors seem to be working all
right
614:34
now let's add scoring mechanism we'll have to head back to our HTML file after our
result display we're going to create a div element the first div El will have a
class of score
614:50
display the text for the score display will be player score colon space then we'll
add a span element within with text of zero row I will give the span element a
unique ID of player score
615:11
display the reason I'm putting this number within a span element I'm going to style
this number different from the rest of the div element the player score okay let's
copy this div element
615:22
and paste it we need another for computer computer score the ID of the span element
will be computer score display going back to our c a stylesheet we'll add the
following after our result
615:38
display we will select the class of score display increase the font size font size
will be 2 R for the actual numbers I'm going to change the color with the CSS
property
615:54
where the font color is green I'll add an additional selector let's select the ID
of player score display I would also like that to be that shade of green and for
the red text let's select the ID of
616:11
computer score display so the computer score that number will be red okay now we
just need to add functionality to the scoring mechanism so back to the top we're
going to select the ID of player score
616:29
display const player score display equals doc min. getet element by ID player score
display and we need the same thing for the computer computer score display and we
need a score value a
616:55
number so we can work with it let player score equals zero let computer score
equals z going to the bottom of this function within our switch within our case of
you
617:11
win we're going to increment our player score player score Plus+ then take our
player score display and update it access the text content set it equal to whatever
the player score
617:31
is then let's do this with our computer computer score Plus+ that's if we lose and
computer score display equals the computer score and that should be everything
let's see if this program
617:51
works you lose you win you win it's a tie you win you win you lose the player score
is four the computer score is two all right everybody so that is a game of rock
paper scissors you can make using
618:13
JavaScript hey what's going on everybody so in today's video I'm going to show you
how we can create an image slider program using JavaScript you will need some
images to work with I would
618:22
recommend finding three or more somewhat related images to whatever you would like
to create an image slider for once you find your images put them within your
website folder and we are ready to
618:32
begin okay let's do this thing everybody so we will create a development to contain
everything this development will have a class of slider within this development we
will create another
618:45
development this development will have a class of slides to contain our images
within this inner div element we will create three image elements the first image
will have a class of
618:59
slide with this image element I will set the source attribute to be a relative or
absolute file path let's begin with image one whatever you currently have I'll copy
the name of this image
619:10
including the extension so my image has a name of image [Link] and for some reason
if this image can't display I'll add some alternative text with the alt attribute
let's say image number
619:26
one and there is my image I will copy this image element paste it twice or once for
every image that you have then I have image two and image three let me change those
we have image two and image
619:42
three so you should have three or more images depending on what pictures you're
using and how many then we're going to add some Arrow buttons for the time being
that will be down at the
619:53
bottom so we will create a button element now you could use a left angle bracket
let me zoom in but I think there's a better option there's a unic code character
for a left
620:05
pointing angle bracket which looks like this we will use the Unicode character of
Ampersand # 100094 I think that looks better but you do you all right then let's
create a
620:19
right angle bracket with another button the number is 1 95 so that will create a
button with an arrow that points to the right for the previous button the left one
I will assign a class
620:34
of prev meaning previous and the next button will have a class of next when we
click on these buttons we'll call a JavaScript function we need to set the onclick
vent Handler equal to
620:48
a JavaScript function for the previous button we'll call a function of prev slide
meaning previous and for the next button we will call a function of next slide to
go to the next slide
621:05
okay and that is all the HTML that we need for now let's go to our CSS stylesheet
we will select our class of slider that contains everything class slider we're
going to use relative
621:20
positioning these elements will move relative to their normal position using
relative so we have position relative I will set a width of 100% as well as margin
Auto to to Center everything
621:35
horizontally now just in case if our images are really big I will set the Overflow
property to be hidden so take our class of slider select all the images with these
images I will set
621:48
their width to be 100% and for now I will set the display property to be none we
don't want to display all the images right away so they should disappear let's add
a little bit of
622:00
functionality before continuing let's go to our Javascript file I'm going to create
a node list of all the images within our class of slides so I will create a
constant of slides which
622:13
will be a node list equals document. query selector all we will select all elements
within the class of slides that are images image elements we will also declare an
index of the
622:29
current slide let slide index so this will be zero initially to start at the first
slide we'll be using the set interval function set interval will return an ID that
we can work with so we
622:43
will declare a variable to hold to that let interval ID for now I'll set it to be
null meaning no value okay let's declare our functions we will have a function to
initialize our
623:01
slider this will populate our web browser with the first image when we call this
function then we need a function for show Slide there will be one parameter an
index an index of the next slide we
623:16
would like to go to a function for the previous slide prev slide and a function for
next slide function next slide within our function of initialized slider we will
take our node list of
623:35
slides at index of our current slide index which will be zero initially I will
access the class list and add a class of display slide which we still need to work
with and then we will call
623:53
this function right away okay we need to build this class still display slide we
will select all image elements that have a class within their class list of display
624:08
slide if an image has this class we will set their display property to display as a
block we should get our first image if you would like although it's not necessary
we could display this
624:23
image after all of the Dom content loads by using an event listener here's how if
you would prefer to wait for all the Dom content to load we can take our document
add an event
624:36
listener we will wait for the event of Dom content loaded once all of the Dom
content loads pass in a call back to initialize slider so this would work too and I
would say
624:51
it's the preferred way rather than just calling this function initially wait for
all the Dom content to load then display our first image by calling this function
625:00
within the initialized slider function we will use the set interval function we
will call the next slide function after a given amount of seconds let's say after 5
seconds I would like
625:15
to go to the next slide and display the next image whatever is next within our node
list in order for us to work with this interval this function is going to return an
interval ID so we can clear it
625:26
later if we need to we will take our interval ID set it equal to the set interval
function so I am going to [Link] my interval ID just to see what it is so
let's save and run
625:42
everything go to console so this interval has an ID of one if I need to clear this
set interval function I can access it by its ID which is currently one and we can
get rid of this
625:55
line to avoid displaying an image if we don't have one we can wrap these two lines
of code within an if statement we will check if our node list of slides its length
property is greater
626:10
than zero if we do have slides then display it and use the set interval function if
there's no slides no images then don't do this okay then we're going to go to the
next slide
626:25
function we're going to increment slide index by one slide index Plus+ and then we
will will call the show slide function pass in our slide index after incrementing
it and that is
626:39
all we need for next slide then we have the show slide function within our show
slide function we will access our node list of slides use the for each method to
626:51
iterate through all of them I would like to take each slide Arrow do this take each
slide access its class list then remove a class from the class list we will remove
the class of display
627:09
slide if it's time to move to the next slide we don't want to display the current
slide anymore we'll remove display slide so that it's no longer displaying as a
block remove these
627:21
properties then outside of this for each method we will add display slide to the
next slide then we will take our slides at index of slide index access the class
list of the next
627:36
slide then we will add a new class add the class of display slide so that it
displays as a block and let's see if this works after 5 Seconds we should move to
the next
627:53
slide and that does in fact work let's wait again for the next slide and that has
worked too we need to reset our slide index because right now we're going out of
628:05
bounds we only have three slides in this example within our show slide function
We'll add an if statement and an lse if statement if we reach the end of our slides
we need to reset the slide index
628:22
and set it back to be zero if our index that's passed in is greater than or equal
to our node list of slides length property if we reach the end we need to take our
slide index and reset it to be
628:38
zero now if we go backwards with the previous button if our index is less than zero
we will take the slide index set it equal to our slides length property minus one
to set it to the end
628:56
if we're on the first slide and we hit the previous button that will bring us to
the last slide these images should Loop let's see see if that does work so we're on
our green car and we
629:12
should go to our blue car next and that does work our initialized slider function
is done if we click on the next button we should be able to go to the next slide
right
629:24
away now we have to work on the previous button and add some functionality to that
within the previous slide function we will take our slide index and decrement it
with minus minus then call
629:37
the show slide function pass in the current index now we should be able to move
forward and back now if we hit the previous button CU we want to look at an image
the timer
629:50
is still going we'll still go to the next slide if we would like to take some time
to admire one of these images we can clear the set interval function by using its
interval ID so if somebody
630:01
were to hit the previous button let's clear the timer we will use the clear
interval function we will pass in that interval ID our set interval function is
still
630:13
going to move the slides forward but if I were to hit the previous button that
interval is going to stop we are done with all of our JavaScript functionality
we're going to
630:24
apply some CSS styling to the buttons and even add a transition animation to the
next image we will style our buttons next within our class of slider select all
630:37
buttons I will set the position property to be absolute positions an element
relative to its parent meaning the slider element with absolute positioning I will
set the top property to be
630:56
50% these buttons will then be positioned on the Y AIS at 50% meaning the middle
then I will use the transform property I will translate them on the Y AIS by minus
%. Translate Y is a function we're
631:15
moving these buttons up by 50% of the element's height that will put this button
right in the middle take 50% of the height of the button Move It Up by that amount
I'll increase the font size
631:28
font size 25 pixels or better yet let's do like 2 RM okay now for the background
color I'll set it to be black but I'm going to lower the alpha on it so it's
transparent I'll set the alpha to be
631:47
50% and for the font color color I'll set that to be white okay you can see our two
buttons are overlapping currently I'm going to remove the border around the buttons
order
631:59
none and change our cursor to be a a pointer if we hover over one of the buttons so
these buttons each have a class previous and next let's select the previous class I
will set the left property to be
632:16
zero to left align it and with the next class that's the next button I will set the
right property to be zero to align it to the right I'm also going to add a little
bit
632:29
of padding too around the buttons let's add some padding here padding 10 pixels by
15 pixels that looks pretty good we are going to add an animation at Key frames
632:47
we need an animation name we will name this animation fade for a fade effect from
this property of opacity I can't spell today 0.5 meaning 50% two this property
633:06
opacity one for 100% when a new image is displayed the opacity is going to be 50%
so it's transparent then after the animation is complete set it to be one for 100%
now we just have to utilize
633:20
this animation of fade all images that have the display slide class we will set
their animation name when that image is displayed to be fade how long do we want
this animation to take
633:33
we will set the animation duration to be about 1.5 seconds okay let's see if this
works we should get a fade animation when each new slide appears we can move
forward and we can move
633:52
back all right everybody so that is an image slider that you can create using
JavaScript HTML and CSS hey everybody in today's video I got to introduce to you
the wonderful world
634:06
of callback hell callback hell is a situation in JavaScript where callbacks are
nested within other callbacks to the degree where the code is difficult to read if
you Nest too many callbacks
634:17
within other callbacks your code starts to form a pyramid and it's really difficult
to work with callback hell is an old pattern to handle asynchronous functions in
Java Script nowadays we
634:28
have promises as well as a sync and a wait to avoid callback hell which we'll
discuss pretty soon to help us avoid callback hell we should be familiar with what
it is I'm going to create four
634:38
tasks these will be functions function task one these will be synchronous functions
we don't need to use callbacks for synchronous functions then we'll change these to
be asyrus functions within task
634:52
one we will [Link] task one complete okay let's copy task one paste it three
times for a total of four tasks we'll have task two task three and task four in
order from the top down we will
635:12
execute task one followed by task two task three and task four when all four tasks
are complete we will [Link] all tasks complete these functions work
synchronously they're all in order task
635:34
one is complete then two 3 then four then we get the final message of all tasks
complete but what if these were asynchronous functions they're not going to follow
this order from the top down
635:45
so to make these functions asynchronous one thing we could do we can enclose this
code within the set timeout function set timeout set timeout takes two arguments
635:56
a call back and a time in milliseconds in which to complete this code for the call
back this could be a call back an anonymous function or an arrow function I'll
write an arrow function parameters
636:08
Arrow do this say the task is complete after 2,000 milliseconds let's do this with
the other tasks too so task two will be complete after 1 second 1,000 milliseconds
task three will be complete
636:29
after 3,000 milliseconds now task 4 task 4 will be complete after 1,500
milliseconds okay let's try this again I need these tasks to be completed in order
starting from one all the way to
636:45
four it says that the tasks are already complete then the tasks are completed in
this order task 2 task 4 Task 1 and task three so that's the problem with
asynchronous code asynchronous functions
636:58
can complete at any time the rest of our program doesn't wait around for them to
finish if I absolutely need these tasks to complete an order starting with 1 then 2
3 4 each of these functions can
637:10
accept a call back so we need to set up that parameter after we say that that task
is complete we will execute the call back to the next function so let's do this
with the rest of the tasks
637:37
if we need these tasks to complete an order starting with one we would take one and
there's one parameter a call back we'll pass in a call back to task two we can pass
in a call back and
637:48
Anonymous function or an arrow function I like Arrow functions though parameters
Arrow do this what are we going to do when task one is complete we'll call task two
task two also accepts a call
638:01
back again this can be a call back an anonymous function or an arrow function this
will be an arrow function parameters Arrow do this what do we want to do when task
two is complete call
638:13
task three task three also accepts a call back we'll use an arrow function
parameters Arrow do this now when task three is complete guess what we're going to
do call task
638:25
four task four task 4 accepts a call back we'll do this parameters Arrow then would
like to [Link] all tasks complete all tasks complete this should work now task
one complete task two
638:47
complete task three complete task 4 complete all tasks complete so what we've done
is use callback hell it's where you're nesting callbacks inside of other callbacks
if you have a lot of
638:59
tasks to complete an order it can become very unman manageable hey this is bro from
the future one thing that I wanted to mention is that four levels of callbacks
isn't too unreasonable but
639:10
when you add additional levels on top of that that's when you're starting to
approach the levels of callback hell where the code can become unmanageable and
really difficult to read what I've
639:19
written in this video isn't too unreasonable but hopefully you can see how we've
come to start that pyramid pattern that is all all right everybody so that is
callback hell it's a
639:28
situation in JavaScript where callbacks are nested with other callback where the
code is difficult to read it's an old pattern to handle asynchronous functions in
some upcoming videos we'll be
639:38
discussing promises as well as a sync and a wait to avoid callback hell and well
everybody that is callback hell and why you should avoid it in JavaScript what's
going on everybody so
639:52
in today's video I got to talk about promises in JavaScript A promise is an object
an object that manages asynchronous operations such as querying a database space
fetching a file
640:03
Gathering resources those you could consider asynchronous operations they can take
an indeterminate amount of time you can wrap a promise object around some
asynchronous code the promise
640:14
object promises to return a value that promise object will be pending then either
that promise will be resolved if the task completed successfully or rejected if it
failed for some reason
640:25
maybe the promise couldn't fetch that file resolved if it did A promise is an
object will create a new promise object with new prom then pass into a function
usually you
640:34
see this is an arrow function there's two parameters resolve and reject Arrow then
do some asynchronous code so in this demonstration we're going to be doing some
chores if you live with your
640:45
parents maybe your mom asked you to do these chores or with the roommate these are
the tasks you need to do or your significant other wants you to do these tasks
anyways we have some chores to do
640:55
we have to walk the dog clean the kitchen and take out the trash I'll create
functions for each of these chores first we'll start by using callbacks then I'll
demonstrate the use
641:05
of promises and how they're helpful so let's create a function to walk dog to make
this asynchronous I'm going to add a set timeout function this takes a call back
and an
641:19
amount of time in milliseconds to complete this code let's say walking the dog
takes 1,500 milliseconds what code would we'd like to perform let's write an arrow
function to keep it
641:30
simple parameters Arrow do this let's [Link] after completing this chore you
walk the dog okay that'll be the first function let's create a function to clean
the
641:48
kitchen function clean kitchen this will take a long time 2,500 milliseconds let's
say when we complete this task we will print you clean the kitchen and a third
function take out
642:12
trash you take out the trash taking out the trash it's really quick it takes half a
second 500 milliseconds if I need to do these chores in order I would need to use
some
642:31
callbacks after walking the dog we will call a call back to clean kitchen after we
clean the kitchen we will take out the trash we need to modify these functions so
that they accept some call
642:42
backs after our code is complete we will invoke the call back call the Callback so
let's add that parameter to each of these functions now if we want to call all
these functions in order we would have
643:00
to start using call back hell which we learned about out in the last video so first
I would like to walk the dog I will call that function pass and a call back but
we'll use an arrow
643:09
function then we will clean the kitchen pass in a call back I'll use an arrow
function take out trash and we'll pass in a call back to do this when we complete
all the chores
643:27
[Link] you finished all the chores okay let's see if this works you walk the
dog you clean the kitchen you take out the trash you finished all the chores if we
have a lot of callbacks to
643:44
work with we'll end up going to call back hell you don't want to go to call back
hell so what we'll use instead are promises with all of this asynchronous code
we'll wrap it within a promise by
643:55
using a promise we don't need callbacks instead of using callbacks we'll use method
chaining we'll method chain our Pro promises here's how how we'll modify these
functions is that at the end of
644:06
each function we will return an object return a new promise return a new promise
object and follow this formula we have two parameters resolve and reject resolve
reject Arrow do this asynchronous code
644:26
within an arrow function take all of the asynchronous code cut it place it within
the promise our promise promises to return a value it's either going to be resolved
or rejected we're going to
644:39
modify this function we don't need to work with call backs anymore we can get rid
of those get rid of the parameter and the portion of the code where we call the
call back if we would like to
644:48
display a message when the promise resolves when it finishes successfully we will
instead call the resolve parameter it's a function this message is the value the
argument that we're
645:00
passing in after you finish walking the dog here's your completion message when the
promise resolves let's modify the rest of the functions so that they use promises
we will return a new
645:13
promise two parameters resolve reject Arrow do this asynchronous code let's cut our
current asynchronous code paste it remove the call back parameter we don't need it
anymore and
645:30
we don't need to call the call back when this promise resolves pass along this
message you clean the kitchen let's do this with take out trash we will return a
new
645:44
promise two parameters resolve reject Arrow do this cut the asynchronous code paste
it within the promise remove the call back and where we call the call back when we
resolve this promise pass
646:01
along this message we no longer need to use callback hell instead we're going to
use method chaining first we're going to walk the dog clean the kitchen and then
646:10
take out the trash in that order we will call the walk dog function and then we're
going to Method chain follow this with the then method walk the dog then what is
what
646:24
we're saying the walk dog function does provide a value parameter this message we
can use that message for something that's going to be stored within value that's
going to be the parameter that's
646:36
provided to us take the value let's print it [Link] my value so when I run
this program we should only be walking the dog you walk the dog and nothing else
looks like I misspelled resolve as
646:52
resolves there after walking the dog I would like to clean the kitchen so I need to
call that function next within our Arrow function we'll write more than one
statement we need to enclose this
647:04
within a set of curly braces print our value and then do this function return clean
kitchen and then call it we'll add another then method then take the value provided
by clean
647:22
kitchen that will be this one take that value arrow [Link] that value you walk
the dog you clean the kitchen then we'll take out the trash at the end we'll add
another statement to this then
647:46
method we will return take out trash invoke this method then we will take the value
provided to us when it resolves this value do this code [Link] that value you
walk the
648:12
dog you clean the kitchen you take out the trash so after taking out the trash
that's our last chore let's add another line of code after displaying you take out
the trash let's [Link] you finish
648:32
all the chores you walk the dog you clean the kitchen you take out the trash you
finished all the chores by Method chaining then methods it's a lot easier to write
than nesting
648:47
call backs now sometimes with asynchronous functions depending on the task the task
May Fail let's say we're trying to locate a resource a file if we can't locate that
file and we're using
648:59
promises we don't want to resolve that promise because we couldn't locate that file
instead we want to reject that's what happens when an asynchronous function fails
to do something when inside a
649:09
promise so let's change our functions around within set timeout let's create a
variable const dog walked did we accomplish this this will be true or false we'll
use an if statement if dog
649:26
walked then we will resolve it if we walked the dog else we will reject we'll pass
in a different value you didn't walk the dog okay let's do this with the other
functions let's create a constant of
649:50
kitchen cleaned equals true if our kitchen is cleaned if that is true we will
resolve this promise you clean the kitchen else let's reject pass along this
message you didn't clean the
650:15
kitchen and lastly take out trash const trash taken out let's set that to be true
if the trash is taken out resolve the promise else we will reject you didn't take
out the
650:47
trash if a promise might reject there's one more method we need to add to the end
of this chain we need to add a catch method to catch any errors this will catch any
Rejects this
651:01
is similar to error handling we'll be provided with one value an error Arrow do
this let's [Link] or even console. error the message provided to us with
reject that's what the error is going to
651:18
be we'll successfully walk the dog that will be true and cleaning the kitchen will
be true but taking the trash out will be false we weren't able to complete this
chore these are the results
651:33
you walk the dog you clean the kitchen you didn't take out the trash how dare you
we'll keep on completing these tasks until we fail at one of them so if walking the
dog was false that was our first
651:51
task this first promise was rejected we don't even attempt to resolve these other
promises all right everybody so those are promises they're an object that manages
asynchronous operations you
652:03
can wrap a promise object around some asynchronous code these promise objects
promise to return a value they will be pending until they complete then they'll
either be resolved if that task
652:14
completed successfully or rejected if it failed for some reason and well everybody
those are promises in JavaScript hey everybody so today I got to talk about a sync
and a weight in
652:28
JavaScript a sync and a waight are two keywords by using these two keywords
together they allow you to write asynchronous code in a synchronous manner a sync
makes a function return a
652:39
promise a wait makes an async function wait for a promise we'll discuss async first
in this sample program from the last topic we have some chores to do we have to
walk the dog clean the kitchen
652:51
and take out the trash each of these functions returns a promise a promise that can
either resolve or reject based on the code that's written if the dog is walked if
if that's true resolve if it's
653:03
false reject a function can be declared with a sync a function declared with a sync
will return a promise however that promise that's returned doesn't resolve or
reject in a way you could say it's an
653:16
empty promise if I were to run this code this is what happens uncaught reference
error resolve is not defined if an asynchronous function returns a promise that
either
653:28
needs to resolve or reject adding a sync to it really doesn't benefit us a sync
works together with a weight by using these two keywords together when calling all
of these asynchronous functions in
653:40
order we don't need to Method chain then statements there's a more synchronous
manner in which we can write the same code but we'll need to contain it all within
an async function async function
653:52
we'll create a function to do chores then we will need to call this function
somewhere let's do so right here first we need to walk the dog walk the dog returns
a
654:06
promise that's where the await keyword comes in a wait makes an async function wait
for a promise before continuing we're going to create a constant of walk dog result
equals use the await
654:22
keyword await walk dog then we will [Link] the walk dog result you walk the
dog now let's do this with clean kitchen we're going to be writing this code in a
synchronous manner line by line
654:42
linearly we will create a constant for clean kitchen result equals await the next
promise await clean kitchen then [Link] clean kitchen result let me close this
you walk the dog you clean the
655:03
kitchen and last we have take out trash const takeout trash result equals a wait
take out the trash then [Link] the result you walk the dog you clean the
kitchen you take out
655:25
the trash let's add one more line when we finish everything one more line of code
you you finished all the chores you walk the dog you clean the kitchen you take out
the trash you finished all the
655:39
chores let me show you what happens if we attempt to use a weight within a function
not declared with a sync uncaught syntax error a weight is only valid in async
functions that's why
655:52
a weight depends on async a weight makes an async function wait for a promise
before continuing now if your promises can reject let's say that dog walked is
false uncaught in promise you didn't
656:10
walk the dog we'll surround all of this code within a tri block then catch any
errors catch one parameter of error we can [Link] or console . error the error
you didn't walk the
656:36
dog all right everybody so that is a sync and a wait a sync makes a function return
a promise a wait makes an async function wait for a promise by using these two
keywords together we can write
656:51
asynchronous code in a synchronous Manner and well everybody that is a sync and a
wait in JavaScript what's up everybody so today I got to talk about Json files
using
657:05
JavaScript Json means JavaScript object notation it's a data interchange format
most of the time it's used for exchanging data between a server and a web
application they can have a few
657:17
different formats usually you'll see a Json file as an object an object made up of
key value pairs or you may see them as an array an array of values or some
combination of both you can have an
657:30
object where one of the values is an array and or you could have an array of
objects like this just to understand the format we'll create a new Json file let's
go to our website folder create a
657:43
new file we'll create an array of names the file extension is Json we'll Begin by
writing an array with a set of straight brackets let's add a few names just some
first names SpongeBob
657:59
Patrick Squidward Sandy this is a valid Json format let's create a new Json file
just for a single person this will be an object new file person. Json this time we
will create a single
658:19
object this object will have key value pairs we will have a name key and a value of
SpongeBob each key value pair is going to be comma separated SpongeBob will have an
age key of
658:38
30 and a Boolean of is employed is SpongeBob currently employed that will be true
this is also a valid format our Json file contains one object an object made up of
key value pairs objects can
658:54
even have arrays as one of their values we will create an array of hobbies what
what does SpongeBob like to do this will be an array jellyfishing karate and
cooking let's create one more Json
659:15
file we will create a Json file for people this will be an array of objects people.
Json we're going to create an array of objects within this array we'll create one
659:27
object what key value pairs should this object have we'll just reuse what we have
for SpongeBob excluding the array to keep it simple okay that will be the first
object let's create another object we
659:42
need another set of curly braces the second object will have a name property of
Patrick age 34 is employed will be false the next object this will be for Squidward
age
659:59
50 is a employed true he works at the Crusty Crab one last object name Sandy age 27
is employed false Sandy is self-employed all right we have an array of objects each
object can have its own
660:18
unique key value pairs so let's close out of these Json files but we'll hold on to
them so Json formats they're one long string to represent that object or array
using the stringify method of Json we
660:33
can convert a JavaScript object or an array into a Json string so let's copy what
we have for names I will create a constant of names equals that array we'll convert
it to a Json
660:50
string const Json string equals access Json Json is a built-in object that's
provided to us to work with Json files we will use the stringify method then pass
in our array or our
661:07
object currently if I were to [Link] my names before stringifying it here's
the result we have an array of strings to work with after using the stringify
method on names we'll be given one long
661:22
string to represent this array if I was to use this on an object let's copy what we
have for person I will create a const of person this will be an object I'll just
paste what I
661:37
have for SpongeBob first let's [Link] person here's my person object then
let's stringify it and display the Json string Json files work with one long string
that represents an object or an
661:54
array let's stringify our people it's an array of objects const people equals paste
what we have let me show you what happens when I [Link] people before
stringifying it we have an array of
662:15
objects each object has its own key value pairs then if I was to stringify it
here's the result one extremely long string now we'll use parse parse converts a
Json string to a JavaScript
662:33
object so let me reformat these to convert these objects or arrays into a string we
can surround them with a pair of back ticks so let's rename these let's say Json
names Json person then Json
663:15
people these objects and arrays are all in a Json format to convert them to their
original form we can use the parse method of Json I will create a constant of par
data equals Json
663:32
parse pass in our data of Json names and then let's [Link] let me show you
Json names first before parsing it we have a string representation of an array but
after
663:46
parsing it it becomes a JavaScript array let's do this with our string
representation of an object Json person normally it looks like this and then after
parsing it we have a JavaScript object
664:01
and then Json people it's an array of objects then we'll parse it and here's the
result an array of objects now I'm going to show you how we can fetch a Json file
we'll talk about
664:15
fetch more in the next topic fetch is a function as an argument we can pass in a
relative or absolute file path or a URL we'll discuss that in the next topic I
would like to get my Json file
664:28
of let's go with person so I will list the relative file path these files are right
next to each other I just need to type person. Json fetch returns a promise we will
follow
664:43
this with the then method then do this we'll be provided with a response object
take our response Arrow do this we will take our response object convert it to a
Json format using the Json
664:59
method then let's display what we have currently then take the value arrow
[Link] that value let's see what we have yep there's SpongeBob we have
successfully fetched a
665:16
Json file let's do this with our array of names we have an array of strings of
first names and people people. Json we have an array of objects one object for each
person if you would like to iterate
665:35
through all the objects let's rename value as values we'll use the built-in for
each method of arrays values. for each take each value Arrow do this [Link]
each
665:53
value now we're iterating through and printing each object if you would like some
of the specific properties like make name follow the value with name SpongeBob
Patrick Squidward Sandy or age or is
666:12
employed oh and another thing that I'm forgetting be sure to add a catch method to
catch any errors just in case we can't fetch this Json file for some reason
[Link] or console. error the error
666:27
message we'll talk about fetch more in the next topic all right everybody so those
are Json files Json means JavaScript object notation it's a data interchange format
it's mostly used for
666:39
exchanging data between a server and a web application Json files are usually
objects or an array or some combination of both to convert a Json object to a
string you can use the stringify method
666:51
to convert a Json string to an object you can use the parse method to fetch a Json
file you can use the fetch function which we'll talk about next and get more in
depth with and well everybody those
667:02
are Json files using JavaScript well it's going on everybody so in today's video
I'm going to show you how we can fetch data from an API using JavaScript and at the
end of this
667:14
video we're going to create a project where we can fetch some images of Pokémon
depending on what Pokemon you type in so sit back relax and enjoy the show all
right people so we got to talk
667:24
about fetch fetch in JavaScript is a function it's used for making HTTP requests to
fetch resources including but not limited to Json styled data images files
resources of that nature
667:38
the fetch function simplifies asynchronous data fetching it's used for interacting
with apis to retrieve and send data asynchronously over the web fetch has two
arguments a URL of the
667:52
resource and an object an object of options I won't be talking about options in
this video that's more advanced JavaScript one of what you may see is a method
property the default is get to
668:04
get a resource you can use post to send some data put to replace some data and
delete to delete some data so the default is get but we don't need to explicitly
state that we'll just be
668:18
focusing on getting data with only a URL to fetch something we have to use the
fetch function and pass in a URL what I thought we could do for this video is fetch
some Pokemon data from the Pokémon
668:30
API if you want to follow along you can go to this URL I would like to fetch some
data on Pikachu because everybody knows about Pikachu and here's some of the data
on
668:43
Pikachu this resource is one gigantic object Pikachu has a name an ID number a type
Pikachu's an electric type there's stats such as his attack power HP there's even
image Sprite which we'll
669:00
work with later we will copy this URL and paste it within the fetch function we
will pass in a string representation of this URL the fetch function is promise-
based it's either
669:13
going to resolve or reject so we should add a then and a catch method to catch any
errors error Arrow do this let's console the error if there's an error once the
669:29
promise resolves will be provided with an object a response object take our
response object Arrow do this for the time being let's [Link] our response
just to see what it is
669:45
exactly so here's our response object the body contains the data we're looking for
for Pikachu this response object has a status code of 200 that means it's okay
here's where you may see
670:00
that status code of 404 if you can't locate a resource it has an okay property if
fetching this resource was okay this is going to be true if not it's false there's
also a URL here too
670:12
now our next step is to convert it to a readable format there's a few different
methods there's array buffer blob text and Json these are all methods we're
interested in the Json method in this
670:26
example so our next step is to take our response object convert it to Json using
the Json method this is also promise based once this promise resolves let's follow
this
670:39
with a then method then take the data our Json data that's going to be returned to
us Arrow do this let's [Link] my data just to see what it is so after fetching
data on Pikachu convert the
670:55
response object to a Json format and here's my data for Pikachu we have a name an
ID Pikachu stats such as his HP and attack and wait and many more things with this
Json data you can
671:13
access one of the properties I would like just Pikachu's name data. name Pikachu
data dot weight how much does Pikachu way 60 60 units of something whatever unit of
measurement they use in
671:29
Anto what is Pikachu's ID 25 near the end of this video we're going to fetch the
Sprites of the Pokémon now for some reason if we try and access a Pokemon that
doesn't exist as of the filming of
671:41
this video SpongeBob is still not a Pokemon we get a status code of 404 meaning we
could not find this resource SpongeBob is not a Pokemon unfortunately so even if we
can't locate a resource
671:57
our promise is still going to resolve it's not going to reject we need to check to
see if our response is not okay let me demonstrate I will [Link] my response
672:09
object here's my response object it is not okay your response will be okay if the
status is within the 200 range since we have a status of 404 we couldn't locate
this resource okay is false we're
672:22
going to throw an error if our property of okay is false within our first then
method we'll write a few statements we need a set of angle brackets before
continuing let's check to see if our
672:38
response access the okay property then use the not logical operator if our response
is not okay if it's false we're going to throw a new error and then catch it using
the catch
672:53
method we can write a custom message let's say something like could not fetch
resource if our resource is okay we won't execute this code otherwise we will
return our response object in a Json
673:13
format let's try and retrieve Pokemon data on SpongeBob okay we have an error but
we have caught this error using the catch method error could not fetch resource
then let's get data on Pikachu
673:27
again and there Pikachu and his ID number if you would prefer to use a sync and a
weight here's how let's delete all this we will create an async function so that we
can use a weight within it I
673:46
will declare a function to fetch data no parameters do all this we will create a
try and catch block try and catch catch has one parameter an error if we receive an
error let's console. error the
674:09
error within our Tri block we will create a constant of response the fetch function
is going to return an object a response object we will await our promise that's
returned by
674:24
fetch then we need to get that URL again let's get data on a different Pokémon
another Pokemon that I like is tyion honestly I think tyion is my favorite Pokemon
all right here's the stats for
674:41
tyion I'm going to copy this URL pass it to the fetch function as a string once the
promise for fetch resolves we have to see if the response is okay we'll use an if
statement if our response
675:00
object is the okay property not okay if our response is not okay if we can't locate
this resource then we will throw a new error let's say could not fetch resource if
our response is okay we will
675:22
create a constant for our data equals await take our response and convert it to
Json this also returns a promise that's why we're using a wait then we will
[Link] our
675:40
data and then we have to call the fetch data function because I forgot to do that
call fetch data and here's the stats for tyion Name tyion ID 157 tyion is a fire
type that's how to use a sync and a
676:00
weight to fetch a resource now that we know what we're doing we're going to create
a text box and a button to search a Pokemon and pull up a Sprite of that Pokemon
and
676:10
display it so going to our HTML file we will create an input element with the type
attribute of text because it's a text box I will set the ID of this input element
to be Pokemon name
676:29
it's a little small right now we haven't applied any CSS I will add a placeholder
of enter Pokemon name then we need a button I will create a button element with
text of fetch
676:49
Pokemon I will set the onclick event handler equal to a JavaScript function let's
call that function a fetch data then I will add a break after fetching some Pokemon
data
677:07
we have an image to work with I will set the source currently to be an empty string
I will display some alternative text if we can't display the image of Pokemon
Sprite and I will give this element an
677:23
ID of Pokemon Sprite to not display the image currently we can access the style
access the display property and set it to be none then if we do want to display it
we
677:39
can set display to be a block let's go to our Javascript file within our Tri block
we will create a constant of Pokemon name equals document. getet element by ID the
ID that I'm selecting is Pokemon
678:02
name access the value of this input element now if somebody types an uppercase
characters I'll take the value make all the letters lowercase I will method chain
the two lowercase method two lowercase
678:25
method with our fetch function we're going to use a template string with a pair of
back ticks for the Pokémon's name we will use a placeholder and pass in our Pokemon
name
678:39
variable so now when I type in a Pokemon's name like Bulbasaur we should get data
on that Pokemon if it exists so let's go to inspect console and here's data on
Bulbasaur Bulbasaur's ID is
678:56
one Bulbasaur is a grass type and I think he's a poison type too if I'm not
mistaken this Json data also has Sprites images of each Pokemon we're going to
fetch the front
679:11
default so we don't need [Link] anymore we'll create a constant of Pokemon
Sprite to get that image equals take our data access the Sprites property get the
front default
679:33
Sprite then we will get our image element this one that has an ID of Pokemon Sprite
const image element equals document. getet element by ID the ID that I'm getting is
Pokemon
679:53
Sprite we will change the CSS of this element take our image element access its
source attribute right now it's currently empty our source is an empty string set
the source equal to our
680:09
Pokemon Sprite this is a constant then we will take our image element access the
style attribute access the display property and set it equal to be a block because
right now it's
680:25
none now when I type in a Pokémon's name like Charizard and fetch that Pokémon we
get the image of that Pokémon it is a little small however it is a Sprite Sprites
tend to be very small or we can get
680:43
meww or whatever other Pokemon you can think of I think there's like over a
thousand Now where's tyion there's tyion all right everybody so that is how to
fetch data from an API
680:56
you got to use the fetch function it's is used for making HTTP requests to fetch
resources you can fetch Json style data images files the fetch function simplifies
asynchronous data fetching
681:09
it's used for interacting with apis to retrieve and send data asynchronously over
the web and well everybody that is how to fetch data from an API using JavaScript
hey everybody so in today's
681:23
video we're going to create a weather app that fetches data from an API you can
look up any didn't get the weather if that sounds good to you then sit back relax
and enjoy the show if you would
681:34
like to follow along you will need your own API key the API that we'll be using is
[Link] you do need to sign up for an account though it is free to sign
up for an account you can go to
681:46
sign in if you're currently not registered you can create an account for free once
you're signed in you'll need an API key go to my API Keys it may take you some time
to get an API key
682:00
generated for you mine took about 15 minutes and once you get it make sure it's
active we will need that API key about 20 minutes into this topic hopefully for you
by then it'll be
682:13
generated okay let's do this everybody we will Begin by creating a form element the
form element will have a class of weather form our form element is going to have an
input element and a
682:26
button within this input element we'll type in the name of the city we would like
to retrieve the weather data 4 so the type of this input element is going to be
text for some
682:38
text the class will be City input so a user can type in the city and we'll add a
placeholder let me zoom in a little so you can see it the placeholder will equal
enter
682:54
City then we'll need a button let's create a button element with text of get
weather the type of this button will be submit it's the submit button for our form
after retrieving the weather data
683:12
we'll display the weather data in a card format like a Pokemon or Yu-Gi-Oh card so
we will create a div elopement with a class of card but before applying some CSS we
683:26
should at least add some placeholder elements so we can style them and see the
changes for the time being let's create an H1 element we will be deleting these
elements later so don't get too
683:37
attached I will set the class of this element to be City display We'll add a sample
City let's say Miami or pick a city if you're choosing then I will create a
paragraph
683:51
element the class will be temp display meaning temperature let's say the
temperature is 90° fah or pick something in celsius if you're on Windows to add a
degree symbol you can hold alt then type
684:05
0176 Miami is going to be 90° F then we'll create a paragraph element for the
humidity class equals humidity display for the text let's say humidity colon space
then a percentage 75%
684:28
then we need a description of the weather this will be another paragraph element
the class will equal description display desk meaning description for the
description let's say clear
684:42
skies I'll also display an emoji depending on what the weather is the class will be
weather Emoji I'll use a sun for some reason if we can't display the weather data
such as if we can't locate
685:02
a city let's add the following paragraph the class of this element will be error
display We'll add the text of please enter a city that is all the HTML that we need
685:20
for now we're going to apply some CSS styling next so now let's head to our CSS
stylesheet we are going to select the body of document select a font family I will
pick Ariel with a backup of s
685:35
serif I'll change the background color of the body background color pick a color
I'm going to use hsl values I will set the lightness to be 95% so it's a light gray
color I will
685:51
set all margin around the body to be zero then I'll use flexbox to display the
element elements display Flex the flex direction will be a column to arrange all
the elements in a
686:07
column then align item Center to horizontally align all the elements align item
center now we'll select the class of weather form that'll be this form that has an
input element and a
686:22
button all we'll do is add a little bit of margin around the entire form 20 pixels
then we'll select our city input that's going to be the text box class of City
input I will add some padding of 10
686:41
pixels let me zoom out to 100% increase the font size to 2 RM set the font weight
to be bold I'll add a border two pixel solid and pick a color but all lower the
alpha so it's transparent to
687:14
30% there's our border currently border radius around the corners let's do 10
pixels add some margin of 10 pixels that'll separate this element from the button
and set a width of 300
687:34
pixels okay let's style the button next okay we are going to select all buttons
that have an attribute where the type equals submit so that's going to be for our
687:48
submit button that says get weather let me scroll down okay I'm going to add some
padding around the button 10 pixels by 20 pixels I'll set the font weight to be
bold I'll increase the font
688:07
size to be to R pick a background color for the button I'll pick something green
but I'll use hsl values I've already pre-picked a color let's go with 122 the 39%
and 50% that's a good shade of
688:34
green I will set the color to be white for the font color remove the border border
none and Border radius 5 pixels to round the corners then when we hover our cursor
688:52
over the button I would like it to be a pointer and that does work when we hover a
cursor over the button we'll use the hover Pudo class to change the background
color so let's take our
689:04
button for the type attribute is submit access the hover sudo class take our
background color make it a little bit darker I'll bring down the lightness by 10%
so it's at 40% so that does in fact
689:19
work okay then we're going to select our card class that contains all the weather
data so we will select the class of card for the background we're going to do
something a little bit different
689:33
we're going to use a linear gradient instead of selecting the background color we
will select the background I will use the linear gradient function there's three
arguments think
689:46
of a linear gradient as a slow transition between two colors we need an angle in
degrees we'll say 180° for now then a color let's pick something blue and orange
I'm going to pick some colors
690:04
that look a little bit better so for blue let's set the Hue to be 210 100% for the
saturation and the lightness will be 75% that's a good shade of blue and for orange
we'll use another hsl
690:25
value for the Hue I'll say 40% the saturation will be 100% And The lightness will
be 75% so I'm hoping with this linear gradient the background color looks kind of
like a sunrise or a sunset once we
690:41
have our background I will add some padding of 50 pixels I'll add a box Shadow to
this card we'll add a vertical and horizontal offset of two pixels each and a blur
effect where the radius is 5
690:55
pixels then we'll pick a color I'm just going to lower the alpha to 50% not bad
this gives our card a 3D pop effect I will set a minimum width of this card to be
300
691:15
pixels then we have to align everything within it I'll use flex box because I like
Flex box display Flex Flex direction will be a column and align items Center to
horizontally align the
691:37
items there we go then we'll select all H1 elements that's going to be our city
name select all H1 elements increase the font size to be 3.5 RM I'll remove any
margin from the top margin top will be
691:59
zero and add margin to the bottom of 25 pixels then we'll select all paragraphs
that's going to be everything underneath our city select all paragraphs increase
the font size to 1.5
692:19
RM there's a lot of natural margin between the paragraphs let's set all margin to
be zero to see what it looks like okay let's add a little bit of margin five pixels
on the top and bottom zero margin
692:33
on the sides that's a lot better we'll select the city display and the temperature
display we're going to be selecting two classes City display comma our temp display
take these two classes apply the
692:49
following properties you know what for our font size let's set that to be 3.5 RM we
can honestly remove that from H1 for the font weight I will set that to be bold for
the color I'll make the
693:04
color a little transparent I'll set the alpha down to 75% so that our city and our
temperature they're both going to be transparent then I'll add some margin to the
bottom margin bottom 25
693:22
pixels okay let's select our humidity display class humidity display set the font
weight to be bold and add some margin to the bottom of 25 pixels then we'll select
our description
693:43
display which we shortened to desk display for the font style I will set it to be
italic and the font weight will be bold I'll increase the font size to 2 RM then
we'll select our weather Emoji
694:05
so class weather Emoji remove all margin around the Emoji margin zero then we'll
increase the font size of the Emoji the size will be 7.5 RM so it's kind of big
then if for some reason we display
694:22
an error we'll display this text so this class is error display I'll set the font
size to be 2.5 RM the font weight will be bold I'll set the color to be something
transparent I'll lower the alpha to
694:48
75% okay that is all the CSS that we need let's go back to our HTML file we can
delete everything within the card class we just wanted to see what it would look
like with the elements populated with
695:02
our card element I will set the style attribute to be take the display property set
it to be none we don't want to display the card at all until we get the weather
data until it's returned to
695:14
us our HTML is done our CSS is done then we're ready to add some JavaScript
functionality we'll declare our constants that we need const weather form equals
document dot now since we're not working
695:31
with IDs we can't get element by ID we're working with classes we can use Query
selector or query selector all so I'm going to use Query selector this will return
the first element in this
695:45
class we only have one element with this class class weather form we'll store a
reference to it const City in input equals document. query selector we are
selecting the class of
696:07
City input that's going to be this text box const card our card is what contains
all the weather data document. query selector select the class of card and give me
the first
696:29
element now we'll need that API key const API key equals now here's my API key
please don't try and use this one specifically I will be deactivating it at the end
of
696:43
this video hopefully by now you should have that API key given to you first we'll
take our weather form We'll add an event listener this is our form the text element
and the submit button
697:01
when we click on this button the event type is going to be submit after we attempt
to submit this form we'll do the following code we'll have one parameter an event
that's going to be provided to
697:12
us Arrow do this we'll fill this in later we'll declare our functions that we need
we will need an async function to get weather data there will be one parameter a
city that's going to be passed
697:32
in then we'll need a function to display weather info there will be one parameter
data the data will be in a Json like format we'll create a function to get weather
697:52
Emoji based on what the weather is there will be one parameter a a weather ID then
we'll create a function to display to the screen any errors if there are any
function display
698:08
error there will be one parameter a message a message to be displayed to the window
within our event listener once we have a submit event once we click the button
forms do have a
698:21
default Behavior where they'll refresh the page we would like to prevent that so
let's take our event use the prevent default method to prevent the default behavior
for a form we don't want to
698:35
refresh the page then we'll have to get the city the value within this text box
const City equals take the city input access the value store it within this
variable it should be a
698:50
string we'll use an if statement if City if there's a value within here this this
will be true we can use it within an if statement if there is a city do this else
we'll call the display error
699:08
function else we will display an error we will pass along the message to please
enter a city let's fill in the display error function we want to be sure that it
works before continuing the display
699:25
error function is at the bottom will be provided with a message to display we will
create a constant of error display equals document now we'll create an element
create element we will create a
699:43
paragraph then we'll need to change the text content of this element error display
access the text content set it equal to be our message then we're going to add the
699:58
class of error display we would like these CSS properties take our error display
element access the class list then we will add a class we will add the CSS class of
error
700:17
display then we will take our card element which normally displays the weather data
take our card reset the text content if there is something there we'll set it to be
an empty string so
700:30
normally with our card the display is set to none we'll set the display to be a
block or even Flex access our card access the style access the display and I will
set the display to be Flex to display
700:47
it we will take our card we will append a child element append child we will append
this par paragraph of error display to the card now if I were to not type in
anything and just press get
701:03
weather we get this error message please enter a city to our card I'm just going to
round the corners to make it look better border radius let's do 10 pixels that's
better okay moving on if
701:21
we do have a city if there's text within here we will try some code because it
might cause some errors we will catch any errors that happen we have one parameter
of error if there's an error
701:35
we can [Link] or console. error the error then let's call our display error
function we'll pass along the error and display it now we need to get the weather
data
701:50
within our Tri block we will create a constant of weather data equals now we need
to await get weather data function and pass in our city so with the weight we can
only use a weight within an async
702:09
function since we're within an arrow function we could declare this Arrow function
as an a sync function so let's preedee our event parameter with a sync so that we
can use a
702:21
weight we're going to wait for this function to return the weather data once we
receive our weather data we will call the display weather info function and pass
along that data the weather
702:36
data okay this function is complete once you've typed everything in I'm going to
close this function and we can close our display error function too now once we
want to get our weather
702:49
data after we have a city now we actually need to fetch the weather data we'll have
to create a URL we'll create a constant of API URL this is what we'll pass to the
fetch
703:02
function we will use a template string be sure to use a pair of back ticks we'll
need to get the following URL at this web page we need to find the API call where
703:16
we can pass in a city name we can copy this within our template string we'll paste
it we'll replace the city name with the placeholder and use our city variable for
the API key we'll use a
703:38
placeholder pass in the API key this is what we'll pass to the fetch function we
will create a response const response equals a weight we can use a weight because
we're with within an
703:56
async function we will fetch our API URL once we have a response let's check our
response let's [Link] our response just to see what it is okay I will type in
the city of Miami
704:15
get weather our data should be within [Link] here's our response it has a
status of 200 and it's okay we need to check to see if our response is not okay
what if we couldn't
704:30
retrieve the data I'll make up some gibberish City let's go to inspect console we
have a response status 404 the response is not okay we'll write an if statement if
our response is not
704:51
okay we will throw a new error and pass along the this message could not fetch
weather data else if our response is okay we will return the response and we will
await our response convert it to a Json
705:14
format using the Json method so at the end of this function return an object that's
in a Json like format this data is going to be returned to our event listener after
we get our weather data
705:30
we need to display it we'll work on the display weather info function next this one
let's [Link] the data we receive I will type in Miami so it looks like that
705:49
worked we have a name of Miami for the city we have the weather which is an array
it's an an array of objects we have coordinates clouds pretty much anything you can
think of regarding the
706:02
weather let's get the name within main there is temperature the temperature will be
in kelvin we need to convert it I'll get the humidity within weather it's an array
of objects we will get the
706:16
description overcast clouds and this ID eventually we'll use the ID to return an
emoji there's different weather codes I'll explain that later so we're going to use
some object
706:29
destructuring const use object destructuring with a set AC krly brackets we will
access the name property and create a variable of city city will be Miami in this
case then we
706:44
will access main main is a property that contains an array take main use object
destructuring again now we're within a nested object I would like the temp and the
humidity then let's select our
707:05
weather so whether it's an array of objects we'll have to use array destructuring
followed by object destructuring give me the description and the ID we have to set
this all equal to data to use
707:28
destructuring and let me organize this to make it look nice our data is one
gigantic object that has nested objects and nested arrays so after destructuring
we'll have
707:41
these variables the city the temperature the humidity a description of the weather
and an ID for the weather code now we can use these like variables so with our card
currently
707:54
we're not displaying it now I would like to to display it we are going to take our
card set the text content to be an empty string if there's already some text here
we would
708:07
like to reset it such as if there was an error message take our card access its
style set the display property to be Flex for Flex box just to be sure that this is
working
708:23
I'm going to get the weather without entering a city after we do type in a city it
should reset that's good that's what we wanted or if we make up some gibberish we
have
708:34
that error could not fetch weather data but then if we type in something legitimate
and get the weather it'll reset that's what we would like okay now we have to
create the
708:45
elements the elements that we previously deleted from the div element we need to
recreate those we will create a constant for City display to display the city
document. create element our city
709:03
display was an H1 element let's copy this line of code and paste it a few times
four additional times we have City display temp display for the temperature that
was a paragraph element humidity
709:21
display humidity display that was also a paragraph element a description display
which we shortened to desk desk display that was also a paragraph and a weather
Emoji weather emoji and that was also a
709:42
paragraph okay now we need to change the text content of each of these elements but
they're empty so to say let's take the text content of our city display. text
content
709:54
property equals our city variable that we destructured okay let's see if that works
I'll type in a city get weather oh and then we need to append it take our card
append child we will append the
710:11
city display element let's try that again type in Miami get the weather that should
display Miami let's try Dallas Texas Dallas Oh and before displaying it we need to
add the class list the CSS class
710:29
for the city display after adding the text content we will take our city display
access its class list add the class the CSS class of City display so then when we
type in a city we should
710:45
have that CSS styling all right now we have to add the temperature following the
same format we will take our temp display access the text content equals I'll use a
template string with a
710:59
pair of back ticks I'll add a placeholder pass in our temperature add a degree
symbol you can hold alt then type 0176 for a degree symbol now this is normally in
kelvin actually I don't
711:12
think Kelvin uses the degree symbol but we'll be changing that momentarily take our
temperature display access its class list add the following class add the CSS class
class of temp
711:29
display then we have to append the element to the card element take our card we
will append a child element of temperature display so now we should see the
temperature but it's going to be in
711:44
kelvin we have the city and the temperature for the temperature if you would like
Celsius let's use deg CI you have to subtract from the temperature 200 17315 okay
but now we should probably
712:03
round it so let's enclose this equation with a set of parentheses follow this with
the two fixed method of numbers to round it to one decimal place 15.6 de C if you
would like a
712:20
Fahrenheit temperature this is the formula take our temp in Kelvin minus 273.15 we
will multiply this by 9 / 5 plus 32 so let's enclose this all within a set of
parentheses so now we should get that
712:44
temperature but in Fahrenheit oh and then add F to the end 60° F then we'll get the
humidity so take our humidity display element that we created access the text
content set
713:01
it equal to be a template string using a pair of back ticks let's add the word
humidity coin space add a placeholder display our humidity variable We'll add the
class list of humidity
713:18
display humidity display access its class list add the following class of humidity
display then we have to append the element to the card element card. append child
append our humidity
713:39
display so we should get the humidity Miami 60° fhe humidity 81 let's add percent
81% yep that does work then we'll add the description a description of the weather
take the element of description
713:59
display access the text content equals the description then add the CSS class to
the class list for this element description display access the class list add the
following class of description
714:23
display then add the element card. append child we will append our description
display let's type in Miami get the weather currently in Miami there's overcast
clouds now we have to get an
714:40
emoji based on the weather with our element of weather Emoji we will access the
text content equals we will call the get weather Emoji function but we have to pass
in a weather
714:54
ID so we will pass in the ID variable that we receive from data once we get our
weather Emoji we'll work on that momentarily we'll take our element of weather
Emoji
715:11
access the class list add the following CSS class of weather Emoji then append it
to the card card. append child we will append our weather Emoji all right now
before we canest it
715:31
we need to fill in the get weather emoi function so with this open Weather AI there
are different group codes so our weather ID is going to be either within the 200
range meaning a thunderstorm the
715:45
300 range means drizzle 500 is rain 600 is snow 700 is atmosphere such as Mist
smoke or even a tornado 800 exactly is a clear sky anything greater than 800 means
716:01
clouds so our weather ID is going to be one of these codes so we're going to use a
switch we will examine the Boolean value of true does the value of true match one
716:14
of these cases we'll have a case for group 200 if our weather ID that we pass in is
greater than or equal to 200 00 and the weather ID is less than 300 that means
there's a
716:37
thunderstorm we will return an emoji a thunderstorm Emoji thunderstorm I don't like
the look at that one that's better okay group 300 is a drizzle so let's copy this
case because I don't
716:57
feel like retyping it if our weather ID is greater than or equal to 300 and less
than 400 that means we have a drizzle we'll just add an emoji of a raining Cloud so
group 500 is also rain but it's
717:17
a heavier rain so let's copy this case paste it if our weather is greater than or
equal to 500 and less than 600 will return rain as well group 600 is snow if our
weather ID is greater than
717:41
or equal to 600 and less than 700 we will return a snowflake meaning snow then we
have group 700 if our weather ID is greater than or equal to 700 and less than 800
we'll return some fog
718:08
Emoji 800 exactly means a clear sky we can display the sun if our weather ID is
strictly equal to 800 exactly we'll return a sun emoji anything within the 800
range means clouds so if our weather
718:40
ID is greater than or equal to 801 800 means clear sky so with this group code it
only goes up to 809 if our weather ID is less than 810 return a cloud then let's
add a default in case
719:01
we get a weird weather code default return I don't know a question mark we get some
unknown weather phenomena UFOs or something I don't know okay and I think that
should be
719:22
everything let's close out of this close out of these functions and now if I were
to type in Miami and get the weather in Miami it is 60.3 De F humidity 81% there's
overcast
719:37
clouds and we get a cloud Emoji because it's cloudy let's try Dallas we have a
clear sky 45° fah humidity 63% clear sky and we get a sun emoji all right everybody
so that is a weather app
719:53
that you can make using Java JavaScript HTML and CSS