Afrikaans
Akan
Albanian
Amharic
Arabic
Armenian
Azerbaijani
Basque
Belarusian
Bemba
Bengali
Bihari
Bosnian
Breton
Bulgarian
Cambodian
Catalan
Cebuano
Cherokee
Chichewa
Chinese (Simplified)
Chinese (Traditional)
Corsican
Croatian
Czech
Danish
Dutch
English
Esperanto
Estonian
Ewe
Faroese
Filipino
Finnish
French
Frisian
Ga
Galician
Georgian
German
Greek
Guarani
Gujarati
Haitian Creole
Hausa
Hawaiian
Hebrew
Hindi
Hmong
Hungarian
Icelandic
Igbo
Interlingua
Irish
Italian
Japanese
Javanese
Kannada
Kazakh
Kinyarwanda
Kirundi
Kongo
Korean
Krio (Sierra Leone)
Kurdish
Kurdish (Soranî)
Kyrgyz
Laothian
Latin
Latvian
Lingala
Lithuanian
Lozi
Luganda
Luo
Luxembourgish
Macedonian
Malagasy
Malay
Malayalam
Maltese
Maori
Marathi
Mauritian Creole
Moldavian
Mongolian
Myanmar (Burmese)
Montenegrin
Nepali
Nigerian Pidgin
Northern Sotho
Norwegian
Norwegian (Nynorsk)
Occitan
Oriya
Oromo
Pashto
Persian
Polish
Portuguese (Brazil)
Portuguese (Portugal)
Punjabi
Quechua
Romanian
Romansh
Runyakitara
Russian
Samoan
Scots Gaelic
Serbian
Serbo-Croatian
Sesotho
Setswana
Seychellois Creole
Shona
Sindhi
Sinhalese
Slovak
Slovenian
Somali
Spanish
Spanish (Latin American)
Sundanese
Swahili
Swedish
Tajik
Tamil
Tatar
Telugu
Thai
Tigrinya
Tonga
Tshiluba
Tumbuka
Turkish
Turkmen
Twi
Uighur
Ukrainian
Urdu
Uzbek
Vietnamese
Welsh
Wolof
Xhosa
Yiddish
Yoruba
Zulu
hey guys in this video i'm gonna teach
you everything you need to know to get
started writing code in javascript so
sit back relax and enjoy the show
if you wouldn't mind please leave a like
comment and subscribe one like equals
one prayer for the youtube algorithm
all right let's get started everybody
what the heck is javascript javascript
is a web-based interpreted programming
language that's used to
add interactive behavior to web pages
build web and mobile applications to
create command line tools and for game
development i like games here are some
important notes before we get started
javascript is not the same as java even
though they share the same name both
languages were developed around the same
time now knowing html and css is helpful
but not necessary at least until we near
the end of this series where we begin
working extensively with the dom the
document object model hey if you're
interested i do have a one hour full
course on both of those subjects what
you'll need you'll need a web browser
and a text editor you'll need a web
browser well because javascript runs in
a web browser i recommend using the
latest version of chrome firefox safari
opera whatever please do not use
internet explorer i also recommend a
text editor a few popular text editors
include but are not limited to visual
studio code sublime text replit which is
an online text editor or notepad if you
want to torture yourself in this series
i'll be using google chrome as my web
browser and visual studio code for my
text editor if you would like to
download visual studio code i'll show
you how to download visual studio code
head to this url
code.visualstudio.com
look for this blue drop down menu then
download the latest stable version for
your operating system i'm running
windows i will install this for windows
then your download should start
automatically if it doesn't you can hit
this big blue button
then i'm just going to go ahead and open
this
accept the license agreement yes i
actually did read it that fast
if you would like you can create a
desktop icon
next
install
we might as well go ahead and launch vs
code now
within vs code the first thing i
recommend doing is downloading the live
server extension
let's go over to the left navigation bar
go to extensions
then look up
live
server
then we're gonna click on this
let's pretend that this wasn't already
installed
then click install
what live server does is that every time
that you save your javascript file
it will update your current web browser
right away to reflect any changes it's a
helpful development tool
we're going to create a new folder to
hold all of our files i'm going to go to
open folder
i'm going to create a new folder on my
desktop i'm going to right click go to
new folder i'll name this website click
website select folder
there we go now let's create a new
javascript file go to new file i'll name
this file
index.js be sure to get that extension
js because well that's a javascript file
i'm also going to create an html file
index.html
on a website this would be the landing
page
then a css style sheet which i will name
style dot css
okay we have our three files
index.javascript file our index.html
file
then our css stylesheet
we'll need html skeleton code to work
with so within your html file if you
type exclamation point then hit tab
that will generate some sample text to
be used to create a webpage
we'll want to take care of this early
let's link our css style sheet within
the head tags of my html document
i'm going to create a link tag
link
take the rel attribute set the sql to
style sheet
the next attribute is href
set the sql to
your css stylesheet
style.css
so our stylesheet is now linked to our
html file
then we need to link our javascript file
to our html file
within the body of my html document i'm
going to create a pair of script tags
script that's the opening tag
then forward slash script to close it
within the opening script tag
i will set the source attribute equal to
the name of my javascript file mine is
index.js
then be sure to save everything to save
myself from potential future headaches i
tend to save all three files
to display output from our javascript
file we'll need to open up a web browser
an easy way to do that would be to go to
explore
right click on your html file open with
live server i now have this window to
work with this window is a
representation of my html file when
coding with javascript i like to place
my browser window and vs code right next
to each other kind of like this to
access our console which we can use to
display output i'm going to right click
within my window go to inspect
click on these arrows then go to console
and then just save
any output within my javascript file
will go to my console to display some
output we can type
console.log
then a set of parentheses
typically with programming you end a
statement with a semicolon it's like the
punctuation at the end of a sentence
it's optional to add a semicolon to the
end of a statement but in nearly all
programming languages besides python to
add a statement you need a semicolon i
type it in just as a force of habit but
it would still work regardless now let's
type something let's type some output to
the console window this can be either
within single quotes or double quotes
let's say something i like some food you
like pizza
i do have that live server extension set
up when i save that will update my web
browser within my console we have the
statement that i made i like pizza if i
would like to print another statement i
can again
type
console.log
then within either single quotes or
double quotes i can say something else
it's really
good
i like pizza it's really good you can
also create an alert box by typing
window dot alert
within the parentheses
within a set of quotes what would we
like to say
i
really love pizza
alert will create a pop-up
i really love pizza
there's also comments to create a
comment you use two forward slashes
comments are ignored by the interpreter
this is a
comment
usually comments are used for notes for
yourself or for other developers
you could also write a multi-line
comment by typing forward slash asterisk
wherever you would like your comment to
end you would type asterisk forward
slash again
this
is
a
multi-line
comment all right everybody that is a
quick introduction to javascript and in
the next topic we'll discuss variables
all right everybody that's a quick
introduction to javascript hey if you
enjoyed this video let me know by
smashing that like button leave a random
comment down below and subscribe if
you'd like to become a fellow bro
all right everybody variables so a
variable is a container for storing data
it's a representation of some value
think back to middle school algebra
class where you had to solve an equation
you have to solve for x and x is some
representation of a value it's basically
no different in programming a variable
behaves as if it was the value that it
contains there's two steps to creating a
variable declaration and assignment to
declare a variable we use one of three
keywords either var let or const we'll
discuss const in a future video but for
now we can either use var or let but
using let is best practice due to
something called variable scope but that
won't make too much sense until we reach
the video on functions so for now for
best practice to create a variable let's
use the keyword let we precede the
variable with let and now we need a
unique descriptive name of this variable
so if you're thinking of algebra you
might think of a variable such as maybe
x or y like they are some number but in
programming you want a variable to be
descriptive of what it contains let's
assign a number to this variable maybe
in this example we need to store a
student's age so age would be a
descriptive name for this variable and
that is step one we have declared a
unique variable named age but it doesn't
yet contain a value that's where
assignment comes in that's step two so
let's try and use this variable
console.log
and i'm just going to display age and
then let's see what happens if you
declare a variable but do not assign it
a value it's undefined so we haven't
reached step two yet we've only declared
a variable when you display a variable
make sure it's not within quotes
because then we're literally printing
the word edge instead of the value
contained within age the variable now
step two is assignment we take the
variable name and use the assignment
operator which is an equal sign and set
this equal to some value let's say that
i'm 21 years old not anymore but i like
to think that i still am now when i
display this variable age it displays
the number 21. so age is a variable it
behaves as if it was the value that it
contains now with creating a variable
you can do this in two steps or you can
combine them both together so instead of
taking two lines of code we could
combine them both together like this and
this would do the same thing but there
may be times when you need to declare a
variable and then assign a value later
on like maybe you're accepting some user
input so in that case it would be better
to do that in two steps different
variables have different data types 21
is a number data type we can use this
variable in some arithmetic expressions
maybe it's my birthday and i need to add
one to my age i can easily change that
by setting age equal to age plus one and
my age is now 22 so this is a number
data type another data type is a string
a string is a series of characters let's
create a variable to hold a student's
name
so we will use that let keyword
and i'll create a variable name named
first name then i could assign a value
later or right away i'll do so right
away so i will set first name equal to
then to create a string we can use a set
of quotes either double quotes or single
quotes
and i can add a series of characters so
why don't you enter in your first name
and now i can use this variable and it
contains a series of characters let's
display this within our console
console.log
first
name so this displays bro 21 another
data type is a boolean a boolean is only
one of two values true or false
this time let's say that we have a
boolean variable named
maybe student if a person is currently
enrolled we could set student to equal
true if they're not enrolled or maybe
they graduated this could be false so a
boolean is one of two values true or
false then let's display this within our
console
console
dot log
student
and this displays false or if i was a
student this could be true so these are
three common data types strings which
are a series of characters
numbers
and booleans
as a beginner it's actually really easy
to mix up strings and numbers numbers we
can use with arithmetic expressions
strings we cannot let's use that
previous example of incrementing my age
by one because it's my birthday
age
equals age plus one we can use numbers
in arithmetic expressions see my age is
now 22 but if this was a string i'll put
this within quotes
string
well when we add one to age it's going
to concatenate one to the end of the
string i am not 211 years old it's
treating age as a series of characters
and we're adding an additional character
to age so as a beginner you really have
to pay attention to data types it is
really easy to put things within quotes
when you don't mean to when you display
a variable within the console or the dom
you can display it along with some other
text so along with my first name i'm
going to display hello
hello
then after i finish the string i will
add comma so hello bro with my second
log method i'll print another message
perhaps you
are
age
years old
hello bro you are 21 years old and what
can we do with student um let's say
maybe enrolled
so this will display true if i'm
currently enrolled
or false if i'm no longer a student if
you need to display a variable within
your dom here's one thing that we can do
so within our html document let's create
maybe some paragraph tags i'll create
three
so we need an opening paragraph tag and
a closing paragraph tag
i will set a unique id of p1
copy this paste it two times
the second one will be p2 and the third
will be p3 so within our dom we have
three paragraph tags each with a unique
id if i need to change the inner html of
these paragraph tags i can do so using
this statement
document
dot get
element
by
id
parentheses
and then within a set of quotes i will
list the id of the html tag i would like
to change
let's begin with p1 and then i will
follow the statement with dot
inner
html and set the sequel to
so let's display hello then to display a
variable we will use some string
concatenation so we will use plus
a variable name let's say first name
hello bro okay let's do the same thing
with p2
u
r so when using string concatenation you
do have to pay attention to spaces
within strings
you are age
plus
years old
you are 21 years old and lastly p3
uh let's say
enrolled
colon space
student
enrolled true and then you know you can
change any one of these values
well yeah everybody those are variables
a variable is just a container for
storing data it's a representation of
some value a variable behaves as if it
was the value that it contains there's
two steps declaration and assignment you
can do these both together or separate
and variables have different data types
three that we discussed are strings
which are a series of characters
numbers and booleans which are either
true or false you can display variables
along with text within your console or
you could use string concatenation to
display a variable's value along with
some text in your dom so yeah those are
variables everybody if you would like a
copy of all this code i'll post this in
the comments section down below if you
enjoyed this video let me know by
smashing that like button leave random
comment down below and subscribe if
you'd like to become a fellow bro
hey everybody i have a super quick video
on arithmetic expressions an arithmetic
expression is a combination of operands
and operators operands are values
variables etc operators are well the
addition sign subtraction multiplication
division and modulus which we'll talk
about a little bit later an arithmetic
expression can be evaluated to a value
for example y equals x plus five x and
five would be operands and the addition
sign would be the operator just really
quick let's cover a few maybe we have a
variable named students we're a teacher
and we have a whole class of students to
keep track of i need to add one student
i could take our students variable and
set the sequel to if i need to increment
students by one i can set the sequel to
students currently it's 20
plus one and then let's display this
console.log
students
and this should be 21. so we also have
subtraction
students equals students minus 1
and now we have 19. for multiplication
you use an asterisk maybe we're
combining two classes students equal
students times two
and now there's forty students perhaps
we're dividing a class in half
students divided by two and you use a
forward slash
and now there's ten now this one's a
little bit strange we will discuss
modulus the modulus operator is a
percent sign it gives you the remainder
of any division we have a class of 20
students and we need to divide this
class into groups of three but 20
doesn't divide by three evenly i can
store the remainder within a separate
variable
i'll create a new variable called extra
students
and we will take students
modulus 3
and let's display the extra students
that we have so we have two extra
students but if this was 21 well 21
divides by three evenly so the remainder
is zero we have zero extra students so
that is the modulus operator one popular
use of the modulus operator is that you
can find if a number is even or odd by
taking a value or variable modulus 2. if
extra students is 1 that means we have
an odd number if it's 0 that means we
have an even number so that is the
modulus operator it can be somewhat
tedious to write these long expressions
out so there is a shortcut instead of
saying students equal students plus one
you could just write
students plus equals one this is also
known as an augmented assignment
operator it's kind of like a shortcut so
students is now 21. then we have
students minus equals one students is
19.
students
times equals 2.
there are 40 students now
students
divide equals 2. and there are 10
students with augmented assignment
operators you can use these if you're
reassigning the same variable like i
couldn't say let
extra students
modulus equals three right
and then if we were to display this we
would have a syntax error so augmented
assignment operators are kind of like a
shortcut you can do if you're
reassigning the same variable another
thing to consider with arithmetic
expressions is that there's operator
precedence maybe we have this equation
let result equals 1 plus 2
times
three plus four
and then i'm just going to display
whatever the result is
so the result is 15. the order in which
you solve this is that you begin at the
left and work your way towards the right
you solve anything within parentheses
first then exponents then multiplication
and division then lastly addition and
subtraction starting on the left and
working our way towards the right we
would solve anything with parentheses
first three plus four is seven then we
solve any exponents there aren't any
multiplication and division we can
either resolve one plus two or two times
seven so multiplication has precedence
over addition we would solve this first
then it's just 1 plus 14 which is 15.
now by adding a set of parentheses you
can force operator precedence this time
i would like to resolve 1 plus 2 first
and now we have a new result the result
is 21. so yeah that's a super quick
video on arithmetic expressions it's a
little dull but it's kind of necessary
to cover hey if this video helped you
out help me out by smashing that like
button leave a random comment down below
and subscribe if you'd like to become a
fellow bro
hey everyone in this video i'm going to
show you how we can accept some user
input in javascript i'll demonstrate two
ways the easy way with a simple window
prompt and the difficult way with an
html text box let's begin with the easy
way i'm going to create a variable named
username and the user will type in a
name for themselves let username
equals and to create a window prompt we
type window
dot
prompt parentheses and within the
parentheses we can add a message
what's your name after a user types in
some user input we will assign whatever
they type into a variable so i'm going
to display this
console.log user name what's your name
type in your name press ok and this will
display the value that you typed in the
difficult way although it's more
practical is to use some html elements
within our html file let's create a
prompt a label
enter your name and then maybe i'll add
a line break
and an input box
input
this is a self-closing tag
a line break with my input tag let's set
the type
equal to text it's a text box and i'll
give this an id of
my
text okay so save we have our label and
a text box let's create a submit button
we'll need a pair of button tags
type
will be button and the id will be my
button
you can add some text to the button
between the button tags just write
something submit okay make sure to save
your html document then we'll head back
to our javascript file what i'm about to
show you is a little advanced but you
can always just copy this and save it
for the future after clicking our submit
button whatever text is within our text
box we'll assign it to a variable we'll
type document
dot
get
element
by id
then type my
button follow this with dot
on
click
and we will set this equal to function
parenthesis then a set of curly braces
at the top of my program i'm going to
declare my variable but not yet assign
it and within my function the set of
parentheses i will take username and set
this equal to
document
dot get
element
by
id
parentheses then within quotes
my text that's the id of the text box
dot value
so when we click on this button take
whatever text is within our text box and
assign it to user name then afterwards
let's display whatever our username is
within our console
or if you want we can change maybe this
label console.log
user name type in your first and last
name
press submit
and this will display your name let's
change this label but i'm going to give
this label a unique id
id equals my label so save go back to
your javascript file i'm going to edit
the inner html of this label document
dot get
element by id
my
label
dot inner html
set the sequel to user name okay so
again type in your first and last name
press submit and this should change that
label maybe i'll add
hello
plus username this time
hello bro code so yeah those are two
different ways to accept user input you
can go the easy way with a simple window
prompt or you can take the difficult
approach with an html text box although
it's more practical but it's above our
current level of understanding at this
point in time so yeah those are two ways
to accept user input in javascript if
this video helped you out you can help
me out by smashing that like button
leave random comments down below and
subscribe if you'd like to become a
fellow bro
hey guys in this video i'm going to
explain type conversion type conversion
is the ability to change the data type
of a value to another and i'll explain
how to do this with strings numbers and
booleans here's one issue when accepting
some user input let's say we have
variable age and i'll create a window
prompt to ask a user to enter in their
age how old are you once we accept some
user input i'm going to increment age by
one because let's say it's the user's
birthday then let's display the user's
age
console.log
happy birthday
u
r
our age variable
years
old how old are you let's say that i'm
21 i press ok happy birthday you are 211
years old when we accept user input it's
of a string data type we can't normally
use strings for any sort of arithmetic
expressions what i intended was to add
our edge 21 plus 1. that would give me
22. if you add a number to a string you
just concatenate that number to the end
of the string because a string is just a
series of characters if i need to take
some user input and use it with some
sort of arithmetic expression i'll want
to convert that string to a number and
one way i can do that is to use the
number constructor so i'm going to set
age
equal to then type number
make sure it's capital
parentheses and then pass in age this
will convert a string to a number how
old are you 21 press ok happy birthday
you are now 22 years old if you ever
need to get the data type of a variable
there is a type of keyword
let's display it type
of
age so before we convert our age
variable it's a string then let's
display the data type of age after we
convert it
at first it's a string we convert it and
now it's a number and then we can use it
in arithmetic expressions here's a few
other examples we have three variables x
y and z
i'm going to set x to equal and we will
use the number constructor and we will
convert the string 3.14 into a number
and then i will display
whatever x is as well as the data type
type of x remember we're converting a
string into a number
so 3.14 is now a number let's convert a
number into a string y equals and we can
use the string constructor
and we will convert the number 3.14 into
a string
console.log
y
and type of y 3.14 is now a string
and to convert something to a boolean
you can use the boolean constructor
so if you pass in an empty string just a
set of quotes this will give you false
console.log
variable z and the type of z
so converting an empty string to a
boolean will result in false and this is
of the boolean data type but if you type
in anything else it will give you true
so maybe
i try and convert the word pizza when
you convert a string to a boolean that's
not empty this will give you true if
it's an empty string just a set of
quotes it results in false this would be
useful if you need to accept some user
input or user types in their name if
they skip that step and using an if
statement which we'll talk about later
you can check to see if a user typed in
something or not based on if that
boolean is true or false but we'll get
into that later so yeah those are a few
basic ways of type conversion you can
change the data type of one value to
another if you need to get the data type
of a variable just precede that variable
with the type of keyword and to convert
a value or variable into another data
type you can surround that value or
variable with a given constructor the
number constructor the string
constructor or the boolean constructor
oh one fun fact too if you try and
convert something into a number that
normally shouldn't be a number
like the word pizza well then this will
result in n-a-n not a number that's just
a fun fact so yeah that is type
conversion in javascript if this video
helped you out you can help me out by
smashing that like button leave a random
comment down below and subscribe if
you'd like to become a fellow bro
hey everybody in this video i'm going to
explain constants a constant is a
variable that can't be changed it adds
some security to our code to declare a
constant you use the const keyword in
place of var or let in this example
we're going to create a sample program
to calculate the circumference of a
circle which has this formula
circumference equals 2 times pi times
radius let's declare all of the
variables that we'll need we're going to
write this program without constants and
then later with constants and i can show
you their usefulness we'll create three
variables let pi
equal
3.14159 just the first few digits of pi
let radius and let
circumference we're going to accept some
user input we will assign radius equal
to
window
dot prompt
enter the radius
of a circle
then when we accept user input it's a
string we'll need to convert that to a
number radius equals
and use some type conversion and convert
our radius into a number to calculate
the circumference of a circle we will
set circumference equal to and follow
that formula 2 times pi
times radius and with the radius the
user will type that in
at the end of our program we will
display our result
the circumference
is
circumference
let's run this
enter the radius of a circle if the
radius is 9 i press ok the circumference
is 56.54 now here's why constants are
useful let's say that somebody changes
our code
pi now equals
420 69. now when we run this program and
we type in 9 for the radius
while the circumference is now
7572 we can prevent a variable from
being changed if we assign it as a
constant in place of let use the const
keyword and our variable pi is now a
constant and a common naming convention
for constants is that you make all of
the letters uppercase it's not necessary
but it's good practice then we are going
to change that here too
enter the radius of a circle i'll type 9
the same as before
and we encountered a type error
assignment to constant variable so once
we declare a constant we can't change it
so if i were to get rid of this line run
this again 9 the circumference is 56.54
you'll want to use constants as often as
possible if you have a variable that you
know will not be changed later we're not
going to assign radius and circumference
as constants because we'll need to
update them later in our program so yeah
those are constants it's basically just
a variable that can't be changed it adds
a little bit of data security if you
found this video helpful you can help me
out by smashing that like button leave a
random comment down below and subscribe
if you'd like to become a fellow bro
all right everybody let's talk about
javascript math math is an intrinsic
object that provides basic mathematics
functionality and constants there's a
lot of functions i think that you would
find useful in this example we have a
variable x and x equals 3.14 feel free
to choose any number that you want maybe
i need to round this variable well
there's a built-in function of math that
can do that for us i could just type x
equals then type math
dot
and then i have access to a bunch of
different functions i would like to
round x so add a set of parentheses and
pass in a value or a variable that you
would like to round and then if i was to
display the value of x with console.log
this would display my value or variable
rounded whatever's within the set of
parentheses of this function and x
rounded is 3. let's cover a few more
the floor function will always round a
number down if this variable was 3.99
the floor function will always round
down x is still three if you need to
round up there is the ceiling function
which is shortened to c e i l
if x is 3.14
seal will round up
x is now four you can raise a value to a
given power
x equals math dot pow in the parentheses
you'll give a base and an exponent each
is separated with a comma
x to the power of 2 is 9.8
x to the power of 3
is 30.9 their square root x equals math
dot square root
sqrt for short
the square root of x
is 1.77
to find an absolute value you can use
the absolute value function x equals
math.abs the absolute value is the
distance away from zero if x was
negative three point one four the
distance away from zero would result in
a positive number positive three point
one four this time we have a couple
variables and we need to find the
maximum and the minimum we'll create two
more variables let y equal
i don't know what about five
let z
equal nine i'll declare a maximum and a
minimum
let maximum
lat minimum
i will assign maximum equal to
math.max function
and pass in x y and z
this will return the maximum and assign
it
so the maximum between x y and z
is nine then there's also minimum
so minimum equals math.min
the minimum between x y and z is x 3.14
there's also some built-in constants too
with x i assigned 3.14 i would like to
assign pi with more digits well there is
a built-in constant of math
x equals math.pi and when i display x x
is three point one four one five nine
two six five three five eight nine seven
nine three so math is an intrinsic
object that provides basic mathematics
functionality and constants there's a
lot more functions and constants than
what we covered but here's a few of the
basics so yeah that is javascript math
if you found this video helpful you can
help me out by smashing that like button
leave a random comment down below and
subscribe if you'd like to become a
fellow bro
hey welcome back everybody in this video
we're going to create a practice program
to find the hypotenuse of a right angled
triangle and the formula to solve that
is c equals the square root of a squared
plus b squared we'll create two
variations of this program first we'll
accept some user input via some prompts
then later on we'll adjust this program
and accept some user input through some
html text boxes let's begin let's
declare three variables each for side a
b and c
let a
let b
and let's see we'll accept some user
input for sides a and b
a equals window dot prompt
and the prompt will be enter side a
when we accept user input it's a string
we'll need to convert that to a number a
equals number pass in a
let's do the same thing for side b
let's copy and paste what we have but
change a to b
and the formula to calculate the
hypotenuse goes a little something like
this
c
equals we'll need to square sides a and
b and add them together we can use
javascript math dot
power function
a to the power of two
plus
copy this paste it
b to the power of two then we need to
square all of this and that equals c
so in the next step we could set c equal
to
math dot square root
and pass in c
if you would like to do this in less
steps you could copy all of this
cut this line
and paste what we just copied so this
would only take one line of code then at
the end we will display side c
side c
c okay let's run this
enter side a
a is three
b is four side c equals five okay now
let's make a more advanced version of
this program we'll accept some user
input via some html text boxes so let's
head to our html file and add a couple
elements we'll create three labels
label the first will have an id
equal to maybe a
label then close this tag and i'll add a
line break
then i'll copy this paste it
will have a b label and a c label i'll
change the text to side a colon
side b
and side c
okay and this is what we have so far
i'll add two text boxes right underneath
a and b and then a button later we'll
create a self-closing input tag
then i'll add a line break at the end
before i forget
set the type
equal to
text because it's a text box
and i will give this a unique id of a
text box
okay let's copy this
then underneath b label and give this
text box an id of b text box okay this
is what we have so far
then i'll create a button underneath
this second text box so right here
so we'll create a pair of button tags
and a line break i'll set the type equal
to button
and an id of what about submit
button then i should probably add some
text
so between the button tags
submit so let's save then heading back
to our javascript file this is what we
have to type this will be a little bit
advanced for us because we haven't
discussed functions yet when we click on
this button we need to do something to
select this button we will type document
dot
get
element by
id within the parentheses we will list a
unique id
i would like the id of my submit button
then follow this with dot
on click when we click on this button we
would like to do something we would like
to perform a function function
parentheses curly braces within the
curly braces we will execute some code
and actually we can copy a lot of what
we have here so let's copy our previous
code and paste it but we need to change
a couple things around we would not like
window prompts so let's change this line
to a
equals
document
dot get
element by id
and i would like to get the value of
this text box which has a unique id of a
text box
follow this with dot value we're taking
the value of this text box and assigning
it to variable a when we accept user
input it's normally a string we're going
to convert it to a number
let's do the same thing with b so copy
that line paste it
change a to b here and here as well
then convert it to a number
we can keep this line of code the logic
is still the same and lastly we can
update this label i'm going to change
this around real quick
i don't want to display anything but
we'll still keep the label i'm going to
change the inner html of this label c
label
document dot get
element
by
id we are selecting
c label and i'm going to change the
inner html
and set this equal to
side c
colon space
plus c
okay so make sure you save both your
html document and your javascript file
and let's run this
so side a is three side b is four let's
press submit and side c is five so yeah
everybody that is a practice program to
find the hypotenuse of a right angled
triangle if you would like a copy of all
this code i'll post this in the comments
section down below if this video helped
you out feel free to help me out by
smashing that like button leave random
comment down below and subscribe if
you'd like to become a fellow bro hey
yeah everybody in this video we're going
to create a simple counter program using
javascript so sit back relax and enjoy
the show
let's begin everybody so head to your
html document we will create one label
and three buttons
label use a closing tag add a line break
the id of this label will be count label
count
label
the text will set to be zero to begin
with
we'll need three buttons
button
close it the first button will have an
id of decrease button
decrease
button
and the text will be decrease
okay let's copy this button paste it two
additional times
the second button will be a reset button
text reset and the third button will be
increase
increase button
increase
i would like to change the font size as
well as the positioning of my count
label i'll link an external css style
sheet
so i will create a new file
style dot css
within the head of my html document i
need to link the style sheet use the
link tag
we'll set the relationship attribute set
the sequel to style sheet and set the
href attribute to the name of your style
sheet style dot css we'll need this
count label id
i would like to change the css
properties of my count label so add a
set of curly braces we'll center this
label and increase the font size
display
block
text align
center font size 50 should be fine 50
pixels
save your style sheet
save your html file
and head to your javascript file we'll
declare and assign a count variable let
count equal zero when we click on one of
these three buttons we would like to
perform some function
let's select the decrease button
document.getelementbyid
decrease
button
dot on
click
let me close out of this equals a
function parenthesis curly braces
so copy this
paste it two additional times
we have reset button
and increase button when i select the
decrease button i will take our count
variable minus equals
one and we will change the inner html of
this label
document.getelementbyid
count
label
dot inner
html set the sql to our count
copy these two lines of code
paste it within each of these functions
for the reset button we will set count
to equal zero and the increase button
count plus equals one let's save
when i click the increase button it
increases my label decrease decreases my
label
and the reset button resets my label so
yeah everybody that is a simple counter
program in javascript i'll post the code
for this program in the comment section
down below hey if this video helped you
out help me out by smashing that like
button leave random comments down below
and subscribe if you'd like to become a
fellow bro
hey everybody just so you know that this
topic is completely optional if you're
ever interested in making any sort of
games with javascript then this video is
a must let's begin to create a random
number let's declare a variable and we
will set the sequel to type math dot and
there is a random method then let's
display whatever x is console.log
x the random method of math will
generate a random decimal number between
0 and 1. but we can actually use that
maybe we're rolling a dice how do i
generate a random number between one and
six so to do this i'm going to take math
dot random and multiply this by six
this gives us a random decimal number
between zero and five technically to
truncate the decimal portion we can
round down i will surround this with a
set of parenthesis
and we will use math dot floor
and this will round down this generates
a random number between 0 and five
because computers always start with zero
if i need a one through six i can add an
offset i'll just add plus one this
generates a random number between one
and six as if we were rolling a dice now
i like to play a lot of dungeons and
dragons and there's different sized dice
there's eight sided dice 10 sided dice
20 sided dice etc if i'm simulating
rolling a 20-sided dice i would multiply
math.random method times 20 plus 1. so
this generates a random number between 1
and 20. maybe i need to roll a couple
dice i'll copy this line of code
we'll create variables y and z
then display them
console.log x y and z this would be as
if we're rolling three dice we get three
random numbers between one and six just
for fun let's create some labels and
generate some random numbers within our
dom so within the body of my html
document i'll create a couple labels
label id this will be x label then close
this label add a line break i'll add two
more
y label
and z label then i'll create a button
close the tag
type equals button
id equals roll
button
then i will add some text to the button
roll make sure to save heading back to
our javascript file
when we click on this button we will
execute a function
so we need to select our button document
dot get
element by id the name of our button is
roll button
dot on click
equals set the sql to a function
parentheses curly
braces let's copy these lines of code
we don't need to declare these again
let's get rid of this text
we'll declare the variables at the top
so after rolling three random numbers
between one and six i will update our
labels
x label y label and z label we need to
select each of these labels
document.getelementbyid
label dot inner
html set the sql to
x
then do the same thing with y and z
make sure to change the labels to y
label
equals y
z label equals z
so make sure to save both of your files
oh i'm forgetting z there okay
so now when i press this button we will
roll three dice and we end up with three
random numbers between one and six
so yeah that's how to generate some
random numbers in javascript if this
video helped you out you can help me out
by smashing that like button leave a
random comment down below and subscribe
if you'd like to become a fellow bro
hey welcome back everybody so let's talk
about some useful string properties and
methods i have a variable user name and
assign this whatever your first and last
name is if we type this variable and add
a dot we have access to a bunch of
different properties and methods of this
string one of which is the length
property this will give us the length of
a string how many characters are within
the string we could assign this to a
variable name length equal username dot
length or we could display it i'm going
to display this with a console.log
statement
console.log username.length the length
of my name is eight characters but yours
will likely be something different let's
cover a few more we can get the
character of a string at a given index
type the name of the string variable dot
char
at add a set of parentheses whatever
character you would like to return you
will add the index of that character
computers always start with zero so the
first character in the string would have
an index of zero so maybe i would like
to assign this to a variable let
first letter equal username dot char at
index zero or you know i could display
it with console.log
and then just add this variable and
method within the parentheses the
character at index 0 of my string is b
then index 1 would be r
2
would be o that is the char at method
you can find the index of the first
occurrence of a letter type the variable
name user name dot
index
of then pass in a character you would
like to find the first index of how
about o and then i will display this
with
console.log the index of the first
occurrence of the character o is at
index 2
0 1 2. there's also last index of
last
index of and we'll keep that as o
the last occurrence of o
has an index of five
zero one two
three four five we can also trim spaces
before and after a string
so i'm going to display this as it is
and i'll turn these into comments
okay console.log username
and we have all the space that we would
like to get rid of
so to do that we will reassign username
with user name dot trim
this gets rid of any empty spaces before
and after any other characters we could
make our string all uppercase username
equals username dot to uppercase
and my name is all uppercase there is
also lowercase
to
lowercase and all the characters are now
lowercase okay here's another replace
all but this time let's create a phone
number
let phone number
equal then within a set of quotes make
up some phone number with dashes
123-456-7890
okay using the replace all method i can
replace all given characters with
another one so phone number
equals
phone number
dot replace
all
so this has two arguments the character
we would like to replace
add a comma
the second character is what we'll be
replacing all of these dashes with how
about a forward slash and we will
display phone number
so here's my phone number
if you would like to eliminate these
dashes then just don't type in anything
and those dashes are gone so yeah those
are a few useful string properties and
methods if you have a string variable
add a dot and you have access to a bunch
of different properties and methods a
lot of which we didn't cover but these
are just a few of the basics so yeah
those are some useful string properties
and methods if this video helped you out
you can help me out by smashing that
like button leave a random comment down
below and subscribe if you'd like to
become a fellow bro
sup everybody let's talk about the slice
method the slice method extracts a
section of a string and returns it as a
new string without modifying the
original string how is this useful maybe
we have a variable full name set the
sequel to whatever your full name is
what i would like to do is extract
certain portions of this full name to
create a first name and a last name
without changing the full name i'll
declare two additional variables but not
assign them yet
first name as well as last name
i can create an entirely new string from
an existing string via the slice method
let's extract this last name and assign
it to this last name variable last name
equals
then type
the original string full name dot slice
within the parentheses there's up to two
values that we can add the starting
index and the ending index if i need my
last name that would be at index 0 1 2 3
4. so 4 would be the last value if you
don't add a second value it's assumed to
copy everything until the end of the
string i would like the entire rest of
the string after index 4 and then we'll
assign it to this new variable last name
let's display it to test it
console.log
last name and this should display my
last name yep what if i need the first
name you can place up to two indices so
first name equals
type the original string full name
dot slice the starting index will be
zero and the ending index will be in my
example 0 1 2 3. this doesn't include
the last character all right then let's
display my first name
and there's my first name even though
this does work it wouldn't be realistic
to do this by hand manually every time
we would like to create a first name and
a last name from a full name right so
why don't we use the string index of
method to search for any spaces and
return it index so let's try this again
let's begin with last name
last name equals full name
dot slice
and we only need one index we need the
starting position of where to begin so
we would like to begin where there's any
spaces plus one so we need to begin at
this character in my example but it
might be different depending on what
your full name is so i would like to
search for any spaces and i can do that
by taking my string full name dot and
use the index of operator and we will
search for the index of any spaces
so let me hide my first name here
oh pay attention to capitalization there
however i need to get rid of the space
because the first value is inclusive so
i will add plus one
everything after the first space
slice it and create a new string so
there's my last name then let's do this
with our first name
first
name
equals
full name
dot slice
then we'll need two indices
zero the beginning
and we will end wherever there's a space
so there's my first name and my last
name let's try a different name just to
be sure that it's working right how
about snoop dogg
yep snoop dogg all right everybody that
is the slice method it extracts a
section of a string and returns it as a
new string without modifying the
original string in our example we
created a first name and a last name
from a user's full name and that is the
string method if you found this video
helpful you can help me out by smashing
that like button leave random comment
down below and subscribe if you'd like
to become a fellow bro
hey everybody we're talking about method
chaining method chaining is a
programming technique where you call one
method after another in one continuous
line of code here's an example of where
it could be useful let's say we have a
username
and assign this whatever your first name
is but i'm going to make this all
lowercase in this example what i would
like to do is take the first character
of the string and make it uppercase
without using method chaining we could
do something like this
we'll create a temporary variable to
store a letter and i will return the
first letter in the string
user name dot and i will use the char at
method
and the first letter has an index of
zero letter is now b but now i would
like to make it uppercase i will need to
reassign my letter variable equals
letter dot
to
uppercase
and then we can display this
console.log letter this should display
the letter capital b to write this code
a little more elegantly we could use
method chaining after calling one method
we can call subsequent methods i'll
eliminate this line and follow the char
at method with
two
uppercase
then add that set of parentheses this
single line of code will do the exact
same thing and it's easier to read and
understand you can follow one method
call it with another if i would like to
invoke another method i don't know like
trim i could just add that to the end
you have the capability of calling one
method after another in one continuous
line of code it makes your code cleaner
and more readable so yeah that's method
chaining if you found this video helpful
feel free to help me out by smashing
that like button leave a random comment
down below and subscribe if you'd like
to become a fellow bro
sup guys in this video i'm going to
explain if statements an if statement is
a basic form of decision making if a
condition is true then we do something
we execute some subset of code if not
then we don't do it in this example i
have variable age and i'll set the
sequel to maybe 21. if somebody's age is
over 18 i would like to display a
message that says you're an adult if
they're under 18 it doesn't display
anything so to create an if statement
type if a set of parentheses for a
condition and then a set of curly braces
if some condition that we check is true
we will execute any code within these
curly braces i would like to check to
see if age is greater than or equal to
18. if it is then we'll execute whatever
code is within these curly braces and
i'll display a message
you are an adult
my current age is 21 the if statement
checks this condition
it's true so we do this if it's not true
like i'm 12 it will skip over anything
within these curly braces entirely this
gives us a lot of options if statements
are a basic form of decision making now
in place of just skipping this code
entirely we could do something else if
you would like to take a different
course of action you could add an else
statement else let's print a different
message
you are a child
now when i run the same code we will
check this if statement if it's false
then we skip everything within the curly
braces if there's an else statement we
instead do this
you are a child if there's any other
conditions you would like to check
before reaching the else statement you
can add an else if statement
else
if maybe i'll check to see if age is
less than zero and we'll display
something else
console.log
you haven't
been born yet
currently my age is 12
this condition isn't true we skip it
this condition isn't true we skip it and
we move on to the else statement kind of
like a last resort now if this condition
is true
age is less than zero maybe i'm negative
five years old well then
this statement is false but this one is
true and you can add as many else if
statements as you want now check this
out let's check to see if somebody is a
senior if they're 65 or older
else if age is greater than or equal to
65.
you are a senior
citizen
so let's change our age to 65.
now check this out
so it displays the message you are an
adult still that's because this if
statement is still true our age is
greater than or equal to 18. so the
order of your if statements does matter
if i would like to check this condition
first i should probably move this to the
top and make it an if statement so let's
make this statement if and the second
one else if
there
you are a senior citizen if you need to
check a boolean value that's actually
really easy to do with if statements
so i'm going to turn all of these into
comments and here's another example
maybe we have a variable
online if somebody's online
this is true if they're offline this is
false if you need to check a boolean
value using an if statement you could
just place the boolean variable within
here if online so if a user is online
let's display
you are online
else
you are offline
okay online is set to true you are
online if this was false
you are offline so yeah everybody those
are if statements it's a basic form of
decision making
if a condition is true then do something
if not then don't do it so yeah those
are if statements in javascript hey if
this video helped you out you can help
me out by smashing that like button
leave a random comment down below and
subscribe if you'd like to become a
fellow bro
hey guys in this video i'm going to
explain the checked property of check
boxes and radio buttons all the checked
property does is let us know if a check
box or a radio button is selected
accessing the checked property will give
us a boolean value true or false heading
to our html document let's create a
checkbox
input
the type will equal
check box
give this check box a unique id
my check box is good
there's our check box but we should
probably add a label because we don't
know what it's for
label for
equals
copy your id
paste it
close the label
let's add some text
perhaps this is a subscribe button
we can check either the check box itself
or click on the label to check that
then we will add a button this will be a
submit button
button id equals my button
let's close it add some text
submit
i think i'll add this on a new line i'll
add a line break
and that should be good for now
heading to our javascript file when we
click on this button we would like to do
something
first we will select this button by
typing document dot
get
element
by id
the id of that button was
my button
set the on click event attribute equal
to a function
when we click on this button what would
we like to do i would like to see if
this checkbox is checked or not
i'll use an if else statement
if that checkbox is checked we'll do
something if not we'll do something else
within the parentheses we'll select this
checkbox
document dot
get
element by id
the id of that checkbox was
my checkbox
follow this with the checked property
we can check to see if this is true by
using the comparison operator which is
two equal signs true
this is optional but you don't
necessarily need to write that
if document.getelementbyid
my checkbox is checked what are we going
to do
let's let the user know that they're
subscribed
console.log
you are subscribed
else if this checkbox is not checked
then you are
not subscribed
okay let's try it i'll just press submit
you are not subscribed i'll reload the
page check that checkbox again press
submit you are subscribed
now this can be a little difficult to
read what i like to do is store elements
within a variable for readability i'm
going to copy this section
then assign it to a variable maybe a
constant const my
checkbox
equals
by document.getelementbyid my check box
we can refer to this element by this
variable name
if my check box is checked
this would do the same thing i find it
easier to read
okay level two let's do this again but
with radio buttons
heading back to our html file we'll
create three radio buttons
input
type equals radio
these will all have the same name
perhaps this will be card for payment
what kind of card are you going to use
the id of the first button will be a
visa button
if they're paying with a visa card
okay let's copy this paste it two times
a mastercard button
then what about paypal button
i'm gonna add a line break at the end
then let's add some labels
label close it
the four attribute will be the same as
the
id the text will be visa
then mastercard
master card
lastly paypal
paypal
okay we have our three payment options
since these three radio buttons are
within the same group we can only select
one be sure to save everything heading
back to our javascript file let's get
all of the buttons and store them within
a variable
const
visa button
equals document.getelementbyid
the id was visa button
then we have
mastercard
button
then paypal button
okay we have our buttons
using if else statements we'll check to
see which of these buttons is selected
first we'll check our visa button if
visa button dot checked
then we'll display a message
you are paying
with a visa
else if
mastercard button is checked you are
paying with a
mastercard
else if
paypal button is checked
you are paying with
paypal
else no radio button must be selected
you must select a payment type
let's try this
i'll select visa press submit you are
paying with the visa
mastercard submit you are paying with
the mastercard paypal submit
you are paying with paypal i'll refresh
the page not select anything that will
execute the else statement
you must select a payment type so yeah
everybody that is the checked property
they're typically found within check
boxes and radio buttons you can access
this property by following a check box
or a radio button with dot checked this
value will be true or false if it's true
you can do something if not you can do
something else so yeah that's the
checked property everybody if you would
like a copy of all this code i'll post
all of this in the comment section down
below and well yeah that's the checked
property in javascript
hey guys in this video i'm going to
explain switches a switch is a statement
that examines a value against many case
clauses it's more efficient than using
many else if statements in this example
i have a letter grade what i would like
to do is examine this letter grade if
our grade equals a then we will display
you did great else if grade equals b you
did good c you did okay d
you passed barely f you failed and there
is an else statement if something is not
one of these letter grades maybe the
word pizza pizza is not a letter grade
it's not normally good practice to use a
whole bunch of else if statements if you
find that you're using a lot of else if
statements it may be better to instead
create a switch let's write the same
program but use a switch instead to
create a switch we type switch a set of
parentheses and then a set of curly
braces within the parentheses we're
going to examine a value or variable i'm
going to examine our grade and we will
compare our grade against many case
clauses
and see if there's a match to create a
case clause you type case and then some
value that you would like to examine to
see if there's a match
case a we're checking to see if grade is
equal to a if they match then we do
something so add a colon then type
whatever you would like to do
console.log
you did great then at the end of your
case make sure to add the word break
this is our case if grade is equal to a
so what if grade is equal to b
case
b
you did
good case c
you did
okay
case d
you
passed
barely
case f
you failed now if there's no matching
cases you can add a default clause
default
let's display
grade
is not a letter grade
this will do the same thing except it's
more efficient our grade is a you did
great
b you did good
c you did okay d you passed barely
f you failed
let's make up something pizza
pizza is not a letter grade so that's a
switch statement now with your cases you
could put a condition instead of letter
grades what if we were working with
number grades like 95 is an a so another
way of writing the switch is that if
we're checking conditions we could pass
true within the switch we'll examine
true against some matching conditions
case
grade
is greater than or equal to 90 so that
would be an a
case grade is greater than or equal to
80. that would be a b grade is greater
than or equal to 70 that's a c grade is
greater than or equal to 60 that's a d
grade is less than 60 so that would be
an f now this way you can compare a
value or variable against many matching
conditions so that would be another way
of writing a switch so yeah everybody
that is a switch statement it examines a
value for a matching case against many
case clauses it's more efficient than
using many else if statements using an
elsif statement isn't bad but you don't
want like you know 10 of them so yeah
that's a switch everybody if you found
this video helpful you can help me out
by smashing that like button leave
random comments down below and subscribe
if you'd like to become a fellow bro
well alright then everybody we are on
the and as well as or logical operators
they give us the ability to check more
than one condition concurrently how is
this useful here's an example
we have a variable temp temp short for
temperature i would like to check to see
if my temperature falls within a certain
range using an if statement is 15
degrees celsius that's not a bad
temperature within the condition of an
if statement i would like to check if my
temperature is greater than 0 and less
than 30 so within the
parentheses let's check if temp is
greater than zero
and to check another condition
concurrently we can use
and which is two ampersands
and i would like to check if temp is
less than 30.
if my temperature falls within this
range between 0 and 30 then we execute
whatever's within this if statement
let's display
the weather
is good
else
the weather is bad
our temp is currently 15 15 degrees
celsius
the weather is good this condition is
true
and this condition is true with the and
logical operator both conditions must be
true in order for us to execute this if
statement if one of them is false then
we don't
what if our temperature was negative 10
this condition is false but this one is
true
and using the and logical operator both
conditions must be true which they're
not in this example so we skip this if
statement and execute the else statement
the weather is bad maybe our temperature
is 50 degrees celsius this time this
condition is true but this one is false
therefore we skip this if statement the
weather is bad that's one use of the and
logical operator you can check more than
one condition and it's useful if you
need to find if something is within a
certain range like a range of
temperatures let's talk about the or
logical operator using the or logical
operator either condition can be true in
order to execute this if statement
so let's rewrite this this time let's
check to see if temp is less than or
equal to zero
or
which is represented by two vertical
bars
or temp
is greater than or equal to 30. if at
least one of these conditions is true
then we execute this if statement but
the weather will be bad else the weather
is good our temperature is currently 50
the weather is bad what if our
temperature was negative 10. the weather
is still bad how about 15
well the weather is good
using the or logical operator either one
of these conditions can be true if one
is false and the other is true that's
completely fine now you can add more
than one logical operator let's head
back to our previous example i'm just
going to undo everything
let's throw in another variable let
sunny sunny will be a boolean value
sunny will equal true if it's sunny
outside if it's cloudy outside well then
sunny will be false so in order for the
weather to be good the temperature needs
to be above zero
and under 30
and sunny needs to be equal to true
but if you're working with a boolean
value you don't need to say equals true
you can just add that boolean variable
so our temperature is 15
and sunny is true all three of these
conditions are true therefore the
weather is good if the temperature is 15
but it's not sunny outside that's false
well then the weather is bad you can
link more than one condition using these
logical operators so yeah that's the and
as well as the or logical operators you
can check more than one condition
concurrently hey if this video helped
you out you can help me out by smashing
that like button leave a random comment
down below and subscribe if you'd like
to become a fellow bro
hey everybody let's talk about the nut
logical operator which is represented by
an exclamation point within a condition
it's typically used to reverse a
condition's boolean value a condition
that is true that's preceded with the
not logical operator becomes false if
it's false originally it becomes true it
gives us a few additional ways to write
code here's an example we have variable
temperature temp for short and i'll set
this to 15 degrees celsius if i would
like to check to see if it's warm or
cold outside normally i could write an
if else statement
if temp is greater than zero then it's
warm outside
it's warm outside
else it's cold outside
currently our temperature is 15 degrees
celsius it's warm outside if it was
negative 15 it's cold outside using the
not logical operator we can write this
code a different way if we choose to we
can check to see if the temperature is
not greater than zero so to do so we
will surround this condition with a set
of parentheses and precede this
condition with the not logical operator
an exclamation point in plain english
we're checking to see if our temperature
is not greater than zero so that would
mean it's cold outside right
else it's warm outside
so taking our same temp of negative 15
it's cold outside
if it's 15 it's warm outside now let's
do this with a boolean variable
let
sunny equal true
if
with a boolean variable if you would
like to place it within a condition all
you have to do to check if it's true is
just write the name of the boolean
variable if sunny
so you don't necessarily need if sunny
equals true
if sunny
if sunny is true
then it's sunny outside else
it's cloudy outside
currently sunny is true
therefore it's sunny outside if i would
like to check if it's not sunny outside
i can precede this boolean variable with
the not logical operator and you don't
necessarily need to surround it with
those parentheses if it's a boolean
variable if it's not sunny well then
it's cloudy outside else it's sunny
outside sunny is true it's sunny outside
if it's false it's cloudy outside so by
using the not logical operator it gives
us a few additional ways in which we
could write code more versatility is a
good thing so yeah that's the not
logical operator it's typically used to
reverse a condition's boolean value if a
condition is true it's now false if it's
originally false it's now true and that
is the not logical operator hey if you
found this video helpful be sure to
smash that like button leave a random
comment down below and subscribe if
you'd like to become a fellow bro
well sup everybody i have to explain
what a while loop is a while loop is
like an if statement except it repeats
some code while some condition is true
it could potentially repeat an infinite
amount of times here's an example let's
say we need to get some user input we
would like a user to type in their
username let's create a variable user
name and i will set the sequel to just
an empty string for this example to
create a while loop we type while set a
parenthesis set of curly braces we will
continue this code while the condition
remains true let's check to see if our
username is equal to an empty string
that means the user didn't type in
anything so within the curly braces
let's create a window prompt username
equals window dot prompt
enter your name then at the end let's
display
console.log
hello
user name and to your name i'm just
going to press ok when we reach the end
of a while loop we check the condition
again if it's still true we repeat this
code for another iteration and then
check again i'm hitting ok but i can't
exit this window prompt until i enter in
my name i'll type in my first name hit
enter hello bro my username although in
this example i'm hitting ok but you
could hit cancel to exit let's add
another condition
or
username is equal to null that means
there's no value to exit i simply can't
press ok
or cancel i need to type in something
because we're stuck in a while loop i'll
type in my first name again and then we
can exit once i typed in something for
my username both of these conditions
were no longer true then we could escape
the while loop and continue on with the
rest of the program now when you create
a while loop you should write some sort
of way to escape the while loop from
within it otherwise you'll encounter
what's called an infinite loop like this
while
and our condition is while one is equal
to one there's no way we can escape it
console.log
help
i'm stuck in an infinite loop
so this code will just repeat forever
you can see that the counter here is
going up i think my web browser froze so
yeah that's a while loop everybody it
repeats some section of code while some
condition is true
once you reach the end of that section
of code you check the condition again if
it's still true you repeat the code
again and this could potentially repeat
an infinite amount of times so that's a
while loop in javascript if you found
this video helpful be sure to help me
out by smashing that like button leave a
random comment down below and subscribe
if you'd like to become a fellow bro
all right guys i have to explain a
variation of the while loop it's called
a do while loop how this works is that
you do something then you check the
condition then you repeat if the
condition is true so going back to the
previous topic on while loops i have a
while loop we're checking if our
username is an empty string which it is
originally while this condition is true
we will prompt the user to enter their
name if i run this program and press ok
without typing anything i can't escape
this prompt once i type in my name hit
enter or ok we escape the while loop and
move on with the rest of our program
which displays hello whatever your
username is what i would like to do is
not assign my username right away i'll
declare this variable but not yet assign
it anything now when i run this program
here's the problem we don't get that
window prompt to type in our name we
skip the while loop and continue on with
the rest of the program and this
displays hello undefined we're using a
variable we declared but not yet
assigned once we reached our while loop
this condition was false from the get go
so we skip over the while loop entirely
what if i would like to run this code at
least once and then prompt again if the
username is equal to an empty string one
way although i wouldn't recommend it is
that we can copy this line of code and
paste it before the while loop that
prompt comes up i'll skip it and then we
enter the while loop and we're stuck
within it until we type in something i
don't like to repeat code if i don't
have to so there's a better way of
writing this let's convert this while
loop to a do while loop let's copy the
while keyword and the condition and
we're going to move it to the end of our
curly braces and preceding the opening
curly brace we will write do instead of
checking the condition first we check
the condition last we will do all of
this code and then check the condition
now if i run this program we encounter
that window prompt i'll press ok and try
and skip this prompt i can't i'll type
in my name and we escape the while loop
so a do while loop is a variation of the
while loop you do something first and
then check the condition with a standard
while loop you check the condition and
then do something if that condition is
true with a standard while loop you may
skip some code entirely if the condition
is false from the beginning with a do
while loop you do it at least once and
then check the condition so yeah that's
a super quick video on do while loops in
the next topic we'll move on to for
loops
well i should probably explain four
loops a for loop repeats some code a
certain amount of times there's a lot of
similarities between what for loops and
while loops can do there are a few
discrepancies though you tend to use for
loops when you want to repeat code a
limited amount of times a while loop is
better suited to something that could
execute an infinite amount of times
possibly in this example we'll create a
program to count to ten we'll start at
one count to ten and we can do that with
a for loop so type four
parentheses curly braces
what would we like to do within our
curly braces let's display a variable
console.log
let's call this counter now within the
for loop there's three statements that
we can add the first is that we can
declare and assign a counter or some
other variable the first statement we
will type let
counter
and i'll set the sql to 1.
then make sure to add a semicolon at the
end to terminate the first statement
second is our condition we'll continue
this statement as long as this condition
is true i will continue this for loop as
long as our counter variable is less
than or equal to 10
then add a semicolon and the third
statement is that we can increment our
counter
counter
plus equals one after each iteration we
increment our counter variable by one
after running this program we begin at
one and count to ten if i need to count
to 100 i can just change this condition
counter is less than or equal to 100 and
we have counted from 1 to 100 if i need
to begin at a different number i could
just set my counter to a different
number like i don't know
50. now we have begun at 50 and counted
to 100 so this variable counter it's
known as a local variable it doesn't
exist outside of this for loop what a
lot of programmers do if they need some
sort of temporary variable within a for
loop to keep track of what iteration
they're on they'll simply just use i
that's a common convention so let's
change counter to i
so let i
equal let's change this back to 1
we'll count to 10 and increment i by one
after each iteration
now we could begin at 10 and count down
if we were to take that approach we'll
set our variable i to 10 we'll continue
this for loop as long as i is greater
than zero and we will decrement i by one
we could pretend that this is a
countdown to new year's day this time
when we escape the for loop let's print
happy new year
console.log
happy new year okay we begin at 10 count
down to one once this condition is no
longer true we escape the for loop and
print happy new year so this simulates a
countdown so for loops are fairly
flexible we can increment or decrement
our counter i we're counting down by one
currently but we could count down by two
if we would like let's change i minus
equals one to two and now we will count
down by two ten eight six four two happy
new year or even three ten seven four
one happy new year so yeah that's
basically a for loop we repeat some code
a certain amount of times there's a lot
of overlap where you could use either a
while loop or a for loop a while loop
tends to be better in certain situations
where you may potentially need to repeat
some code an infinite amount of times
for loops are more suitable for code
where you only need to repeat it a
certain or given amount of times so yeah
those are for loops hey if this video
helped you out you can help me out by
smashing that like button leave random
comments down below and subscribe if
you'd like to become a fellow bro
hey guys i have a super quick video on
the break and the continue statements
let's begin with the break statement the
break statement breaks out of a loop
entirely in this example i'm going to
create a for loop we will count the
numbers 1 through 20. however once we
reach 13 i would like to exit this loop
because 13 is considered an unlucky
number i know it's a weird example so
let's define our counter i i equals one
and i will continue this as long as i is
less than or equal to 20 then increment
i by one
for the time being let's display
whatever i is this will display the
numbers 1 through 20. if i would like to
break out of this loop entirely if we
reach the number 13 i can add a break
statement so let's check to see if
i
is equal to 13
if it is then we'll break
okay we have the numbers 1 through 12
then we break there's also the continue
statement it will skip an iteration of a
loop if we replace break with continue
we will skip that specific iteration and
continue on
so we have 1 through 20 but the number
13 is not here so that's the main
difference between break and continue
break will break out of a loop entirely
continue will skip only that iteration
so yeah those are the differences
between the break and continue
statements
hey guys in this topic i'll be
explaining nested loops a nested loop is
just a loop inside of another loop
here's an example so i'll create an
outer loop that will count i don't know
to three
let i
equal one continue this as long as i is
less than or equal to three increment i
by one
during each iteration i will display the
value of i
console.log i this counts up to three
what if i would like to repeat this
entire for loop so many times well i
could put a for loop inside of a for
loop
so let me copy this
get rid of this line
and paste another for loop within the
curly braces of the outer for loop we
have a nested loop it's a loop inside of
another loop now one thing with nested
loops is that you'll want another
counter besides i because we don't want
to reuse the same counter a common
convention of the counter of nested
loops is that they'll use a counter of j
because j comes after in the alphabet
so let's replace i with j
and do so with our console.log statement
so if i was to run this program we would
count the numbers one through three
three times once we complete all of our
iterations of the nested loop we then
complete one iteration of the outer loop
if i change this outer loop to continue
as long as i is less than or equal to
two well then we will repeat this inner
loop a total of two times here's a
different example let's use nested loops
to draw a rectangle within our dom and
we'll accept some user input the outer
loop will be in charge of the rows the
inner loop will be in charge of the
columns we'll declare two variables let
rows equal window
dot prompt
enter number of rows
then let
columns equal number of columns
the outer for loop i will continue as
long as i is less than or equal to rows
and the inner for loop will continue as
long as j is less than or equal to
columns
we'll need an html element to work with
so within your html file let's create a
label
label
close it
and i will give this an id of my
rectangle
make sure to save
then heading back to our javascript file
let's change the inner html of our label
i will select our label
element document.getelementby id
my rectangle
i will set the inner
html before we draw a rectangle let's
print some of these numbers
i would like to append the inner html i
will set this to plus
equals
our counter j
the inner for loop will print one row
then to go down to the next row we can
add a break line
document
dot get element by id
my rectangle
dot inner html and i'm going to append a
line break
okay so let's try this for now we'll
just print some numbers what about three
rows and nine columns
so we have three rows and nine columns
of our index j let's replace these
numbers with maybe a symbol so it's an
actual graphical rectangle
let's
symbol
window dot prompt
enter a symbol to use
and replace j with our symbol
enter a symbol to use what about a
dollar sign press ok
number of rows maybe
four rows five columns
and we have a graphical rectangle let's
try it again what about an asterisk
three rows
nine columns
sweet
so yeah everybody that's a nested loop
it's a loop inside of another loop when
you encounter them it's kind of
situational in this video we used a
nested loop to help us print a rectangle
so yeah that's a nested loop everybody
hey if you found this video helpful be
sure to help me out by smashing that
like button leave random comments down
below and subscribe if you'd like to
become a fellow bro
hey everybody we are moving on to
functions with a function you define
code once and then use it many times
whenever you need to perform some code
you simply call the function name in
this scenario i need to sing happy
birthday like three separate times so
without using a function i could write
something like this
this will be one iteration so when i run
this we sing happy birthday once if i
need to sing two additional times well i
would have to copy this code and paste
it two additional times to sing three
verses of my happy birthday song so we
don't like to repeat code if we don't
have to wouldn't it be nice if we could
write this code once and reuse it
whenever we need well we can do that
with a function so to create a function
we will type
function and then a unique function name
let's name this function happy birthday
add a set of parenthesis and a set of
curly braces any code you would like to
repeat simply place within the curly
braces
if i need to sing one verse of happy
birthday i take the function name and
add a set of parentheses this will
invoke otherwise known as call the
function so you type the function name
add a set of parentheses i like to think
of the parentheses as a pair of
telephones that are talking to each
other that's how you call a function if
i need to use this code again i can
simply call the function again so that's
2 times and three times
so we have accomplished our task of
singing three verses of my happy
birthday song what if we have some
variables
let user name equal your first name
and let age equal some age within my
happy birthday song i'm going to insert
my username
as well as my age
so within my happy birthday song
we have my username and my age functions
have access to global variables a global
variable is basically a variable that's
declared outside of any functions or any
set of curly braces for example we may
have a function to start our program
and we will place this code within here
i will call the start program function
to begin my program
but we have one issue uncaught reference
error username is not defined variables
when declared with the let keyword
aren't recognized outside of the
immediate set of curly braces so my
happy birthday function has no idea what
username or age is these variables only
exist within the immediate set of curly
braces what i could do is that when we
invoke the happy birthday function from
within the start program function we can
send some information to this happy
birthday function so that it will
recognize my username and my age to pass
some values or variables to a function
when you invoke that function within the
set of parentheses just list whatever
you would like to send over i would like
to send over my username and my age
these are known as arguments however you
need a matching set of parameters within
the declaration of my happy birthday
function i need a matching set of
parameters
you can just copy the arguments over and
then paste them within the happy
birthday function these are known as
parameters you need to send over a
username and an age so now this should
work
so here's my username and my age
if i invoke this function without
passing my arguments well then this
function doesn't know what my username
and age is and with your parameters they
don't necessarily need to be the same
name you can rename these values when
you receive them within the function
i'll rename username as a and age as b
and i'll change that here and here
this would also work but make sure you
get the orders of the arguments and the
parameters right so if i switch these
around happy birthday dear 21 you are
bro years old so the order of the
arguments and the parameters does matter
so yeah everybody that's a function you
define code once and then you can use it
many times to perform some subroutine of
code you just call the function name
this is useful because we don't have to
repeat code more than once if you find
that you're going to repeat code more
than once you could write it within a
function so yeah those are functions
everybody in the next video we'll
discuss return statements hey if this
video helped you out you can help me out
by smashing that like button leave
random comments down below and subscribe
if you'd like to become a fellow bro
well alright everybody i need to discuss
the return statement the return
statement is used within a function to
return a value back to the spot in which
you invoked a function when you call a
function you can return some information
to demonstrate this we're going to
create a program to calculate the area
of a rectangle using a function and then
return the value so to create this
program let's declare a few variables
let area
let
with
and let height we'll accept some user
input
width
equals window
dot
prompt
enter
width copy this line paste it change
width to height
here and here at the bottom of our
program let's create a function to
calculate the area of a rectangle so to
create a function type function
let's name this get
area parentheses curly braces
when we use this function to calculate
the area of a rectangle we'll need to
set up some parameters in order to do so
we'll need a width
and a height when we invoke this
function we will pass these variables as
arguments when we assign our area
variable let's set this equal to then
invoke the get
area function
but we need to pass in a matching set of
arguments
our width
and our height
let's fill in this get area function i
will declare a temporary variable let
result
equals and to calculate the area of a
rectangle it's simply width times height
if i need to send a value back to the
spot in which we called a function we
can use the return keyword i would like
to return the result
then at the end of our program but
before our function let's display the
result just to be sure that it works
fine
console.log
the area
is
area okay let's try it okay enter the
width
maybe five height six the area is thirty
let's try it one more time how about the
width is six and the height is nine the
area is 54. so when we returned the
result once this function was completed
just imagine that we're replacing this
function call with 54. we're returning a
value back to the spot we invoked a
function we assigned 54 to our variable
area you could shorten this code as well
you don't necessarily need a temporary
variable we could eliminate this line
and return width times height and that
would do the same thing 6 times 9 is 54.
so yeah everybody that is the return
statement it returns a value back to the
place where you invoked a function so
yeah that's the return statement hey if
you found this video helpful be sure to
smash that like button leave a random
comment down below and subscribe if
you'd like to become a fellow bro
hey guys in this video i'm going to
explain the ternary operator it's a
shortcut for an if-else statement it's
represented by a question mark there's
three parts we write some condition
follow the condition with a question
mark as if we're asking a question if
that condition is true we perform an
expression if that condition is false we
perform a different expression and
separate each expression with a colon
here's an example let's create a
function that will check a user's age
initially we'll use an if else statement
and then later write it using the
ternary operator maybe we have a boolean
variable let adult and we will invoke a
check age function and pass in some age
let's define this function
function
check
age
there is one argument let's name this
age i need to check to see if age is
greater than or equal to 18 i could
write
with an if statement
if age is greater than or equal to 18
let's return a boolean value of true
else
return
false let's display whatever our adult
boolean variable is
console.log
adult i passed the number 21 as an
argument check age returns true if i was
12 well then check age returns false
there's another way of writing this and
i think it's a lot easier lot less
syntax this function will return a value
so i'm going to precede our tenary
operator with the return statement to
use the ternary operator we write a
condition followed with a question mark
as if we're asking a question
age is greater than or equal to 18
question mark second is an expression if
that condition is true we're returning
something let's return true and the
second expression if that condition is
false after a colon write some
expression or some value
false so this will do the same thing
currently i'm 12 this returns false if
i'm 21 well then it's true we have three
parts a condition with a question mark
an expression if that condition is true
colon and expression if that condition
is false here's another example maybe
we're playing a game and we have to
check to see if somebody won the game
i'll declare a check winner function
function
check
winner
let's declare a parameter of when this
will be a boolean value we're not
returning anything we don't need that
return keyword if we're examining a
boolean variable or parameter all we
need to do is type the name win question
mark if when is true what do we do
let's display a message this time
console.log
you win
colon then some expression if win is
false
you lose
then let's invoke this function
check
winner
then we can pass in a boolean value or
variable
like true
you win
or false
you lose so that's the ternary operator
it's a shortcut for an if else statement
you write some condition followed by a
question mark if that condition is true
you do something if not you do something
else it's a shortcut basically so yeah
that's the ternary operator if you would
like a copy of this code i'll post it to
the comment section down below and well
yeah that's the ternary operator in
javascript
guys in this video i'm going to explain
some of the differences between the let
and var keywords when declaring
variables variable scope is where a
variable is accessible any variable
declared with the let keyword is limited
to a block scope it doesn't exist
outside any sets of curly braces any
variable declared with the var keyword
is limited to a function here's an
example let's create a for loop
we'll count up to three
we will declare a counter of i set this
equal to one will continue as long as i
is less than or equal to three then
increment i by one so within my for loop
i will display whatever value i is
console.log i
our results are one two three what if i
attempt to access this variable i
outside of this for loop
console.log
hi what would happen exactly we have an
uncaught reference error i is not
defined that's because any variable
declared with the let keyword is limited
to a block scope it doesn't exist
outside of the set of curly braces
that's why my interpreter doesn't know
what the heck this is if we instead used
the var keyword to declare a variable
well then this variable i can exist
outside of curly braces and that could
be a problem so now if i attempt to
display whatever i is it's now 4. so if
i would like to reuse this counter i but
we declared it with var since it already
has a value it's going to potentially
mess with my program and cause problems
however any variable declared with the
var keyword doesn't exist outside of any
functions if it's within one let's
create a function
function do
something
i don't really care what it does
so let's copy this for loop place it
within the function and invoke this
function do
something
now when i display i after it's been
declared with the var keyword we have
that uncaught reference error i is not
defined a variable declared with the var
keyword can escape a set of curly braces
but it can't escape a function if it's
contained within one and that's where we
need to discuss global variables a
global variable is declared outside of
any functions so we have our function if
i was to declare let
name equal
some name since this variable is outside
of any functions it's considered a
global variable my entire program has
access to it and recognizes what it is
if you use the var keyword when
declaring a global variable that can be
problematic because if a variable
declared with var is global it can and
will change the browser's window
properties here's an example for a
demonstration within my console i'm
going to access my browser's window
object i will type window
select it hit enter we haven't discussed
objects yet we will in a future video
but windows have properties and my
browser window has one property of name
and currently it's just an empty string
let's say that i'm a beginner programmer
and i would like to declare a name
variable to hold a username
so if i was to use the var keyword and i
create a variable name and set the
sequel to whatever my name is
behind the scenes i will unintentionally
change this window property of name so
i'm going to save and run this let's
access our window again
and let's find name there so i have
unintentionally changed this windows
property of name and i didn't even
realize it and that could happen to any
of these properties and that could of
course possibly mess with your program
and cause problems now this time i'm
going to use the let keyword and you may
need to open this again with live server
this time i'm using the let keyword
i will type window again
select it hit enter and let's find that
name property again there by using the
let keyword i was able to declare this
variable name without changing this
windows property of name so yeah those
are some of the differences between the
var and the let keywords a variable
declared with let is limited to a block
scope a variable declared with var is
limited to a function scope if you
declare a global variable with var it
can potentially mess with your browser's
window properties let will avoid that
problem so it's considered good practice
to use let over var but you should still
know that var exists so yeah everybody
those are a few of the differences
between var and let hey if you found
this video helpful please be sure to
smash that like button leave random
comments down below and subscribe if
you'd like to become a fellow bro
hey guys in this topic i'm going to be
discussing template literals they're
delimited with backticks instead of
double or single quotes they allow for
embedded variables and expressions maybe
we're working on a page for an online
store let's create three variables let
username make up some username
let items for the number of items that
we have our cart has maybe three items
in it let
total
and make up some total price 75
okay so normally if i would like to
display these variables along with some
strings with console.log i would write
something like this
hello
username
you have
items
items
in your cart
your total is
dollar sign
total hello bro you have three items in
your cart your total is 75 dollars
another way of writing this which i like
to use is to use template literals in
place of singular double quotes for
strings we will use these backticks so
i'm going to copy these three lines of
code turn these into comments
so when using backticks we can embed a
variable or expression within a string
for this first string let's type
hello and to embed a variable or
expression use a dollar sign followed by
a set of curly braces
and we can embed a value variable or
expression i would like to embed my
username
so currently this is what we have hello
your username let's try this again
you have i would like to embed items
so that's dollar sign curly braces type
the variable name
items
the word items
in your cart
you have three items in your cart
your total is
dollar sign curly braces total
so if you need that dollar sign i could
just precede this with another dollar
sign
your total is 75
i find using template literals a lot
easier to work with here's a scenario
what if we would like to display one
very long string here's what we can do
let's assign a new variable let
text equals
and i will copy what we've placed within
these log statements
make sure it begins and ends with that
backtick character
so we have assigned this entire string
template to a variable text
if i need to display all of this
i can simply just use this text variable
console.log text
hello bro you have three items in your
cart your total is 75
where this is really helpful is if we
need to update an html element with some
text
especially if it takes up several lines
let's head to our html file i'll create
a new label
label
add a closing tag
i'll give this an id of
my
label
in place of displaying this to my
console i'm going to update this label
to select that label i will type
document dot
get
element by id the id was my label
change the inner
html equal to text
and this is what we have currently
except i'm going to add some line breaks
i'll add that here
here and maybe here
so there you go
hello bro you have three items in your
cart your total is 75 dollars by using
template literals they allow for
embedded variables and expressions it's
a more flexible way to write some output
i'll be using these a lot more in the
future because well i like them so yeah
those are template literals everybody if
you would like a copy of this code i'll
post this in the comment section down
below and well yeah those are template
literals in javascript
hey what's going on everybody so in this
video i'm going to explain the two
locale string method of numbers what
this does is that it returns a string
with a language sensitive representation
of this number it's fantastic if you
need to format a number as some currency
we have a number with numbers there's a
built-in method named to locale string
and a few arguments the first is locale
locale specifies the language if you
pass in undefined well then you'll use
the default set in your browser next is
options options is an object with
formatting options we can specify if
this number is currency a unit of
measurement a percent let's begin let's
create a number let my num
equals make up a number i'll just pick
one two three four five six point seven
eight nine
so i'm going to reassign my num
equals my num dot to
locale
string
the first argument is locale this is a
string then we'll pass in a language
united states english that would be en
us
then let's display my num
console.log
num
so when i run this this number is
formatted with a comma for every
thousands place so that is us english
okay next let's try hindi
so let's copy this paste it hindi is
h i dash
i n
so there's a different number formatting
system
that is hindi let's try one more what
about standard german
standard german is d e
dash
d e
there's a different number formatting
system
standard
german
whatever language you need you just have
to look up the format code then pass
that as a string but those are a few
this time let's format some currency we
would set that within options
i'll pick us english
to add some options we'll use curly
braces
set the style
to
currency
then currency
colon
then a unit
usd is us dollars
so this number is now in us dollars and
you can see too that this number is
rounded to dollars and cents
originally we had three decimal places
okay let's try another
what about rupees
let's copy this paste it
h i
i n
currency
rupees have a currency code of i n r
there then let's try
euros let's set the language to german d
e dash d e the currency code is e u r
for euros
now there's other styles besides
currency this time let's try a percent
mynum
equals
mynum
to
locale
string
this time i will set the first argument
in place of a language to be undefined
but i will set the style
to be
percent
this number as a percent is
12 million percent so let's change that
100 would be ten thousand percent point
five is fifty percent
point zero one is one percent that's how
to format your number as a percent
then let's go to units
my num equals my mynum.2 locale string
we can set the first argument to be
undefined
then under options set the style to be
unit a unit of measurement what kind of
unit would we like i will separate that
with a comma
unit colon space what about celsius
celsius
so currently my number is
100 make sure it's lower case
there 100 degrees celsius
you have a couple different units to
choose from celsius kilometers miles
kilograms whatever you need
well okay then everybody that is an
introduction to the two locale string
method it returns a string with a
language sensitive representation of a
number you can set the locale which
specifies the language by passing in
undefined as an argument that will use
the default set in the browser then you
can pass in formatting options would you
like to set the style to currency
percent a unit of measurement etc so
yeah everybody that is the two locale
string method in javascript
hey guys in this video we're going to
create a very basic number guessing game
in javascript so heading to our html
file let's create some html elements
i'll need a title for this game i'll use
an h1 take we'll add some text number
guessing
game let's save that i'll add a
paragraph right underneath pick a number
between
1
through 10
and i'll add a label
label close it
enter a guess
we'll need some input
this will be a text box input id equals
guess
field
and a submit button
input
type
equals
submit the id will be submit
button
and those are the html elements that
we'll need now heading back to our
javascript file we'll need a random
number
i'll make this a constant
and it will be answer
answer will be a random number between 1
and 10.
so we will use math.random
times 10.
this will give us a random number
between zero and nine so let's add one
for numbers one through ten
then we will surround this with
math.floor to round it
math.floor and i will surround this code
with math.floor
math.floor we'll keep track of our
guesses
let
guesses equal zero
so when we click on this button we would
like to do something but we need to
select this button
and the id was submit button
document dot get
element by id
the id is submit button
and set the on click event attribute
equal to a function
what would we like to do well there's a
lot of stuff we have to do we'll need to
get the value from this text box
so document.getelementbyid
the id is
guest field
dot value and we will assign this to
guess so let's declare that and assign
it whenever we make a guess we should
increment guesses by 1 to keep track of
it guesses plus equals 1.
we'll first check to see if our guess is
equal to our answer
if guess is equal to our answer
let's create an alert message
alert
i'll use a template literal
answer
is the number
it
took you
guesses
guesses
else if
our guess is less than answer
we will alert the user
too small
else
alert
too large
okay make sure you save everything and
let's run it enter a number i'll pick
something right in the middle five
too small
what about seven
two small
nine
nine is the number it took you three
guesses
so yeah that is a very basic number
guessing game everybody
if you would like a copy of this code
i'll post this in the comment section
down below and well yeah that's a very
basic number guessing game in javascript
hey everybody in this video we're going
to create a practice program in
javascript to convert some temperatures
using some html elements so sit back
relax and enjoy the show
okay let's begin everybody before we add
html elements to our dom let's work on
the logic behind the functions let's
declare and assign variable temperature
and set the sequel to some temperature
doesn't matter if it's fahrenheit or
celsius yet and at the end of our
program let's declare two functions
function
to
celsius
and there will be one parameter
temperature and function two
fahrenheit the formula to convert a
temperature in fahrenheit to celsius is
our temperature
minus 32
times
five divided by nine
the formula to convert celsius to
fahrenheit is return
temp
times 9 divided by 5
plus 32
let's say that our temperature is
currently in fahrenheit and i need to
convert this to celsius i will reassign
temp
equal to and i will invoke the 2 celsius
function
and pass in my temperature then at the
end we will display whatever our
temperature is console.log
temp so the temperature should be zero
zero degrees celsius if we're converting
this to fahrenheit then 32 degrees
celsius converted to fahrenheit
is 89.6 degrees now that we have the
logic behind these functions completed
let's add some html elements heading to
our html file within the body tags we
will create a label
then close it and i'll add a line break
for some text let's add
enter
a
temperature
then we'll create a text box
so use a self-closing input tag i'll
create a line break
the type
is text
the id
let's say is text box
let's create a second label
label
close it
add a line break we will add the text
convert to colon we'll create two radio
buttons
input
type
equals radio so with a radio button if
they're in the same group you can only
select one
this first radio button will be for
celsius
we'll give this a unique id of c button
for celsius
name
unit
let's save there's one radio button and
we'll add a label next to this radio
button
label
close it
add a line break
and the label will be
celsius
okay let's copy these two lines
and paste them and make a few changes
this will be the fahrenheit radio button
we'll give this an id of f button the
name will be unit
and change the label
fair and height
since these radio buttons are within the
same group they have the same name
we can only select one of them
if they had a different name
like c or f
well then you can select both of them
because they're in different groups
so these will have the same name unit
let's create a submit button right at
the end
so button
let's close it
add a line break
the type will be button
and the id is maybe submit
button
let's add some text to this button
submit
i'm going to close that at the very
bottom of our dom let's add a label that
will display the temperature
use a pair of label tags i'll give this
an id of
temp
label and those are all the html
elements that we'll need
let's save head back to our javascript
file when we click on the submit button
there's a lot of things that we need to
do at the very top of my program i'm
going to type
document dot get element by id
the id of this button is submit button
dot on click
and i will set the sequel to a function
parentheses curly braces
there's a lot of lines of code that
we're going to add between these curly
braces so let's get rid of these three
lines of code we don't need them any
longer i'm going to declare a local
variable within this function let
temp
so when we click on our button let's
check to see if one of these radio
buttons is selected
let's begin with the celsius button
if
document dot get
element by id
and the id of the celsius button is c
button
we need to check to see if this radio
button is checked or not
so add dot
checked
if this
equals true
but since this is a boolean value you
don't need to necessarily add equals
true
document.getelementbyid c button dot
checked
that's fine as a condition
if our celsius button is selected do
something
else if
our fahrenheit button is selected do
something else
let's copy our condition paste it
this time we are checking the fahrenheit
button that is f button
and lastly else else means we didn't
select anything let's work on the else
statement first that's fairly easy so i
would like to change our label that's
down here at the bottom temp label
so type document dot get element by id
temp label and i will change the inner
html i'll set the sequel to
select a unit
if i were to click on the submit button
it should change the text of my label to
select unit we know that it's working if
we enter in a temperature press the
celsius radio button
then click submit
what would we like to do
let's extract the temperature from this
text box
so we will take our temperature variable
set the sequel to
document dot get element by id
and the id of this text box is text box
dot value
when we accept user input from a text
box it's of a string data type we'll
need to convert that to a number so
let's reassign temp equal to
use the number constructor and pass in
our temperature
it's assumed to be in fahrenheit if we
would like to convert to celsius let's
invoke the 2 celsius function
i'll reassign temp equal to
the 2 celsius function invoke it and
then we need to pass in our temperature
after the temperature is converted we
need to change our label
so copy this line of code paste it
and i will set the sql to
temp plus
if you're writing this code on a pc if
you need the degree symbol one shortcut
is to hold alt
and on the numpad press
zero one seven six
if you're on a mac then do this
i'll post it on the screen right now so
this temperature is in celsius
okay let's test this
32 degrees
converted to celsius
is 0 degrees celsius
if this was 50 degrees fahrenheit
converted to celsius
that would be at 10 degrees celsius
now with the fahrenheit radio button
let's copy everything we have within
this if statement
paste it
and we will invoke the 2 fahrenheit
function instead of the two celsius
function
and change the temperature from c to f
okay let's try this
zero degrees
in celsius converted to fahrenheit is 32
degrees fahrenheit so yeah that was a
practice project to convert temperatures
using javascript hey if you found this
video helpful please be sure to smash
that like button leave a random comment
down below and subscribe if you'd like
to become a fellow bro
well well well we've finally made it to
a raise think of an array as a variable
that can store multiple values it's a
little more complex than that but that's
an easy way of thinking about them in
this example i have a variable fruit
fruit contains some string
representation of a fruit like an apple
i can store multiple names of fruits
within this variable if i convert it to
an array so to change this variable into
an array surround all of your values
with a set of square brackets and
separate each value with a comma maybe i
don't want just an apple maybe i would
also like
an orange
and a banana just so it's more obvious
that this contains multiple values i'm
going to change this variable name from
fruit to fruits well i guess in the
english language fruit would also be
plural but it's just not obvious so we
have an array fruits now look what
happens when i display this array using
console.log
if i display my array fruits it will
display all of this junk you can see the
different values within this array apple
orange banana each value within an array
is also known as an element if i would
like to access a particular element
within this array when i use the array
name i will add a set of square brackets
then i need to list an index number of
the element i would like to access
computers they always start with zero so
the first element in my array has an
index of zero if i was to display fruits
at index of zero then we have access to
the first element which contains an
apple
the next element which has an index of
one is my orange at index 2 there's the
banana if i attempt to access an element
that doesn't exist such as index 3 well
then it's undefined
you can also update and change the
elements of an array
so to do that type the name of the array
followed by an index number
maybe fruits at index of zero is now a
coconut
and then let's display fruits
so we have a coconut orange and banana
if i change this to one we have an apple
coconut banana
two
apple orange coconut so to access an
element from an array you type the array
name followed by a set of square
brackets and then an index number you
can later on add an element
to do that use the push method
type the array name
dot push parenthesis
then add a value
like a lemon
we have an apple an orange a banana and
a lemon this will add an element
we can remove the last element
fruits dot pop
okay that lemon is no longer there apple
orange banana
removes last
element
we have the capability to add an element
to the beginning of an array type the
array name dot on
shift
method
and add a value
maybe a mango
mango apple orange banana
this method will add
element to the beginning
and the shift method will remove the
beginning element
fruits
dot shift
apple orange banana that mango is gone
because i ate it so the shift method
removes element from
beginning
you can access the length property of an
array i'll store this within a variable
let
length
equal fruits
dot
length
and the length of my array
is three we have three elements an apple
an orange and a banana you can find the
index of an element
let
index equal the array name
dot
index of method i would like to find the
index of our apple value
and i will display this
so again computers always start with
zero
the index of my apple value was found at
index zero the beginning
orange would be at one
banana is at two if you search for an
index of an element that doesn't exist
such as
how about a kiwi well then this will
return an index of negative one that
means it was not found
so yeah everybody that's an array think
of it as a variable that can store
multiple values it's a little more
complex than that but that's an easy way
to think about it so yeah this is the
beginning on a small series on arrays
hey if this video helped you out you can
help me out by smashing that like button
leave a random comment down below and
subscribe if you'd like to become a
fellow bro
hey guys in this video i'm going to show
you how we can loop through the elements
of an array maybe we have an array of
prices and i will set this equal to and
just make up some prices it doesn't
really matter five dollars ten dollars
fifteen dollars twenty dollars good
enough two popular ways to iterate over
an array is one to use a standard for
loop and the other is a for of statement
let's begin with a standard for loop so
type four parentheses curly braces we'll
need to create a counter let i set this
equal to zero i would like to continue
this while i is less than the length
property of our array prices prices dot
length then i will increment i by one i
plus equals one during each iteration i
will display my array prices but we
gotta list an index so that index is i
prices at index of i during the first
iteration i will be zero during the next
iteration it would be one then two then
three so on and so forth so after
running this program this will iterate
and display the elements of my array 5
10 15 20 and it will adjust according to
the size of the array and my for loop
will iterate over that price as well now
if you would like to iterate backwards
over this for loop here's how to do that
so i'm going to set my counter equal to
prices dot length minus 1. i would like
to continue this as long as i is greater
than or equal to 0 and then lastly we
will decrement i by 1. this allows me to
iterate over my array backwards we're
beginning at the end 25 20 15 10 5. so
that's how to use a standard for loop to
iterate over the elements of an array an
additional option is a for up statement
we'll type four parentheses curly braces
we'll declare a counter
let
i
of
our array prices
console.log
just i and this will also iterate over
our array but a better way of writing
this in place of our counter i let's use
a word that's more descriptive of what's
within our array our array is named
prices
an element of this array prices would be
price so let's change this to price
because it's more descriptive
console.log price and i think people
would understand that more there 5 10 15
20 25. so yeah everybody those are a
couple different ways to iterate over
the elements of an array hey if this
video helped you out you can help me out
by smashing that like button leave a
random comment down below and subscribe
if you'd like to become a fellow bro
hey everybody in this video i'm going to
show you how we can sort an array of
strings in javascript let's create an
array of fruits because i'm hungry and
add some various names of fruits make
sure that they're not in order
banana
apple
orange
and a mango to display my array of
strings i can use a for of statement
we'll create a for loop and the
statement within the for loop is let
fruit of fruits
console.log
fruit
singular
and here is my array of fruits
to sort this array there is a built-in
method of arrays called sort but i'm
going to reassign this to the same array
fruits equals fruits and use the sort
method
and my fruits are now sorted in
alphabetical order if you need this in
reverse alphabetical order this is what
you can do
i'm going to turn that line into a
comment copy it paste it we're going to
do some method chaining add dot reverse
parentheses
and my array of strings is now sorted in
reverse alphabetical order so yeah
that's a super quick video on how to
sort an array of strings in alphabetical
order and reverse alphabetical order if
you would like a copy of this code i'll
post this in the comment section down
below and well yeah that's how to sort
an array of strings in javascript
hey guys in this video i'm going to
discuss 2d arrays also known as
multi-dimensional arrays it's an array
made up of arrays so in this example
we'll create a grocery shopping list and
that grocery shopping list will be made
up of separate individual lists a list
for fruit vegetables and meat let's
begin by creating three individual
arrays and then add them all to one
array to contain them let's begin with
an array named fruit or fruits
let fruits equal and think of some fruit
i'm thinking apples
oranges
bananas this is our first array let's
create another i'll name this vegetables
what about carrots
onions
and potatoes and lastly meat
or meats
eggs
chicken
fish we have three individual arrays if
we wanted to we could add these
individual arrays into another array i'm
going to create another array this will
be our two-dimensional array named
grocery list
equals and add the names of the arrays
that you would like to add
fruits
vegetables
and meats
so grocery list is our two dimensional
array how can we iterate over the
elements of this two-dimensional array
we can use nested loops i'll use nested
four of loops
the outer loop will be in charge of
managing each list
let
let's name each item maybe list
let list
of
grocery list
so right now if i display list it's
going to display all of the individual
arrays i'm just going to test that
console.log
list this for loop will iterate three
times one for each array within our
grocery list and it displays details of
each list to access the individual
elements within each list each array i'm
going to create a nested loop we'll use
a for of loop again
let
how about food
like each food item
of
list
and i will display console.log
each food item each element food so this
will display all the elements of my
two-dimensional array apples oranges
bananas carrots onions potatoes eggs
chicken fish what if you need to change
one of these elements within your
two-dimensional array with a
two-dimensional array there are two
indices to access one of these elements
within a two-dimensional array
type the name of the two-dimensional
array and there's two indices so if we
take a look at the way that all of these
elements are set up
it kind of resembles a grid there's rows
and columns picturing a grid the first
index would be the row the second index
is the column i would like to replace
apples with mangoes i need to find the
row number and the column number so
computers they always start with zero
the first row would be row zero
and the first column would be column
zero
so the indices are zero zero and i will
set the sql to
mangoes i think that's how you spell
mangoes
yeah after refreshing we have mangoes
oranges bananas
let's replace bananas
that is row zero column two
zero one two so change the second index
to two
apples orange's main goes let's replace
eggs with steak
that would be row zero one two
column zero
steak chicken fish for my last example
let's replace fish with steak that is
row zero one two column zero one two
two two eggs chicken steak yeah
everybody that's basically a 2d array
it's an array of arrays it's useful if
you ever need some sort of grid of
information we probably won't be using
2d arrays too much in the future so yeah
those are 2d arrays hey if you found
this video helpful please be sure to
smash that like button leave random
comments down below and subscribe if
you'd like to become a fellow bro
hey y'all everybody in this video i'm
going to explain the spread operator it
allows an iterable such as an array or
string to be expanded in place where
zero or more arguments are expected
basically speaking when used with an
array it unpacks the elements in too
many individual pieces let me give you a
demonstration we have an array of
numbers let numbers equals
make up some numbers put them within
this array one two three four five six
seven eight
nine
using console.log if i was to display
this array directly
console.log numbers
this will display the details of this
array this array object
now if i was to precede my array with
the spread operator
which is three dots it would expand the
elements of this array we have the
elements one through nine actually you
can do this with a string too i'll give
you a demonstration
let
user name equal your first and last name
so i will use the spread operator
a string
and this will spread the string into
individual characters how could this be
useful let's say we need to find the
maximum value within this array well we
could use the
math.max method but with the max method
it accepts a varying number of arguments
we could pass in a value a variable like
x y z whatever the maximum is we would
return it and we can store that within a
variable let
maximum
equal math.max so what if we stick an
array in here
math.max numbers and then display it
console.log
maximum what happens exactly
uh so this returns not a number in place
of passing this array directly to a
method we could expand it by using the
spread operator so this will unpack
these elements into individual arguments
now when i run this we have our maximum
value of 9. if i added another like 10
well then it returns 10. so it's
fantastic if you need to pass in a
varying amount of arguments to a
function or method here's another
example we're a teacher and we have two
classes each represented by an array of
student names i need to merge these two
classes into one we'll create class 1
let class 1 equal some student names we
have spongebob
patrick
and sandy class 2 has these students
class 2 equals
squidward
mr krabs
and plankton
to add an element to an array you type
the array name
followed by the push method
and pass in an element if i would like
to add all of these students you would
think that i passed the array name as an
argument
class1.push class2
so let me show you what happens
console.log
class 1
so we have three students and an array
so we have an entire array as an element
which i didn't want to do so in place of
adding this class directly as an element
let's spread it into individual
arguments by using the spread operator
now when i display this array we have
six students spongebob patrick sandy
squidward mr krabs and plankton another
way to display this is to use the spread
operator
i will precede class 1 with the spread
operator
class 1 is divided into individual
elements spongebob patrick sandy
squidward mr krabs plankton
so the spread operator allows an
iterable such as an array or string to
be expanded in place where zero or more
arguments are expected by preceding an
array with the spread operator you
unpack the elements it's kind of like
you're opening a box and taking out
whatever's inside so that's the spread
operator if you would like a copy of
this code i'll post this in the comments
section down below don't be afraid to
smash that like button leave random
comments down below and subscribe if
you'd like to become a fellow bro
everybody in this video i'm going to
explain rest parameters rest parameters
represents an indefinite number of
parameters it packs arguments into an
array when you pass arguments to a
function here's how using rest
parameters would be useful i have five
different variables
i would like to sum a varying amount of
these variables
using console.log
i will invoke a sum function which we
will need to declare let's pass in
variables a and b to begin with i need a
matching function that is named sum that
accepts two arguments
function sum
arguments a and b we will simply return
a plus b so this returns three variables
a and b are arguments what if i would
like to add another argument
like c this specific sum function isn't
suitable for three arguments i would
need a sum function that accepts three
arguments this time
a b c
return a plus b plus c
then i could accept three arguments but
wait what if i have to pass in another
argument like d
well this function no longer is suitable
i would need to create another function
that accepts four arguments
a b c
d return a plus b plus c plus d you can
kind of see where i'm going with this we
have three different sum functions if
this time we need to pass in two again
two arguments
we receive not a number we would need to
give each of these functions a unique
name like sum2
sum3 sum4
but this isn't practical
wouldn't it be better if we had a
function that could accept an indefinite
number of parameters while we can with
the rest parameters
so let's get rid of all this code we
will declare a function that will accept
any number of arguments
function
sum
the rest parameters will pack these
arguments into an array
so we will use the three dots for the
rest parameters then we need a name for
this array like numbers
if our elements are within an array we
would just need some way to access those
elements there's a couple different ways
you could do this i'm going to create a
total let total equal zero and we will
iterate over our array
for
let
number
of our array numbers
we will take our total incremented by
our number and then at the end return
total
this time we can pass two arguments to
this function
or three
or four
five
doesn't matter so that's the benefit of
using rest parameters they represent an
indefinite number of parameters when you
call a function that has rest parameters
it will pack the individual arguments
into an array then you would just need
some way to access the elements of that
array you can mix and match the
parameters for example you could say x
and y
if i was to write it this way these
first two arguments will be x and y
respectively and any arguments
afterwards would be packed into this
array if you're mixing and matching rest
parameters along with some named
parameters make sure that the rest
parameters take up the last parameter
within this function so yeah that's rest
parameters if you would like a copy of
this code i'll post this to the comment
section down below if you haven't
already smash that like button leave
random comments down below and subscribe
if you'd like to become a fellow bro
hey guys in this video i'm going to
discuss callbacks a callback is a
function passed as an argument to
another function
using callbacks is a popular programming
technique because it ensures that a
function is not going to run before a
task is completed here's an example of
where a callback would be useful let's
say we need to add two numbers together
let
total equal sum
pass two numbers as arguments
maybe two and three i'll create a
function to add these numbers together
and return something we will declare a
function sum to add these two numbers
together
and set up some matching parameters to
these arguments let's name these x and y
let result equal x plus y
return result
then afterwards i would like to display
my result one function to display the
results to the console and the other to
the dom function
display
console
i'll name this argument
output
console.log
output
after finding a total we will invoke the
display console function and we will
pass our total as an argument this
displays the number 5 to the console now
let's create a function to display some
output to the dom
function
display
dom
we'll keep output as the argument
however we will change the inner html of
an element
so heading to our html file let's create
a label
close it
i'll give this an id of
my
label
save head back to your javascript file
and i would like to select my label
document.getelementbyid
the id of that label was my label
and i will set the
inner
html equal to the output that i receive
i will instead invoke the display dom
function display dom pass in total as an
argument and we have the number five
another way of writing this is that we
could use a callback we can pass a
function as an argument to another
function let's get rid of these lines we
won't need them anymore but we will keep
these two functions this time i'm going
to invoke a sum function
pass in my arguments
2 and 3
and also the name of a function i would
like to execute once we finish this
function
let's invoke the display console
function once we finish the sum function
so we will pass the name of this
function as an argument just be sure not
to add that set of parentheses after
because then you would be invoking that
function just the name of the function
next i need to set up this sum function
this specific function will have three
parameters the first two are the numbers
we would like to add together and the
third is a callback so let's define a
sum function function sum and there's
three parameters we'll name these x
y
and for the callback you can really name
it anything
i'll just name it callback and again
make sure not to add that extra set of
parentheses afterwards
so call back we'll add these two numbers
together let result
equal x plus y and then we will invoke
our callback so at the end of the
function type
callback remember that it stores a
function kind of like a variable then
add a set of parentheses then we'll be
invoking this function and if there's
any arguments
we have one parameter output make sure
to pass that in
so pass in result execute my callback
pass result as an argument
and this display is my output if i would
like to pivot and instead display my
output to the dom
i'll just pass in a different callback
display dom so we'll pivot and execute a
different function and our output is
displayed to the dom so you don't
necessarily need to name this parameter
callback
we could name this maybe
do something
at the end of the function do something
do some other function
or maybe my funk this would be valid too
so remember you can rename parameters so
using callbacks is an additional way in
which we can write code it ensures that
a function is not going to run before a
task is completed it helps us develop
asynchronous code when one function has
to wait for another function it helps us
avoid errors and potential problems for
example we could wait for a file to load
once the file loads then we do something
we'll have more practice with callbacks
in future videos so yeah that's a
callback everybody you can pass a
function as an argument to another
function and then execute it later hey
if this video helped you out you can
help me out by smashing that like button
leave a random comment down below and
subscribe if you'd like to become a
fellow bro
hey guys in this video i'm going to
discuss the for each method of arrays
the for each method executes a provided
callback function once for each array
element we have an array of students let
students
equals and make up some student names in
this example let's make all of the
letters lowercase we'll create a
function that will capitalize the first
letter of each student name so i'm going
to write spongebob all lowercase
patrick
and squidward
let's define a function that will
capitalize the first letter of each
string function
capital lies
now with the for each method there's up
to three arguments that are provided
automatically behind the scenes that we
have access to
an element
an index
and the array we don't necessarily need
to use any of these but they're provided
for us but in this function we will to
capitalize the first letter of each
string this is what we can write i would
like to access my array parameter at
index
of index
equals
our element
at index of zero
this will select the first character of
every string dot
follow this with the
two
uppercase method
plus
element
dot
sub string method
pass in
one this line right here will capitalize
the first letter of each string then i
will print one of these elements
console.log students at index of zero
now to use the for each method we will
type the name of the array
students dot for
each
then pass in a callback as an argument
we will apply this callback to every
element in an array the callback is the
name of the function capitalize make
sure to not add an additional set of
parentheses that will call the function
we're only passing the name of the
function as an argument this will
display the first student spongebob and
the first letter of his name is capital
let's do this again but create an
additional function to print each
student that's within my array
function
up to three arguments are provided for
us an element an index and an array we
don't necessarily need to use all three
i would just like to use element
and remember you can rename these two
such as x y or z but i would do
something that's descriptive but this
time we only need element
using
console.log
i am going to display each element and
again we will use the for each method
students dot for
each passing our callback of print
and here we go
yeah spongebob patrick squidward alright
everybody that is the for each method of
arrays it executes a provided callback
function once for each array element so
yeah everybody that is the for each
method of arrays if you would like a
copy of this code i'll post this in the
comment section down below and well yeah
that's the for each method of arrays in
javascript
hey everybody in this video we're going
to discuss the map method of arrays the
map method executes a provided callback
function once for each array element and
creates a new array here's an example
let's create an array of numbers
let
numbers
equal
one two three 4 5.
we're going to use the map method of
this array at numbers and the map method
will square each element in this array
and create a new array let's define a
square function
function
square
we need at least one parameter element
we will return
math
use the power method
pass in our element as a base raised to
the power of 2.
this is our square function
we will pass the name of this function
square as a callback to the map method
and this will create a new array so
let's define a new array
let
squares
equal to then i would like to invoke the
map method of my numbers array
numbers
dot map
pass in my callback of square and then i
would like to display the elements of
squares i'll do that with a print
function
function
element
console.log
element
and i will use the for each method of my
squares array squares
for each method pass in a callback of
let's take a look at the elements of
squares
yeah each element from my numbers array
was squared and added to a new array
squares
1 4 9 16 25. hey for fun let's create a
cube function
function
cube
we need at least an element parameter
copy this line
but change two to three
element to the power of three
let
cubes
equals
numbers dot map
cube
cubes
for each method pass in print as a
callback
and all of my original numbers are now
cubed and stored in a new array cubes 1
8 27 64 125 so yeah everybody that is
the map method of arrays it executes a
provided callback function once for each
array element and it creates an entirely
new array so yeah that's the map method
of arrays if you would like a copy of
this code i'll post this in the comments
section down below and well yeah that's
the map method of arrays in javascript
all right let's talk about the filter
method the filter method creates a new
array with all elements that pass a test
provided by a function we can filter out
elements from an array and create a new
one based on certain criteria let's
create an array of student ages
let
ages
equals
make up some student ages
18
16
21
17
19
90. i'm going to create a new array of
anybody that's 18 or older so i will
create a function to check age function
check
age
and there is one parameter
element this will create a new array we
will return and now we need some tests
to filter out any elements that don't
meet the criteria
our test will be
element is greater than or equal to 18.
so we will use this check age function
as a callback within the filter method
this will create a new array so let's
define that let
adults
equal
ages the original array
dot
filter
pass in the check age function as a
callback and then we just need to
display all of the elements of this
array
adults dot for
each
pass in a callback to
a print function which we'll define
momentarily
function print
element
console.log
element
so the elements in our new array are 18
21 1990 so yeah that's basically the
filter method it creates an entirely new
array with all the elements that pass a
test provided by a function and this
will leave the original array alone but
it creates an entirely new array of
elements that pass a test so yeah that's
the filter method everybody if you would
like a copy of this code i'll post this
in the comment section down below and
well yeah that's the filter method of
arrays in javascript
hey guys in this video i'm going to
explain the reduced method of arrays the
reduce method reduces an array to a
single value a very good use of the
reduce method would be to sum up all the
values of an array imagine we have an
online store and somebody has a bunch of
items in their cart we could sum up the
prices of all the items and create a
total let's create an array of prices
let prices equals make up some prices
five dollars ten dollars fifteen twenty
twenty five that's fine and i will
create a function that we will use as a
callback function
checkout
we'll call this function when we would
like to check out and make a purchase so
there are at least two parameters that
we need total this parameter will hold
the accumulated value as well as the
current element that we're working with
we will return
if we're trying to create a sum of all
the elements
total plus
element so when we return a value we
will reuse it as an argument for the
next iteration this is how we can reduce
all the elements of an array to a single
value let's create a total variable and
this will hold the final price that the
user has to pay to reduce all of these
prices to a single value we type the
name of the array use the built in
reduce method
and pass in the callback checkout
then i will just display what our total
is console.log
i'll use a template literal for this i
will use a set of backticks
the total
is
total
okay
so the total price is 75
let's add something else something that
is 30
now the total is 105
so that's the reduced method of arrays
it reduces an array to a single value a
fantastic use of the reduce method is to
sum up an array of values like items in
a shopping cart and create a total
that's the reduced method of arrays if
you would like a copy of this code i'll
post this in the comments section down
below and well yeah that's the reduced
method of arrays in javascript
hey guys in this video i'm going to show
you how we can sort an array of numbers
in javascript let's imagine that we're a
teacher and we have a student grade book
our task is to sort our students grades
in either ascending order or descending
order let's begin let's create an array
named grades
and make up some student grades i'm
thinking 100
50
90
60
80
70. let's create a function that will be
used as a callback to sort these numbers
in descending order so the greatest
number will be first the lowest number
will be last
function
let's name this
descending
sort
there's two parameters x and y all we
have to do is return
y minus x this will compare two values
at a time to sort this array and use
this callback function i will reassign
grades equal to grades
dot sort method and pass in a callback
descending sort and then we just need to
display our grades grades
i'll use the built-in for each method
and i will pass a callback of print then
we just need to define this function
function
there is one parameter
of element
console.log
element
now after running this
our grades are in descending order let's
create a callback function for ascending
order
so let's copy this paste it change
descending to
ascending return
x minus y
and for the callback we will pass the
argument ascending order
and our grades are now in ascending
order the lowest is first the highest is
last so yeah that's how to sort an array
of numbers if you would like a copy of
this code i'll post this in the comment
section down below and well yeah that's
how to sort an array of numbers in
javascript
hey guys in this video i'm going to
explain function expressions a function
expression is a function without a name
also known as an anonymous function a
benefit is that function expressions
help us to avoid polluting the global
scope with random function names we can
write a function and then forget about
it if i need to create a function to
display a greeting message using a
function declaration i would need to
think of a unique function name such as
function how about the say
hello function
console.log hello then to invoke this
function i just type the function name
followed by a set of parentheses boom we
have our function so it can get somewhat
tedious and annoying to think of unique
function names especially if the rest of
your program is not going to use it
another way that we could write this is
to use a function expression and we will
store that within a variable i will use
the const keyword this time const is
just a variable that you can't change
the value of later const
greeting
and i will set the sequel to a function
expression we will type function
parentheses curly braces and we do not
need to think of a unique function name
what would we like to do
console.log
hello then to invoke the function stored
within this variable i just type the
variable name followed by a set of
parentheses to invoke it
hello so there is no need to think of a
unique function name we can assign an
anonymous function to a variable or some
other entity which we'll discuss in the
future here's another example we'll
create a counter using two buttons we
can increase or decrease our counter
heading to our html file let's create a
label and two buttons
we'll need an opening label tag close it
add a line break
i will set the id of this label to my
label
i'll add some text
just zero
we'll need two buttons
button
close it
the idea of this first button will be
decrease
button
the text will be decreased
and we'll need an increase button
copy this paste it change decrease to
increase
and we have our two buttons
if we were using function declarations
we would need to think of two unique
names to link to these two buttons using
function declarations we would probably
say something like
function
increase
count
and we need a count variable let count
equal zero
we will increment count by one count
plus equals one
and change the text of this label so we
need to select it document dot
get element by id
we are selecting my label
change the inner html equal
to count
then we will create a decrease count
function
function decrease count count minus
equals one
lastly we just need to link these
buttons to these functions there is an
on click event attribute beginning with
the decrease button
take the on click attribute set the
sequel to the appropriate function
decrease count
add a set of parentheses
copy this
paste it for increase button and we will
select the increase count function
let's save and run this
so with this label we can increase it
and decrease it however i think this
would be better with function
expressions we don't need to declare two
functions such as increase count and
decrease count we can assign some
function expressions to these buttons
and then simply forget about them i'm
going to get rid of both of these
functions and we will create some
function expressions let's select this
increase button
i'll just copy what we have here
increase
button
dot
on
click
set the sequel to a function expression
what would we like to do
these two lines of code
increase count by one and change our
label
let's copy this function expression
paste it
do the same thing but with the decrease
button decrease button
decrement count by one and change our
label
we can get rid of this previous code
let's save heading back to our html file
we can also get rid of these on click
event attributes
okay save everything and this should
work we can increase our label and
decrease it and there is no need to
create two unique function names we were
able to assign function expressions to
the event attribute of an html element
so those are function expressions if you
would like a copy of this code i'll post
this in the comments section down below
don't be afraid to smash that like
button leave a random comment down below
and subscribe if you'd like to become a
fellow bro
hey guys in this video i'm going to
explain arrow function expressions which
are represented by well and arrow it's a
compact alternative to a traditional
function expression i'll give you a
whole bunch of examples of where this
could be useful let's create a
traditional function expression which we
learned about in the last topic
i'll create a constant
greeting
and i will set the sequel to a function
expression
function we have an argument
maybe username
console.log
will display a message i'll use a
template literal
hello
then my placeholder user name
so to invoke this function i type the
function name a set of parentheses and i
have one argument a username i'll type
in my first name run this
and this displays hello whatever your
username is
a compact alternative to this function
expression is that we could convert it
to an arrow function expression
we will eliminate these things
eliminate the function keyword after
your arguments add an arrow
and we can eliminate these curly braces
looks good to me does this still work
yes it does
so depending on what arguments you have
if you have no arguments you need just a
set of parentheses
if you have one argument you don't
necessarily need to enclose this in a
set of parentheses
if you have two or more arguments you do
need a set of parentheses
that is one example of the arrow
function
let's try a different example the second
example will have two arguments it will
calculate a percentage
first let's write a function expression
const
percent
equals a function expression there are
two arguments
x and y
x will be the denominator y will be the
denominator and i would like to return x
divided by y
times 100.
let's use console.log
i'll use a template literal for this i
would like to display here's my
placeholder
i'll invoke this function
percent
pass in two arguments
a nominator and a denominator
what is 75
over 100
then let's add percent to the end
so 75
over 100 is 75
what about 80 over 150
53.3 repeating percent in place of a
function expression let's use the arrow
function
so we eliminate the function keyword
keep the arguments add an arrow
and we can eliminate these curly braces
and we don't necessarily need this
return statement
and this still works the same
what about 45 over 50 that is 90
here's one last exercise
we'll reuse the code on the video on
sorting an array of integers in that
example we had an array of student
grades
and these are integers one student has
100
another has 50
90
60
80
70.
if i was using standard functions i
would write something like this
function
descending
there are two arguments x and y
return y minus x
and i will also create a print function
function
we have one argument an element
console.log
element
to sort and display each of these
elements i will use two separate
functions
grades dot sort
pass in a callback descending
and i would also like to print
grades for each
pass in a callback to print
so all of these grades are in descending
order if we were writing the same code
using function expressions i could stick
a function expression within each of
these methods let's turn this first
function into a function expression
cut it
and paste it within the sort method
and we will do the same thing with print
get rid of the name
cut this
and paste it
and that does the same thing but it uses
function expressions in place of
function expressions let's now use the
arrow function we get rid of the
function keyword
add an arrow after the arguments
and we can eliminate these curly braces
and we don't need the return keyword
either let's do the same thing with the
for each method to display each element
get rid of the function keyword
add an arrow after the arguments we can
eliminate the curly braces
and that semicolon
all right let's see if this works
i can't believe it it actually worked in
place of function expressions we were
able to instead use arrow function
expressions it's a compact alternative
to a traditional function expression
it makes your code a lot more readable
so yeah those were a few examples of us
using the arrow function you have your
arguments on one side arrow then some
code you would like to perform so yeah
that's the arrow function everybody if
you found this video helpful please be
sure to smash that like button leave a
random comment down below and subscribe
if you'd like to become a fellow bro
hey guys in this video i'm going to show
you how we can shuffle the elements of
an array this would work perfect for a
card game let's say we have an array of
cards
let cards equal
these will be string representations of
cards we have an ace
a two
i'm not worried about the suit but you
can feel free to add a suit if you would
like i'm just gonna fill in this array
then we have a
jack a queen
and a king so this is our array of cards
to shuffle this array i can create a
function to do that for me
function
shuffle
and there will be one parameter an array
when we invoke this function we need to
pass an array as an argument
shuffle our array cards now to shuffle
this we'll begin at the end i need this
array's length and i will store that
within a variable that we will name
current
index and set this equal to the arrays
length we will begin at the end
and we'll need a while loop
our condition is while
current index does not equal zero now
we'll need a random number between the
beginning of this array up to the length
of the array let's declare random
index
set the sql to
math math.random
times
the arrays length property
then surround this with math.floor
math.floor decrement our current index
by one current index minus equals one so
i'm going to maximize this
we will begin at the end we will swap
this element with another one during the
next iteration
the previous element will be the current
index we will swap this element with
another one chosen randomly we'll
continue this process until we reach the
end of our array then stop then it's a
matter of swapping two elements but
we'll need some temporary storage
let
temp
equal array
at our current index
array
at our current index
equals array at our random index
array
at our random index equals temp
at the end of this function you can
return the array if you like if you
would like to reassign it
i'm going to display all of the cards
the array itself
console.log
cards
so here's our array
every time i run this program these
elements are being shuffled
if you would like the top element that
would have an index of zero
the top card in my deck currently is an
eight
now it's a king
one trick if you would like to deal all
the cards is that you can use the for
each method of arrays
cards dot for each method we can pass in
a callback a function expression or an
arrow function expression
i'll use an arrow function expression we
have one argument let's name this card
arrow
i would like to display that card
console.log card
this will deal all of the cards in my
deck
and every time i run it it's shuffled
so yeah everybody that's one way in
which we can shuffle the elements of an
array if you would like a copy of this
code i'll post this in the comment
section down below and well yeah that's
how to shuffle the elements of an array
in javascript
hey yeah everybody in this video i'm
going to explain nested functions it's a
function inside of another function
think of the topic on nested loops it's
a loop inside of another loop outer
functions have access to inner functions
inner functions are hidden from outside
the outer function they add data
security and they're used in closures
which is a future video topic
so let's begin we'll use traditional
functions and then create some nested
functions i have two variables let
username equal some username
and a variable to hold the amount of
messages that i have like an inbox let
user inbox
equal
zero or some other number i'm going to
create a message to log in like we're
logging into our email
function
login i'll create a function to display
our username
function display
user
name
and another function to display our
inbox
user
inbox when i display my username let's
use console.log
i'll use a template literal
welcome
i'll add a placeholder
user name with the display user inbox
function
we will display how many messages we
have you
have
add a placeholder
user inbox
new
messages
after logging in i would like to invoke
these two functions display username
and display user inbox
and we need to invoke the login function
as if we were logging in welcome bro you
have zero new messages
now a problem with this we have access
to the display username function as well
as the display user inbox function from
outside of the login function meaning
that we don't need to log in in order to
display our username and our inbox so i
can invoke these functions directly
display username
display user inbox and there's no need
to even log in
welcome bro you have zero new messages
to add a little bit of data security i
could place these functions within
another function
so in order to access the display
username function i need to first log in
and the same thing goes with the display
user inbox function
if i attempt to invoke these functions
when they're nested
i don't have access to them it adds some
security in order to invoke these
functions i first need to login
so we'll invoke the login function
and then we have access to the display
username function and the display user
inbox function so yeah those are nested
functions they're functions inside of
other functions the outer function has
access to inner functions
inner functions are hidden from outside
the outer function it adds some data
security and they're also used in
closures which is a future video topic
so yeah those are nested functions if
you would like a copy of this code i'll
post this in the comments section down
below and well yeah those are nested
functions in javascript
hey guys in this video i'm going to
explain what a map is a map is an object
that holds key value pairs of any data
type here's an example we have an online
store we can associate prices with items
constant
store
equals new
map
add a set of parenthesis
a set of square brackets
and within the square brackets we can
create key value pairs add each key
value pair to a set of square brackets
and separate each pair with a comma the
first value is the key the first key
value pair is a t-shirt and the
associated value is twenty for twenty
dollars this is one pair in my map
object let's create another my second
pair
are jeans
they go for about thirty dollars maybe
the third pair in my map are socks
i'll sell them for ten dollars and what
about underwear they're expensive
they're fifty dollars they're very good
underwear okay here is my map object
it's named store to iterate over the
pairs in my map i can easily do this
using the for each method so type my map
name dot for
each
i can pass in a callback a function
expression or an arrow function
expression i'll use an arrow function
expression we have two parameters a
value
and a key
arrow
i would like to display my key value
pairs
console.log i'll use a template literal
i'll add a placeholder
key
and each value
value
and i'll add a dollar sign
so this is what i have currently
this line will iterate and display each
pair of my map and here is each pair
it's kind of like i'm listing all the
items in my store if i need to get one
of these items like i would like to make
a purchase there is a get method i'll
create a variable to store the prices
that are going to add up let shopping
cart i'll set the sequel to zero if i
would like to buy one of these items
there is an associated price and i just
need to access this value so i will take
shopping cart and increment it to access
one of these values i will type the name
of the map store get
and then a key i would like to buy a
t-shirt
so i will get
my t-shirt and let's display our
shopping cart console.log
shopping cart
currently our shopping cart is twenty we
have to pay twenty dollars i would like
to add another item
i want some of that fancy underwear
store dot get underwear my total is now
seventy dollars
twenty dollars plus fifty so that is the
get method here's a few other methods
there's a set method we can add a pair
to our map
store
dot set i would like to add a hat
and the price is 40. it's an expensive
hat it's gucci now when we iterate over
this map we have a t-shirt jeans socks
underwear and a hat that is the set
method we can delete a pair
store dot delete type in the key
hat
and our hat is gone we can check if
there's a key within our map type the
map name
has
and pass in a key do we have any hats
this will return a boolean value so i'm
just going to place this within a
console.log statement
do we have any hats store has hat
false
store has underwear
that's true
that is the haz method and the last one
i'll show you is the size property type
the map name store dot size
i'll put this within console.log
and the amount of pairs within our map
is four so yeah that's a map everybody
it's an object that holds key value
pairs of any data type you can associate
a key with the value one example that we
covered is if we had an online store we
could associate products with prices so
those are maps everybody hey if you
found this video helpful please be sure
to help me and smash that like button
leave a random comment down below and
subscribe if you'd like to become a
fellow bro
alright guys we have finally made it to
object-oriented programming an object is
a group of properties and methods
properties are what an object has like a
name a color a year methods are what an
object can do for example if we're
creating a car object two possible
methods could be drive and break so
let's create some car objects to begin
with i'll create a constant constant car
and this is how we can create an object
within a set of curly braces we can
create some properties which are kind of
like variables this car has a model
property
and we can assign a value
this car is a mustang
separate each property with a comma
let's create a color property the color
could be red
and a year
the year is 20 23.
we can also add some functions too i'll
create a drive function so create a
function name
colon
function parentheses curly braces
when we invoke the drive function we can
do something
i'll display a message
console.log
you drive the car let's create another
function
this will be the
break method so function parenthesis
curly braces
you step on the brakes
and there we go we have a car object
within a set of curly braces you can
assign properties and methods and then
at the end make sure you don't have a
comma an object can have properties what
an object has like a model a color and a
year
and methods what an object can do this
car can drive and it can break to access
an object's properties and methods
follow the object name with a dot if i
need access to the model of this car i
would type the object name
car
dot
model
and i will display this within
console.log but you can assign it change
it do whatever you want with it this
statement displays mustang
if i need the color property i would
type the object name
dot color
which is red
car dot year
is 20 23 if i would like to invoke one
of these methods found within my car
object i would type the object's name
followed by the method i would like to
perform
car dot drive add a set of parenthesis
to invoke it
you drive the car
then we have car dot break
you step on the brakes we can create
multiple objects each with different
properties and methods one way to do
this we haven't discussed classes or
constructors yet we can just create a
new name and we'll rename car as car 1
so we have two different car objects but
i'll change the properties of card too
we'll keep drive and break the same
this will be a corvette
the color is blue and the year is 20 24.
so this car is named car 2. in order to
access this car's model i would type the
name of the object
car 2
car 2. model
car 2.color car 2.ear
car 2 dot drive car 2 dot break
we have a corvette the color is blue
the year is 20 24.
when we invoke the drive method you
drive the car the brake method
displays
you step on the brakes so yeah those are
objects it's a group of properties and
methods that have a name properties are
what an object has methods are what an
object can do they're functions that
belong to an object to access properties
and methods of an object you use a dot
following the object name so those are
objects if you would like a copy of this
code i'll post this to the comment
section down below if you haven't
already please be sure to smash that
like button leave random comments down
below and subscribe if you'd like to
become a fellow bro
hey yeah everybody in this video i'm
going to explain the this keyword all it
is is a reference to a particular object
but it depends on the immediate context
where you use the this keyword here's an
example i have two objects car one and
car two car one is a red mustang car two
is a blue corvette each has a similar
drive function
you drive the car
in place of the word car why don't we
replace the word car with the model of
each car object i'm currently using a
template literal i could insert the
model of my car will create a
placeholder
this is what happens if i just type
model you think this would work because
this is like a variable right and let's
do the same thing with cartoon i will
invoke these two methods
car one dot drive
and cartoon.drive
okay we ran into an error model is not
defined at object drive within an object
if i would like to use one of these
properties i would need to precede this
property with the this keyword in place
of model i would type this dot model and
do the same thing with cartoon this
dot model
let's run this again you drive the
mustang you drive the corvette this
refers to the object that we're
currently working with the immediate
context within this object the immediate
context of this is car1 in this other
object the immediate context of this is
car two within an object when using the
this keyword just imagine that we're
replacing this with the object name
car1.model and cartoo.model
this will do the same thing so this is
just a reference to the object we're
working with let me show you what
happens if i use the this keyword
outside of any objects i will
console.log
this so what the heck is this we're
actually within the context of a window
object if you use the this keyword
outside of any objects that you declared
well then this refers to instead the
window object because that is the
immediate context and i can change one
of these properties if i wanted to let's
change this name property i would type
this
dot name
equals my
cool window
so i can run this
let's find that property
there's my name property my cool window
if i would like to access this property
directly i would follow this with dot
name
my cool window
so that's the this keyword everybody
it's a reference to a particular object
just imagine that we're replacing the
keyword this with the name of an object
hey if you found this video helpful
please be sure to smash that like button
leave a random comment down below and
subscribe if you'd like to become a
fellow bro
hey everybody in this video i'm going to
explain classes a class is a blueprint
for creating objects within a class we
can define what properties and methods
that type of object should have and they
typically contain a constructor to
assign some unique properties but we're
going to focus on constructors in the
next video i had some trouble
brainstorming some possible class ideas
that wouldn't utilize a constructor but
one that i thought of could be a player
we can create a player class as a
blueprint and create some player objects
so to create a class we will type class
player
curly braces and we can define a
properties and methods that all player
objects will have its blueprint maybe
each player has their own individual
score and i will set this to zero each
player will start at zero each player
has a pause method now when you declare
a method within a class you don't
necessarily need that function keyword
when a player pauses we will display a
message console.log
you paused
the game and maybe an exit method
console.log
you
exited the game now to utilize this
class to create an object we would need
an object name let's say constant
player1 this will be the first player
that joins now to utilize this class to
create a player object we use the new
keyword followed by the name of the
class
player
add a set of parentheses and a semicolon
we have created player one player one
has a score property and two methods
pause and exit let's display what player
one score is
console.log
player1.score
and that is currently zero but you can
adjust its score player one dot score
plus equals one he scored a point player
one now has one point player one dot
pause method
you pause the game and player one
connects it player one dot exit
you exited the game we can reuse this
class to create multiple players i'll
create player two constant player two
equals new player i'll display player
two score
and we will have player two exit the
game
player one has one point player two has
zero points player one invoked the pause
method player two invoked the exited
method you can keep on reusing this
class as much as you would like this
time i would like four players so same
process as before declare a unique
object name set the sql to use the new
keyword the name of the class that's a
class it's basically a blueprint for
creating objects we can create as many
objects as we want and within this class
we define what properties and methods
that each object created from this class
should have and in the next video we're
going to discuss constructors so we can
assign some unique properties to each
object so those are classes hey if you
liked this video let me know by smashing
that like button leave a random comment
down below and subscribe if you'd like
to become a fellow bro
all right everybody constructors a
constructor is a special method of a
class its job is to accept arguments and
assign properties or anything else you
would like to do when you instantiate an
object let's create a student class
class
student to create a constructor we will
type
constructor
parentheses curly braces now when we
create an object a student object in
this example we can assign some
properties each student has a name an
age and a gpa within the constructor we
can assign some of these arguments to
properties of this class we can state
this
dot
name
equals name
this dot age equals age
this dot gpa equals gpa
there we go there's our constructor you
can also add additional properties or
methods outside the constructor let's
add a study method
study
let's display
i'll use a template literal
this dot name
is studying
okay let's create some student objects
we can use var let or const i'll use
const
student one
equals new
student
within our constructor we have three
parameters that means that we need to
pass three arguments a name an age and a
gpa so that we can assign these
properties the first student will be
spongebob that's his name his age he'll
be 30 and his gpa he has a 3.2 gpa and i
can display these console.log
student1 dot name
his name is spongebob
age and a gpa spongebob his age is 30
his gpa is 3.2 and for fun let's invoke
the study method
student one dot study
spongebob is studying
now we can reuse this class as a
template to create other students and
pass some unique arguments to assign to
its properties
let's create student 2
student 2 equals new student the
student's name will be patrick
he will be 35 years old his gpa is 1.5
and we have access to student two's
properties and methods
student two dot name age gpa
and he has his own study method
okay patrick is 35 his gpa is 1.5 and
patrick is studying we can reuse this
class to create as many students as we
like
so lastly let's create one last student
student 3
student 3 will have a name of sandy
sandy will be 27
and sandy's gpa is of course a 4.0
student 3 has its own unique properties
and methods
a name age gpa
and study method we have sandy she's 27
her gpa is 4 well 4.0
and she has her own study method sandy
is studying so that's a constructor it's
a special type of method within a class
it accepts arguments and assigns
properties when you construct an object
so those are constructors hey if you
haven't already please be sure you smash
that like button leave random comments
down below and subscribe if you'd like
to become a fellow bro
hey guys in this video i'm going to
explain the static keyword a member that
is static whether it's a property or a
method belongs to a class and not any
objects created from that class in this
example i have a class car and a
constructor when we create a car object
we can pass in a model of a car so i
have three car objects suppose i would
like to keep track of how many cars i
have created we're entering some cars
into a race well we could create a
property to keep track of how many cars
that we have instantiated let me show
you why we would want to make this
static so we have a property
number
of cars and i will set this equal to
zero within the constructor we can add
additional code every time we create a
car let's increment cars by one number
of cars plus equals one now i will
precede number of cars with the this
keyword so what happens when we display
number of cars for each car
console.log
car one dot number of cars
car two car three
so the total number of cars within our
race is one i guess so the reason why
number of cars is in three is because
each car object has their own number of
cars variable each car object can share
the same property or method and we would
precede that property or method with the
static keyword instead of each car
having their own copy the car class
itself has the only copy then to
increment number of cars by one in place
of the this keyword i will use the name
of the class car the car classes number
of cars will be incremented by one every
time we call the car constructor there's
a problem here i'm accessing the number
of cars property but no one object from
this class has ownership of this
variable to access the static property
of number of cars i will use the name of
the class car
car dot number of cars how many cars
have we created we have created three
cars and i could create another
car for
is a
ferrari
now we have four cars
or even
five cars
a static property is useful for caches
or anything with a fixed configuration
we also have the capability to make
methods static it's more or less useful
for utility functions now we would like
to start our fictional race we could
create a start race method
start
race
console.log
three
two
one
go so currently this is not static so
any one of these cars can begin the race
on their own terms
car one wants to begin the race start
race
three two one go so i'm going to make
this a static method it's more or less a
utility function
so precede the method name with static
now to invoke this start race method
type the name of the class car car dot
start race three two one go
basically that's the static keyword
anything that's static belongs to the
class and not the objects one place
where we do see static methods is within
the math class say i need to round
math the name of the class dot round
method
i wouldn't need to create a math object
such as const math1 equals new math that
would be silly to access the round
method i would just type the name of the
class
dot round it's a static method that's
the static keyword everybody if you
would like a copy of this code i'll post
this to the comment section down below
and well yeah that's the static keyword
in javascript
hey y'all everybody in this video i'm
going to explain inheritance inheritance
is when a child class can inherit all
the methods and properties from another
class how is this useful let me give you
a demonstration our job is to create
three classes a class for rabbits fish
and hawks three specific kinds of
animals so we have class
rabbit
each rabbit will have a boolean variable
called alive and i will set this to true
if you're a rabbit object you're alive
and a name equal to rabbit
each rabbit should be able to eat
console.log
i'll use a template literal
this at a place holder
this dot name
is eating and all rabbits should be able
to sleep
sleep this
this dot name
is
sleeping
and one more how about run
run this this dot name
is
running this is our rabbit object so
let's copy this class paste it
and convert the second class to fish
alive will remain true name will be fish
eat and sleep will remain the same but
fish they don't run well because they
don't have legs they will instead have a
swim method
this this dot name is swimming
copy all this code
and we will create a hawk class this
will be the last class class
puck name is hawk
hawks will be able to eat and sleep in
place of a swim method they will have a
fly method
this this dot name
is
flying we have three separate classes
rabbit fish and hawk but with
programming we don't like to repeat code
and we're repeating quite a lot of code
within each of these classes each class
has an identical eat and sleep method as
well as in a live boolean variable so to
eliminate the need for us to repeat some
of this code we can simply create a
class and all of these individual animal
classes can inherit some properties and
methods from that one class so what do
all of these classes have in common and
a live boolean variable and an eat and
sleep method so why don't we create a
separate class and each of these classes
will inherit from that one class this
will be a parent class rabbit fish and
hawk will be children classes
so let's create class
animal that's descriptive of what they
all have in common class rabbit will
extends the animal class rabbit is the
child class animal is the parent class
do the same thing with fish
and hawk
any properties or methods that all of
these classes have in common we can put
within the parent class they each have
an alive property set to true we can
eliminate that for each class and stick
it within the parent class there's no
need to repeat this variable each time
they each have the same eat and sleep
methods
we can copy those
paste it within the animal class
and then eliminate each of these methods
within the children classes
so any properties or methods that are
unique to these children classes you
should keep within the children classes
rabbit inherits these properties and
methods from the animal class
fish does the same as well as well as
hawk and you can see that we eliminated
a lot of lines of code there was no need
for us to repeat ourselves let's create
some animal objects
const rabbit equals new rabbit
fish equals new
fish
hawk equals new hawk let's test to make
sure that each of these children classes
does in fact have access to these
properties and methods rabbits should
have in a live boolean variable
if you're a rabbit you're alive
congratulations console.log rabbit.alive
that is true
even though within the rabbit class we
didn't write in a live boolean variable
within the rabbit class itself it
inherited one from its parent and i bet
rabbits can also
eat
i bet they can sleep
and they can run
yep the rabbit is eating sleeping
running so let's test this with fish
fish not alive fish.eat fish.sleep what
would happen exactly if i attempt to
invoke the run method of fish fish.run
is not a function so this run method
belongs to the rabbit class fish don't
have a run method but what they have in
common are those eat and sleep methods
fish do have a swim method so the fish
is eating the fish is sleeping the fish
is swimming and let's test hawk
hawk dot alive hawk.e hawk.sleep
hawk.fly
okay true this hawk is eating this hawk
is sleeping this hawk is flying so
that's inheritance everybody a child
class can inherit all of the properties
and methods from a parrot class if you
have multiple classes that all have the
same properties and methods you could
stick those properties and methods
within a parent class and there's no
need to repeat those properties and
methods if they're identical not only
does this eliminate repetition when
you're coding but if you need to make
any changes to one of these methods it's
all in one place if my boss says i need
to change the eat method to
this this dot name is eating to
hunting i just have to make this change
in one place if we had an eat method
within each of these classes i would
have to go to each individual class and
make that change manually it's not bad
if there's three classes but imagine if
you had hundreds that would be a lot of
unnecessary work when you could just
make that change in one place so that's
inheritance everybody if you would like
a copy of this code i'll post this in
the comments section down below if you
haven't already please be sure you've
smashed that like button leave random
comments down below and subscribe if
you'd like to become a fellow bro
hey guys in this video i'm going to
explain the super key word the super
keyword when using inheritance refers to
the parent class
it's commonly used to invoke the
constructor of a parent class here's an
example i have three children classes
rabbit fish and hawk they all inherit
from the animal parent class suppose we
have a constructor within each of these
child classes
constructor rabbits will have these
three properties
a name
an age and a run
speed
so to assign these properties when we
instantiate a rabbit object we could
assign this dot name equals name
this dot age
equals age and this dot run speed
equals run speed
i'll copy this constructor
paste it within the fish child class
fish well they don't have a run speed
but they will have a swim speed property
swim speed
this
swim speed equals swim speed let's copy
our constructor paste it within hawk
change swim speed to fly speed
this fly speed equals fly speed let's
create some of these objects
const rabbit equals new
rabbit we have to pass in three
properties a name
an age and a run speed for the name
we'll say rabbit
age one one for one year old
and a run speed of 40 kilometers per
hour i don't know if that's accurate i
just made up a number
okay let's create a fish object
fish equals new
fish
the name is fish the age will be
i guess two
swim speed 80 kilometers per hour okay
then we have
hawk equals new hawk
pass in a name
hawk
and age maybe three and a fly speed
200 kilometers per hour
just to test everything i'm going to
display my rabbit's name
age and run speed
rabbit dot
name rabbit dot age
and rabbit dot
run
speed
okay let's take a look
what the heck so we encountered an
uncaught reference error must call super
constructor in derived class before
accessing this so if we have any
children classes and those children
classes have constructors we would want
to invoke the constructor of a parent
class one of the reasons why this would
be useful is that within each of these
constructors we're repeating some code
this dot name equals name and this dot
age equals edge but the run speed swim
speed and fly speed are all unique to
each of these classes to promote code
reusability we can call the constructor
of a parent class to assign the name and
age properties so within the animal
class i will create a constructor
we will have a name and age property and
then we'll assign them
this dot name equals name
this dot age equals age
we can eliminate these two lines
and when we construct a new rabbit
object we will first invoke the
superconstructor so you type super
then pass your arguments to the
superconstructor we will pass our name
and age and we can do this with the
other constructors
this eliminates some code repetition
and this should work so we have our
rabbit we have our name rabbit age is
one year old and the speed is 40
kilometers per hour let's try this with
fish fish dot name fish dot age fish dot
swim speed
the name of this fish is fish this fish
is two years old swim speed of 80. and
in our last example we have hawk
hawk.name hawk.h hawk.flyspeed
the name is hawk
this hawk is 3 years old and has a fly
speed of 200 kilometers per hour so the
super keyword refers to a parent class
it's commonly used to invoke the
constructor of a parent class it helps
with code reusability we could write
this code once and simply reuse it by
invoking the superconstructor of the
parent class then if any class has any
unique properties you can assign those
unique properties within the constructor
of each of these child classes so that
is the super keyword it just refers to
the parent class if you would like a
copy of this code i'll post this to the
comments section down below and well
yeah that's the super keyword in
javascript
hey yeah everybody in this video i'm
going to explain getters and setters
let's begin with getters to create a
getter you use the get keyword its job
is to bind an object property to a
function when that property is accessed
here's an example let's create a class
car class
car
i'll create a constructor constructor
we'll have one parameter power this will
be in
horsepower this dot power equals power
when i create a car object let car equal
new car i will pass in a unit for power
this will be in horsepower 400
horsepower is good
then i will display this console.log
car.power
my car has 400 horsepower one thing i
don't like about how my code is written
is that when i'm displaying the car's
horsepower there's no unit of
measurement when i display this property
i could add on
car.power plus
hp for horsepower but i have a better
idea let's use a getter when we get this
property we can add some additional
logic i will type get the name of the
property power
parentheses curly braces when we access
this property we will instead invoke a
function we will return
this dot power
now there's a couple issues with this
when i run this first we have a type
error cannot set property power of car
the property name and the getter cannot
have the same name a common naming
convention with properties of objects if
you have getters and setters set up is
that you take the property name and
precede it with an underscore this lets
other developers know that this is a
protected property and you probably
shouldn't mess with it now if i run this
we have another issue
uncaught range error maximum call stack
size exceeded that's because when we
invoke this getter we're returning this
dot power again we're invoking the
getter method from inside of it we will
instead return this dot underscore power
underscore power is the protected
property now when i run this it displays
my number 400 by associating a protected
property with only a getter this
protected property is read-only and not
writable if i was to take car.power and
set this to like a gajillion and i
display my car's power well it's still
at 400 we do not have direct access to
this property i mean theoretically you
could set car dot underscore power to a
kajillion but developers know that if
you see underscore than a property name
that means it's protected and you
shouldn't mess with it at all another
thing that we can do with getters is
that we can add some additional logic
instead of just returning this.power
let's add horsepower to the end
i'll place this within a template
literal
and add hp for horsepower
so when i display my car's power
it's 400 horsepower so that's a few
benefits of getters is that one it
increases data security and two you can
perform some additional logic when you
access a property directly to use a
getter you type the object name followed
by the getter name it appears to be no
different from accessing that property
directly we don't need to invoke a power
method you just type power as if it's a
property let's create a protected
property for gas
within my constructor i'll set this
dot underscore gas
to some amount of gas in liters perhaps
we're selling cars and each car will
have 25 liters of gas to start with then
to display my gas i can use a getter
get
gas
return this dot underscore gas
the unit of measurement will be liters
let's display my car's power
and its gas
25 liters let's add some additional
logic along with the gas level i would
like to display the percentage of what
my tank is at so zero percent would be
empty 100 would be full i'll return a
template literal
what about
this dot
underscore gas
divided by maybe some max tank size like
50 liters
times 100
percent
if my guess level is at 25 well then my
tank is half full and i can change this
to a different number like 50. now my
tank is completely full
or it's empty
now let's work on setters setters bind
an object property to a function when
that property is assigned a value with
my power property i don't want anybody
to mess with that that's why i only have
a getter but with the gas level i would
encourage people to change the gas level
they would want to be able to fill their
tank i'll create a setter set
gas
we'll need some argument i'll name this
value to fill my car with gas i can take
this dot
gas property equals value since gas has
a setter that means it's writable i'll
take my car's gas property and set the
sql to some value as if i'm filling the
tank currently there's no additional
logic within this gas setter a user
could theoretically add like a kajillion
liters of gas
now my gas is like 2 billion percent
full i might want to limit that i'll
check to see if our value that we
receive
is greater than maybe 50. so that will
be the max tank size if the value is
greater than 50 then let's set value
equal to 50 to limit it
if we attempt to add over a billion
liters of gas
it will be capped at 50. or possibly
somebody will set this to a negative
number negative 100 liters
else if value
is less than zero
value
now equals zero
there now our tank is empty so yeah
everybody those are getters and setters
they bind an object's property to a
function when that property is accessed
in the case of a getter or assigned a
value in the case of setters so those
are getters and setters everybody if you
would like a copy of my code i'll post
this in the comment section down below
and well yeah those are getters and
setters in javascript
hey guys in this video i'm going to show
you how we can pass objects to a
function as an argument i have a class
car and we have three car objects each
car has a model year and color how could
passing objects to a function be useful
i need a function to display all of the
information for each car so let's create
a function
function
and we could name this display
info if we're accepting an object as an
argument we need a matching set of
parameters i think we should just name
it simply car all lowercase remember
when you pass an object to a function
the parameter name is kind of like a
nickname that you're giving it
temporarily then to invoke this function
i will type the function name display
info and pass a car object as an
argument i would like to display car
one's info within this function let's
display this car's model year and color
car
model
year
and color
okay let's see if it works yeah
with this car object the model is a
mustang the year is 20 23 the color is
red we can pass a different object as an
argument this time how about car two
display info card two
car two is a corvette the year is 2024
and the color is blue
then car three
is a lambo the year is 2022 and the
color is yellow let's create another
function to maybe change the color of a
car and we will have two parameters
function
change color
we will accept a car object
and a color we will take
car
dot color set is equal to
whatever color we receive as an argument
let's change the color of our lambo so i
will invoke the change color function
and i will pass in two arguments a car
and a color
car three
and let's change the color to gold and
then display it and the color of our
lambo is now gold and not yellow that's
how to pass an object to a function when
you invoke a function just pass the name
of an object as an argument and with the
parameter name just find a name of
what's descriptive of what you're
accepting as an argument so that's how
to pass objects as arguments if you
would like a copy of this code i'll post
this in the comment section down below
if you haven't already please be sure to
smash that like button leave a random
comment down below and subscribe if
you'd like to become a fellow bro
hey guys in this video i'm going to show
you how we can create an array of
objects in javascript i have a class car
and we have three car objects car one
cartoon car three each car has a model
year and color as well as a drive method
let's come up with a descriptive name of
this array
what about cars
then with creating arrays you use a pair
of straight brackets what would we like
to add to this raised elements well the
names of our objects car 1
card 2
and car 3. let me show you what happens
when we display one of these elements
console.log type the name of the array
followed by an element number the first
element has an index of zero because
computers always start with zero and we
have our car object but if you need one
of these properties or methods you would
follow the array name and the index
number dot and then a property or method
so at index 0 of our array cards i would
like to access the model property the
first element of this array has a model
property of mustang if i were to repeat
the process for cars at index of one and
two those respective models are a
corvette and a lambo if you need to
access a property or method of an object
that's within an array you type the
array name and index number followed by
dot then a given property or method just
for practice let's invoke the drive
method of each of these cars so i would
type the array name and index number
follow it with a dot then a property or
method i would like the element at index
zero within this array to use the drive
method let me get rid of these lines
okay you drive the mustang let's do that
with the other elements one and two
you drive the mustang you drive the
corvette you drive the lambo just as a
challenge let's create a function that
will loop over the elements of this
array and invoke the drive method of
each element we're going to have a race
we need a function to start our race and
have every car use its drive method so i
will create a function let's name this
start
race
say that we need to pass our array of
objects as an argument we'll need a
matching set of parameters i will name
this parameter cars and i would need to
loop through all of the elements within
this array i can use a4 loop for that
let's say const
car of cars car is the current element i
need each car to use its drive method
then we need to invoke this function
start race then we can pass in our array
of objects cars
you drive the mustang you drive the
corvette you drive the lambo hey let's
add another car
car 4
is a ferrari
the year is 2025.
the color is
white so let's add this object to our
array
car four
now we have four cars in our race
you drive the ferrari so yeah that's an
example of an array of objects it's a
useful programming technique because you
can keep all objects organized within an
array so that's an array of objects if
you would like a copy of this code i'll
post this in the comments section down
below if you haven't already please be
sure you smash that like button leave
random comment down below and subscribe
if you'd like to become a fellow bro
hey guys in this video i'm going to
explain anonymous objects they are
objects without a name a benefit is that
using anonymous objects requires less
syntax and there's no need for unique
names however a downside is that we do
not have direct access to one of these
objects so here's an example we're going
to create an array of cards each card
will be an object which we'll create
with a class
class
card
i'll add a constructor
each card will have both a value and a
suit
this dot value equals value
this dot suit equals suit
suppose i would like to make a card
normally if we're using names not
anonymous objects i would declare a
unique name like let card one
equal new then the name of the class to
instantiate an object card for this
object i need to pass in a value and a
suit this card will be the ace of hearts
a
the second argument will be
hearts
i'll create a couple other cards
card two will be named well card two
card two will be the ace of spades
card three
ace of
diamonds
card four will be ace of clubs
i'll just create four more cards i'll
copy all this
paste it
we have cards five
six seven eight
these cards will be two of hearts two of
spades two of diamonds and two of clubs
i'll just stick with eight cards for
this example i don't need a whole deck
of 52 cards to explain this so we have
eight cards i'm going to add them to an
array
let
cards equal
we'll add card one
card two
and the others
that's good enough to access one of
these properties of one of these cards i
can either do so directly by the object
name or by an array element
so if i were to display console.log
one
dot value
plus card one dot suit
this would display ace of hearts
or i could access this object indirectly
via the array
that would be my array cards
at index of zero dot value plus
cards at index of zero
dot suit
this would do the same thing
with this first statement we're
accessing this object directly by its
name in the second statement we're
accessing this object indirectly via an
array index you know this does in fact
work and all but i would write this a
different way there's no need to create
all of these unique names that's a lot
of work if we were to rewrite this using
some anonymous objects this is what we
can do we'll get rid of everything
before the new keyword
we've created eight cards but we have no
way to reference them in place of adding
some object names directly to our array
when we instantiate a card object we can
actually place that within the array
we'll add a new card
with these properties
and that will be the first element
then let's add the others
i'll speed up the footage
this would do the same thing however we
have a reference error card 1 is not
defined so there is no card 1 anymore my
interpreter doesn't know what the heck
card 1 is that's because we never
declared it so using anonymous objects
we have no way to directly access these
objects by a name because well they
don't have one in order to access the
properties of an object i would need to
do so indirectly
since these objects are within an array
i can reference them by an index number
cards at index 0 would be the ace of
hearts
cards at index of 1
is my ace of spades
and then 7
is my two of clubs so you can see that
this still works and it's a lot less
syntax sometimes it would be impractical
to give an object a name if you're never
ever going to reference it directly for
fun let's display all of the cards
within this deck using the for each
method
cards dot for each
we will take card as an argument arrow
function
console
dot log
i'll use a template literal
let's take card
dot value
and also display
card dot suit
there here are all the cards in my deck
displayed so yeah everybody those are
anonymous objects they're just objects
without a name you don't need to declare
a name to create an object names are
just used as a reference as storage the
downside is that you don't have direct
access to an anonymous object you would
typically store them within something
like an array and some benefits is that
there's less syntax it reduces the size
of your code and there's no need to
create some unique names so those are
anonymous objects everybody if you would
like a copy of this code i'll post this
in the comments section down below and
well yeah those are anonymous objects in
javascript
hey guys in this video i'm going to
explain error handling errors are
objects with a description of something
that went wrong encountering an error
will halt the execution of your program
we would like some way to gracefully
handle these errors without interrupting
our program errors can happen for one of
a few reasons a few examples would be
you can't open a file you lose
connection to a device a user types in
some incorrect user input or a type
error one example of type error is that
we mistype something instead of saying
console.log maybe we misspell log as leg
console.leg well we encountered an
uncaught type error console.lag is not a
function if an error happens while your
program is running it can cause your
program to stop we would like to
gracefully handle these errors and one
way to do that is to surround any
dangerous code with a try block code
that could cause an error is considered
dangerous accepting user input is almost
always dangerous because you don't know
what they're going to type in so let's
create a try block and add some
dangerous code now if you have a try
block you need to follow this with a
catch block
and there's one argument an error if
something goes wrong we will do
something else
in fact i will display whatever our
error is console.log
error again if i type console.leg
while this won't interrupt my program it
will simply just display the error type
air console.lag is not a function so we
don't get that big nasty red error
message sometimes in your program
something will go wrong but it won't
generate an error here's an example
let's accept some user input we'll ask a
user to type in a number let's declare
variable x x equals window dot prompt
enter a number when we accept user input
it's of a string data type we'll need to
convert that to a number
okay at the end let's display a message
console.log
i'll use a template literal
x is a number
okay let's run this enter a number well
pizza is my favorite number i'll enter
that in so even though this didn't cause
any errors it's definitely going to
cause problems for me in my program
something is going to go wrong using
this throw keyword i can execute a
user-defined error but we'll need to
know when to use it i'll add an if
statement if and the condition is is
not a number
pass in x if this is true then we will
throw an error or an argument to be used
as an error so we're just displaying a
message in this example
that wasn't a number
so now when i run this again i'll enter
pizza in
that wasn't a number what if the user
doesn't type in anything they just press
the ok button
0 isn't a number so that means they
didn't type in anything we can throw a
user defined error we'll need another if
statement
if
x is equal to an empty string
then throw
that was
empty
let's try this again i'll just press ok
that was empty so an error is an object
with a description of something that
went wrong there may be times when
something will go wrong in your program
but it doesn't raise an error like
somebody types in something that you
didn't anticipate you can use this throw
keyword to execute a user defined error
now there's one more statement that we
can add to this you can add a finally
block finally we'll always execute
doesn't matter if your code is
successful or unsuccessful if there's an
error here's one use of the finally
block let's say we open a file after we
open the file and are done with it we
would like to close it but if we open
the file and cause an error we would
still like to close it so the finally
block is good for any sort of cleanup
but we're not going to be working on
opening files let's just display a
message
console.log this always executes
let's run this again i'll enter in a
number 123. 123 is a number this always
executes so even if our code is
successful we will still execute the
finally block let's enter in something
that's not a number like the word pizza
that wasn't a number this always
executes so yeah everybody those are a
few ways to handle errors and error is
an object with a description of
something that went wrong sometimes
things will go wrong and they don't
cause errors if that's the case you
would want to use this throw keyword and
it will execute a user defined error or
a message or value that can be used in
an error so that's some basic error
handling if you would like a copy of
this code i'll post this to the comment
section down below and well yeah that's
error handling in javascript
hey yeah everybody in this video i'm
going to explain the set timeout method
it invokes a function after a number of
milliseconds it's an asynchronous
function meaning that it doesn't pause
the execution of your program for my
example we're going to be annoying we're
going to spam some alert messages after
a given amount of milliseconds let's
create a few functions
function
will display three messages this will be
the first message
first
message i'll create an alert
alert
i'll use a template literal
buy this course for
five hundred dollars okay let's create
two more messages
second message
third message for the second message
let's say that this is not a scam the
third message will be
do it
i would like to invoke these functions
after a given amount of time i will use
the
set timeout
method
so we pass in a callback a function
expression
or an arrow function expression just to
keep things simple i'm going to pass a
callback let's begin with the first
message that's the first argument the
callback is the first argument
and then a given amount of milliseconds
we would like this function to execute
after three thousand milliseconds three
seconds we will alert the user to buy
this course for five hundred dollars it
is possible to have multiple set timeout
methods executing concurrently let's
invoke the set timeout method two
additional times
after about
maybe six seconds we will invoke the
second message function
then we will invoke the third message
function after nine seconds
okay let's try
buy this course for five hundred dollars
this is not a scam
do it if at any time you ever need to
clear or cancel your set timeout method
you can use the clear timeout method
but i'm going to link this to a button
let's create a button within our html
document
button
id of my button
and the text will be by if we want to
buy that fictional course that we're
selling
i need to select this button by its id
document
dot
get
element by id
the id was my button set the on click
attribute equal to a function
i will invoke the clear
timeout method
but we need to pass in the id of a timer
when you invoke the set timeout method
it will return an id so let's store that
within a variable
let
timer 1
equal set timeout
then let's create timer two
and timer three
so we will pass these variables as
arguments to the clear timeout method
so copy and paste timers one two and
three let's alert the user so if they
click on this buy button they buy our
fictional course
thanks for buying
buy this course for five hundred dollars
i'll click buy
thanks for buying that will cancel and
clear the set timeout methods
if you need to pass arguments to a
function you can list those after the
milliseconds argument let's create
variable item
we would like to sell
how about a crypto currency this time
we will list a price let
price equals 420 69. so i'm going to
pass these two variables as arguments
item
and price when i invoke the first
message function but we need parameters
item and price
let's actually use these buy
this
item
for
price
buy this cryptocurrency for 4 20 69. so
yeah everybody that is the set timeout
method it invokes a function after a
number of milliseconds it's an
asynchronous function it doesn't pause
the execution of the rest of your
program if you need to perform a task
after a given amount of time you can
invoke the set timeout method hey if you
found this video helpful please be sure
to smash that like button leave a random
comment down below and subscribe if
you'd like to become a fellow bro
hey guys in this video i'm going to
explain the set interval method the set
interval method much like the set
timeout method it invokes a function
repeatedly after a number of
milliseconds it's an asynchronous
function it doesn't pause the execution
of your program let's create a count up
timer i will declare a counter let
count set the sql to zero and we will
accept some user input let max equals
window
dot prompt
count up to what number i'll need to
convert the user input to a number
because it's normally of the string data
type when we accept user input now let's
invoke the set interval method
set
interval
we can pass in a callback a function
expression an arrow function expression
let's just pass a callback to keep
things simple count
up after how many milliseconds would we
like to repeat this function maybe one
thousand for one second let's declare
this function
function
count up
i will increment count by one this will
be our counter and we will display
whatever count is
console.log
count let's stop if
count
is greater than or equal to
max the number that we enter in the user
input to stop the set interval method we
can use the clear interval method
however as an argument we need to pass
in the id of the set interval method so
we can actually assign that
constant
let's name this my timer equals set
interval my timer is storing the id of
the set interval method i'll pass that
as an argument to the clear interval
method and when i run this we should
count up to a number that we set count
up to what let's count up to ten
press okay
okay we begin at one two three four
and we should stop at ten
yeah if you ever need to pass arguments
to a function a callback maybe a lot of
these variables are within a function so
if i need to pass max i can add that as
an argument then make sure to have a
matching set of parameters so that is
the set interval method everybody it
invokes a function repeatedly after a
number of milliseconds if this video
helped you out please be sure to smash
that like button leave a random comment
down below and subscribe if you'd like
to become a fellow bro
hey guys in this video i'm gonna discuss
date objects date objects are used to
work with dates and times to create a
date object we just call the date
constructor let
date equal new date
and then we can display the date
console dialogue
date and here's the current date and
time including time zone although it's
not that readable we can actually change
that i will set the date equal to date
dot
2
locale
string method
and that is a lot more readable hey for
fun within our dom let's create a label
and update the label with the current
date and time so within my html file i'm
going to create a new
close it
i'll give this a unique id my label is
fine
and i will change the inner html of my
label
document dot
get
element by
id
pass in a unique id my label change the
inner html equal to
date
yeah it's pretty cool right now with the
day constructor if you don't pass in any
arguments date will equal the current
date and time however if we pass zero as
an argument zero is a reference point
for us this is known as the epic it will
be some date around the year 1969.
imagine this is the date where time
began not really but just imagine it
this is a reference point for us within
the day constructor we can pass an
amount of milliseconds as an argument so
if i pass in i don't know how many
milliseconds that is this will create a
new date 10 million milliseconds after
this date the starting point so 10
million milliseconds after our epic is
the same day but 8 o'clock at night so
i'm just gonna pass in some random
numbers and see what dates we get
this number equates to the date
september 8th 2001
8pm and let's see what this is
okay now we're in the year 33 000. so
you can pass an amount of milliseconds
to the date constructor but zero is a
reference point there are additional
arguments you can pass too the first
argument is a year let's pick the year
2023 the next argument is the month zero
corresponds with january february
corresponds with one then you just
follow that pattern i'll pick uh let's
say january so zero the next arguments
for the day
the hour
minutes
seconds
and even milliseconds so after passing
how many arguments do we have here i
think seven
the current date and time is january 1st
2023 about two in the morning if it's
easier for you you can even pass in a
string representation of a date and time
how about january
1st
2023
midnight
that's another option available to you
too you can even get properties from a
current date if you need the year we
could assign that to a variable let year
equal
date dot get
full year
and let's display this
so the current year is 2022
day of the month
day of month
the corresponding method is get
date
let's display day of month
and it is the seventh currently
day of week
get
day
sunday is zero monday is one tuesday is
two you just follow that pattern since
day of week is one that means it's
monday we have access to the month
get month
the month is currently one january is
zero february is one march is two you
follow that pattern we have access to
hours
get
hours
the current hour is 10
this is in military time so the possible
hours are between 0 and 23
minutes
get minutes
so the current time for me is six
minutes after 10
seconds
get seconds
every time i refresh this page you can
see that the seconds is going up and
even milliseconds let's name this
variable ms for short
get
milliseconds
and this is pretty much updating every
time i refresh the page so if you need
one of these properties of a date you
can use an associated method you can
also set these properties too i would
like to set the year of my date date
set full year i'll pass in the year 2024
and let's display our date
so for me i'm recording this on february
7th but the year is changed to 2024
there's also set month
date dot set month i'll change the month
to december so that would be 11 december
7th 2024 you can set the day of the
month
date dot set date i'll change this to 31
december 31st 2024 we have set hours
date dot set hours let's move this to 12
that would be 12 p.m and 23 would be 11
p.m same thing applies four minutes set
minutes what about one seconds set
seconds
i don't know 30 and even milliseconds
although we're not displaying it
currently date dot set milliseconds and
pass in some amount of milliseconds so
those are various set methods you can
set a property of a date we can even
create our own custom functions to
format a date and time so i'm going to
get rid of this line let's create a
function to format the date first
function
format date
we will accept a date as an argument
let's create a few variables for the
year month and day
let year equal and we can get the year
date dot get
full year
let month
equal date dot get month
and let day
equal date
dot
get
date so let's return a string
representation of the year month and day
return i'll use a template literal so if
you would like the month first like
what's displayed in my web browser we
can put the month first
then the day next
end of the year
when i update my label i will invoke the
format date function that i created and
pass in our date
there we go remember though that january
is zero and february is one but
whoever's using this program probably
won't know that let's add one to our
month
there now it's february and for some
additional practice let's create a
format time function
function
format time
we have one parameter a date
let hours equal date dot get hours
let minutes
equal date dot get minutes
let seconds
equal date dot get seconds
let's return a string representation of
the hours minutes and seconds i'll use a
template literal
hours
minutes
seconds
let's invoke the format time function
that we created
yeah and that's my current time but it's
currently in military time let's change
it to standard let's add am or pm let i
don't know what to name this variable am
or
pm i guess
equals and i'll use the ternary operator
our condition is we'll check if hours
is greater than or equal to 12
question mark if that's true we will
return pm if it's false we'll return am
and i will display
my variable am
or pm
and it is currently am the hours are
still currently in military time so to
convert that to standard this is one way
in which we can do that let's reassign
hours equal to we'll write hours
modulus 12. modulus finds the remainder
of any division then i'll use the
bitwise or operator
12. we're taking hours modulus 12. if
ours is currently 12 this expression
would evaluate to be zero then using the
orbit wise operator we would instead use
12. so this line will convert your hours
from military to standard so yeah
everybody that's a few things we can do
with date objects they're used to work
with dates and times if you would like a
copy of this code i'll post all of this
in the comment section down below and
well yeah those are date objects in
javascript hey everybody in this video
we're going to create a practice program
to create a clock that will update every
second let's begin by going to our html
file and i will add a label we'll use a
pair of label tags and i will set the id
equal to
my
label
save head back to your html document
i'll assign that variable to a label
constant my label
equals
document dot get element by id
the id was my label
and we'll create an update function
function
update
and we will get the current date and
time
let
date equal new
date
let's update this label just to test it
my label dot inner html equals date
and then we should invoke this function
update
so that's the current date and time but
i would like to format this within our
update function let's create a nested
function to format the time
function
format time
let's get the hours let hours equal date
dot get hours
the minutes
let minutes date dot get minutes
and seconds
seconds date dot get seconds
let's return a template literal
hours
minutes
seconds
make sure you spell return right let's
invoke the format time function
and we should probably pass a date
so set up a date as an argument and a
parameter
this time is in military time so let's
set this to standard we'll need am or pm
let am or
pm
equal i'll use a ternary operator
we'll check if hours is greater than or
equal to 12 question mark if that's true
return pm
otherwise return am
let's add our variable am or pm
my current time is 12 22 pm the hours is
still in military time although you
can't tell from my example to convert
that between 1 and 12 i can set hours
equal to
hours modulus 12
bitwise operator 12.
modulus gives you the remainder of any
division if hours is 12
then the remainder of 12 divided by 12
is 0
then we would instead use 12 in place of
0 using the or bitwise operator since
i'm filming this at 12 pm there's no
change i would like this clock to update
every second after we invoke the update
function let's invoke the set
interval method of our window object the
first argument is a callback
we'll pass our update function as a
callback and then a delay every 1000
milliseconds i would like to update our
clock
there it's updating currently
now if one of these variables is a
single digit we don't have any leading
zeros
i'd like to change that if we have a
single digit i would like a leading zero
before the actual time unit so let's
create another nested function
function
let's call this format
zeros
we'll accept a time let's set our time
parameter equal to
time
dot to string this will convert a number
to a string then we will use some string
concatenation
and return
we'll use the ternary operator let's
check the times length property
if it's less than two that means it's a
single digit
if our time length is a single digit
then we will precede
our time with zero if it's false we'll
just return time back so then we just
need to invoke and reassign hours
minutes and seconds we'll invoke our
format zeros function
pass in our hours
and do the same thing with minutes and
seconds
and we now have some leading zeros
so yeah i thought that would be a fun
practice project we have a clock that
will update every second if you would
like a copy of this code i'll post this
to the comment section down below and
well yeah that's a simple clock program
in javascript
hey guys for this topic i will explain
the differences between synchronous and
asynchronous code in a span of a few
minutes synchronous code isn't an
ordered sequence they are step-by-step
linear instructions you start some
process now and you finish now the rest
of your program has to wait for a
synchronous process just a quick
demonstration let's display something
start
this step is
synchronous
and then
end
so these are step-by-step instructions
in order to move on to the second step
we first need to complete the first step
no matter how long the statement will
take our next step has to wait for the
first step to finish so our results are
start this step is synchronous and end
now asynchronous code can be out of
sequence these may be tasks such as
accessing a database fetching a file
basically tasks that take time they'll
take an indeterminate amount of time you
don't want the rest of your program to
wait around for some process to finish
you start now finish sometime later and
the rest of your program can carry on
with whatever it was doing an example of
some asynchronous code would be the set
timeout method so i'm going to replace
the second line with set
time out just to keep things simple i'll
pass in an arrow function expression and
we will display a message
console.log
this is
asynchronous
and we'll wait maybe five seconds
okay we have start and end and that
asynchronous code should kick in right
about now so you can see that this step
is out of order it's asynchronous it's
out of sequence it's running in the
background step three in my program
doesn't need to wait for step two to
finish step two will start now finish
sometime later when it's ready that's
the main differences between synchronous
and asynchronous code synchronous code
has to be in order it's a set of linear
instructions you start now and finish
now such as a console.log statement
asynchronous code is out of sequence it
takes an indeterminate amount of time
like accessing a database fetching a
file etc start now finish sometime later
and it doesn't pause your program it
will continue on with the rest of the
instructions so that is a quick
description of the differences between
synchronous and asynchronous code in
javascript
hey guys here's a super quick video on
the time method of the console object i
think you would find this fairly useful
it's a great utility method its job is
to start a timer that you can use to
track how long an operation takes
and you can give each timer a unique
name to track how much time has elapsed
for a given operation i can use
console.time
to give this timer a unique name i can
pass that as a string argument
let's see how long it takes for a user
to click a button
i'll name this timer response
time
so this is the start
to end this timer
i can use time end at the end of my
program i will invoke console.time
end
and pass the same name as an argument
response time
so this is the end if i run this
currently the time end method will print
the elapsed time in my console this
program took
.0019 milliseconds to complete
let's actually do something
i'll create an alert
alert
click the ok button
and let's see how much time elapses
okay click the ok button i will press ok
and the response time for me to click on
that button was 4 86 milliseconds so
about 4 seconds
if you ever need to track how long an
operation takes you can use the time
method of the console object however if
you have an asynchronous process
well the time end method isn't going to
wait around for it
so what if we have set timeout set
time out
we'll just display a message we need a
callback i'll simply just pass in an
arrow function
console.log
hello
i would like this to execute after three
thousand milliseconds so three seconds
so when i run this
we have already completed our program
and then the set timeout function kicks
in
so the time method and the time end
method will track how long a synchronous
operation takes so yeah i thought that
would be a very useful utility method
that you might be interested in if you
would like a copy of this code i'll post
this in the comment section down below
and well yeah that's the time method of
the console object
hey everybody we have a big topic today
that is promises promises are an object
that encapsulate the result of an
asynchronous operation
a benefit is that they let asynchronous
methods return values like they were
synchronous it's a promise to return
something in the future for this topic
let's pretend that we're fetching a file
i haven't talked about the fetch api yet
but we'll do so in the future for the
time being we'll just pretend that we're
loading a file
let file loaded this will be a boolean
value true or false i'll set this to
true loading a file is an asynchronous
process we could encapsulate this
asynchronous process with a promise when
this process is finished the promise can
return a value or catch any exceptions
if there's any problems like we can't
find the file so this is how to create a
promise
let's declare one const
promise
equals new
promise
within the promise we can list a
callback a function expression or an
arrow function expression i'll use an
arrow function expression
there's two arguments
resolve
and reject
if our asynchronous process is
successful we will invoke this resolve
callback if not we'll invoke reject
so what would we like to do within this
promise we can place any asynchronous
code within this promise
then let's check to see if our file is
loaded if
file loaded
we will invoke this callback of resolve
if you have any arguments for this
callback you can place those here i'll
add some text
file loaded
else
we will invoke reject
place any arguments within this callback
file not loaded
that's step one of our promise
promises have a state
they're pending then they're fulfilled
or rejected and the result is what can
be returned
there's two parts to a promise the
producing code which is this portion and
the consuming code if this promise is
resolved what do we want to do we'll
handle that with the consuming code
we will take our promise
follow the promise with invoking the
then method
if our promise is resolved then we can
perform some function
this can be a callback to a function
a function expression
or an arrow function expression
i'll stick with an arrow function
expression
if we have any arguments we can list
them here we're returning one value just
some text
value
arrow
then let's do something
console.log
whatever my value is
okay let's try this
after creating this promise my file
loads that's set to true
file loaded
what would happen if we couldn't locate
a file this value is false
well we have an uncaught exception
because we invoked this reject callback
to catch any exceptions we can follow
then with
catch
and i'll place this on a new line
just so it's easier to read
we have one argument so let's set up one
parameter this is the argument we will
name this parameter error
arrow what would we like to do
console.log
whatever my error is
when i run this again
we have caught this exception
file not loaded so that's kind of the
basics of a promise
it's a promise to return something in
the future the state is pending then
it's either fulfilled or rejected now
you don't necessarily need to reject a
promise
this would still work too
it doesn't do anything
here's another example
let's create a separate promise we'll
wait for five seconds then display a
message
const
promise
equals
new
promise
i'll write an arrow function expression
this time we will only resolve
arrow
and then maybe some curly braces okay
what are we gonna do within this promise
let's set timeout for five seconds
set timeout
resolve
after five
seconds that's 5000 milliseconds
then i will take
the name of my promise
follow it with then
then pass in a function
so you don't necessarily need to return
a value when resolving
so this function will have no arguments
arrow
will display message console.log
thanks for waiting
after five seconds this should display
my message
thanks for waiting
what if you would like to pass an
argument to a promise let's rename this
promise object as something else
something that's more descriptive
like wait
wait is now a promise
when we create this promise we can pass
an argument how about an amount of
milliseconds let's wait for three
seconds that's three thousand
milliseconds
i'll precede this promise with an arrow
function
and list any arguments before the arrow
maybe time
time will be this value whatever we're
passing in
we'll wait for some amount of time
3000 milliseconds
let's run this again
one two three thanks for waiting so yeah
those are promises
they're objects that encapsulate the
result of an asynchronous operation
they let asynchronous methods return
values as if they were synchronous it's
a promise to return something in the
future so those are promises if you
would like a copy of the code we worked
on today i'll post that in the comments
section down below and well yeah that's
an introduction to promises in
javascript
hey guys in this topic i'm going to
explain the async keyword it makes a
function return a promise in this
example i have a promise there's a
callback with two arguments a callback
for resolve and a callback for reject
all we're doing is we're checking to see
if a file loaded not really but we're
pretending we are because i haven't
taught about loading files yet so we
have a boolean variable file loaded it's
set to true if our file didn't load we
can set this to false if file loaded we
will invoke this callback of resolve if
not we'll invoke this other callback of
reject so currently my file loaded if i
switch this to false my file is not
loaded an easier way of writing this is
that we can stick this code within an
async function and it will return a
promise so let's create an async
function use the keyword async
function and what's a descriptive name
of this function how about load
file
that's an asynchronous process i'll copy
this code
cut it
i'll delete this promise
and paste my code within this async
function there's no need to use this
resolve or reject callback if my
asynchronous process is successful i
will simply return a value
return file loaded this will be an
argument if my asynchronous process is
not successful i could instead use the
throw keyword
this will raise an error and we can
catch it so this is my error message
right here now to invoke this function
in place of a promise i will invoke the
function that contains my asynchronous
process
load file so let's check to see if this
works file loaded is set to true file
loaded
i'll set this to false file not loaded
when using the then and catch methods in
place of adding these methods after a
promise object we would invoke a
function and a promise is going to be
returned back to this place in which you
invoke the function another way of
writing this that's a little more clear
but it's a lot more syntax is if we were
not using the async function we would
return a promise i'll eliminate this
async keyword just for a demonstration
so we're returning a promise object
promise dot resolve
and i will pass this text as an argument
else
return
promise dot reject
this would do the same thing but it's
more syntax file loaded
file not loaded when we invoke this
function we're returning a promise back
to the spot in which we invoked this
function but i like using the sync
keyword it's a lot less text so yeah
that's the async keyword everybody it
makes a function return a promise and it
pairs very well with the await keyword
which we'll discuss in the next topic in
about three two one go
hey guys in this topic i'm going to
explain the await keyword it makes an
async function wait for a promise in
this example i have an async function
that is named load file
we're pretending to load a file that
would be an asynchronous process
if our file loads we will return a
promise with this text as an argument
file loaded
if for some reason we can't load our
file we will throw an error and catch it
and display this error message another
way of writing this without using these
two lines of code invoking an async
function followed with then and catch is
that we could use the await keyword so
we will type await then invoke an async
function
await load file
we're waiting for a promise awaiting an
async function in this example will
return some text file loaded or file not
loaded so i'm going to store that text
within a temporary variable let's say
let
message
equal await load file then i'll simply
display that message console.log
message and i can eliminate these two
lines
so after running this
we have an uncaught syntax error a
weight is only valid in async functions
so in order to use this await keyword we
need to place it within another async
function so maybe we're beginning the
process of loading a file usually that
takes more than one asynchronous process
you have to first locate the file open
it then close it so i'm going to declare
an async function
async function
start
process
and i will stick these two lines within
that function you can only use the await
keyword within an async function
and then we need to invoke this function
to begin the process
start process
file loaded there was no need to invoke
this async function followed with
then and catch we can eliminate that
all you need is a weight but it does
have to be within an async function
now check this out what if our file
doesn't load this will throw an error
uncaught in promise file not loaded we
would need some way to catch this error
when it's thrown
one way in which we can do that is to
surround any dangerous code with a try
block
see the topic on the series in error
handling where i'll discuss this more in
depth
so try this code if there are any errors
we will catch them so catch there is one
argument of error
and i will simply display our error
catch
console.log
error
so let's run this again
file not loaded so this is very helpful
if we have to wait for more than one
asynchronous function we'll discuss this
in the next topic maybe not only do we
have to load a file but we first need to
locate it and we have to close it in the
next topic we'll have to wait for
multiple asynchronous functions we might
have locate file
and close file
so when we begin a process we're waiting
for multiple asynchronous functions but
we'll discuss that in the next topic so
yeah that's the await keyword everybody
it makes an asynchronous function wait
for a promise when using the await
keyword you don't need to invoke a
function then follow it with the then
method and catch
there's no need for that so yeah
everybody that's the await keyword we'll
practice this more in the next topic
hey guys in this video i'm going to
explain es6 modules the idea behind a
module is that it's a file of reusable
code we can import sections of
pre-written code to use whenever we want
they're great for any general utility
values and functions they help to make
your code more reusable and maintainable
think of modules as separate chapters of
a book each javascript file could be its
own individual chapter to begin working
with modules within the opening script
tag of your html document add this
attribute
type equals module
then we'll create a new javascript file
i'll name this
math underscore util
dot js
this file will contain some general map
utility functions such as get the
circumference of a circle or the area so
let's begin i'll create a constant as
well const pi
i'll set the sequel to 3.14159
and maybe some functions
function
get
circumference
will accept a radius
and we'll return
two
times pi
times radius
then let's create a get area function
get
area
will return
pi
times radius
times radius
to export any variables or functions i
will precede them with the export
keyword
i like to do this inline
then save
heading back to our main javascript file
we can import everything from this
javascript file to do that we will type
import
then within curly braces then list all
of the variables or functions we would
like to import
i would like to import pi
get circumference
and get area
add from
then an absolute or relative file path
i'll use a relative file path because
these files are right next to each other
so that would be dot forward slash the
name of the file math underscore util
dot js
and that's it so we can use these
variables and functions as if they were
in the same file
to test this i will use console.log
pi
and that value is 3.14159
we have access to this variable even
though it's not written within this file
we've imported that variable from the
separate javascript file let's calculate
the circumference of a circle
let
circumference
equal
get circumference
pass in a radius maybe 10.
then let's display our circumference
console.log
circumference
if we pass in 10 as a radius the
circumference is 62.83 we also have get
area 2.
let area equals
get area
the area would be
314.159 even though all of this code is
written in a separate file we can access
it from another file by importing it
make sure that anything you want to
export is preceded with this export
keyword there is another way to import
this too
i'm going to copy all of this
and paste it
if there's a lot to import we can simply
import everything by using an asterisk
but we'll give all of these imports an
alias that's like a nickname import
asterisk as
your nickname should be descriptive of
the file that you're importing this is
as if we're creating a separate
namespace
maybe
math
util now in order to use these variables
or functions i would need to precede
them with that namespace mathutil
dot pi
mathutil dot get circumference
mathutil dot get area then this would
work when i'm using math util dot pi
that's kind of similar to math.pi it's
kind of the same concept except we
ourselves created the separate
javascript file so yeah those are
modules they're files of pre-written
code that we can import and use whenever
we need to if you would like a copy of
this code i'll post this in the comment
section down below and well yeah that's
an introduction to modules in javascript
hey guys in this video i'm going to
quickly explain the dom it's an acronym
for document object model technically
it's an api an application programming
interface it's an interface that's used
for changing the content of a page and
it's arranged in a hierarchical tree our
dom is a representation of an html
document and this tree contains nodes
the first child of our document is the
html root element so our html tags
enclose all of this content including
the head and the body elements
which are here
and here the head can contain a title
and some text which you see right here
and the body can contain some various
html elements like a div tag by
interacting with this dom we can change
the elements of a web page document is
the entry point of our dom if i typed
console.log
document this would display my dom and
everything within it so we have document
our html node
the head
and the body and a bunch of stuff within
those nodes too now if you were to type
console.dir
then pass document as an argument this
will list all of the properties of your
dom if i need access to the title of my
document i can access that by typing
document dot title property and then
i'll display this console.log
document.title and the title of my
document is well document or i could get
the url console.log document.url
so this is my url and you can change
these properties too i can change the
title of my webpage document.title
set the sql to something
title goes here and taking a look at
this tab of my web browser you can see
that it says title goes here i can even
change the location
document.location
i'll set the sequel to google
so http colon two forward slashes
www.google.com
then when i save this it takes me to
by accessing the dom i have access to my
body element and i can change something
about the body of my document if i would
like to change the background color i
would type document
dot the name of the node body in this
case
and i will set the style
background color
sky blue
and this will change the background
color of the body of my document if i
need to change some html element like
this div tag i could type
document
dot get
element by id
and we will search for an id within our
dom
like my div and i can set the inner html
equal to some text like hello
hello
that's a quick summary of what the dom
is it's an api an application
programming interface it's an interface
for changing the content of a page we
can change content without having to
reload the page to reflect any changes
document is the access point each node
can contain an object this tree is a
model so it's a document object model a
dom and in the next few topics i'll
demonstrate how we can search for given
elements and traverse nodes so that is a
quick overview of what the dom is
hey guys in this video i'm going to show
you a few different ways we can select
elements in a web page let's begin with
something very basic i'm going to create
an h1 header tag we'll create a menu for
a restaurant this is the menu and i will
give this h1 element a unique id
my
title to select this element i can type
document dot get
element by id
and the id was my title and i will store
this within a variable
let
element equal document.getelementbyid
and what should we do with this element
let's change the background color
so type element
dot style
dot background
color i'll set this to
light green that's a good color
so yeah you can select an element by its
id but you probably knew that already we
have a little bit of experience with
this method
let's select elements by their name the
name attribute is useful if you have
more than one elements in some sort of
group like radio buttons let's create
some radio buttons
input
type equals radio
and i will give this a name of fruits
the first will have a value of apple
then i'll create a label for this
label
for
equals
apple
close the label i'll add a line
and i will type apple okay two more
fruits
what about an orange
for orange
the text will be orange
and a banana
value
banana
for banana and the text will be banana
so each of these three radio buttons has
the same name fruits to select all of
these radio buttons within my document i
can type document dot get
elements that's plural with an s
by name
then pass a name as an argument fruits
this method returns a node list
it's similar to an array
so i will store that within
let's say fruits
let fruits equal document dot get
elements by name fruits so what would i
like to do with this node list of fruits
if i were to use console.log and display
fruits well we have a node list with our
three elements a radio button for apple
orange and banana if i add an index
number only that element is displayed so
we have our apple at index one would be
our orange
and two is our banana
maybe i would like to change the
background color of each of these
elements what's one way we can check to
see if one of these elements is selected
i'm going to add an attribute
with the apple radio tag let's add this
attribute
checked equals checked
by default this will already be selected
i would like to print whatever radio
button is checked we've already selected
our elements by their name fruits so i
will use the for each method of this
node list fruits for each i will cycle
through this node list of elements and
find whatever element is checked and
display it so we have our parameters
fruit
arrow function
let's check to see if our fruit
is checked fruit dot checked
then we will
console.log
whatever our fruit is
then add dot value
so our apple is selected
let's change the checked attribute of
our orange this time
so we have orange now
and banana
so that is get elements by name now we
have get elements by tag name heading to
our html file let's create an unordered
list
ul for unordered list
close it
we will add some list items
perhaps these are vegetables
carrots
potatoes
and onions
we can select elements by a given tag
name like list item let's store our
elements within vegetables let
vegetables
equal
document dot get
elements by tag name
and the tag name was
li for list items this method returns
technically an html collection it
behaves similarly to an array let's take
vegetables at index of zero
that would be our carrots i'm going to
access the style the background color
property
set the sequel to light green
the second element would have an index
of one
and the next element would be two
so that is get elements by tag name find
tags that you would like to select and
then just pass that as an argument to
this method
okay we have get elements by class name
i think this time i'll create some div
elements
div close it
and i will give this a class of desserts
desserts
first we'll have ice cream
cake and maybe pie
each of these three developments has the
same class name desserts
i'll store elements within
let
desserts
equals
document dot get
elements plural with an s
by
class
name
and the class name was desserts
desserts is technically an array-like
object but it behaves similarly to an
array again
so i'm going to change the background
color let's start with element zero
so that is the first element index zero
index one
and index two
that is the get elements by classname
method now we have query selector query
selector tends to be fairly popular we
can select an element by either an id
a class name
a tag
or an attribute let's create variable
element
equal
document
dot
query selector
then pass in an id a class name a tag
name or an attribute let's begin with an
id let's select id my title
if you're selecting an id be sure to
precede the name with a hashtag i will
change the background color of this
element to light green again
there so using query selector we've
selected an element by a unique id
we can also do so by a class name
so class desserts
with a class name you're going to
precede the class name with a dot
so class desserts now with quarry
selector it selects the first element of
any group if you need all of the
elements you'll need to use query
selector all which we'll cover in just a
little bit you can also select by a tag
name like list item the first list item
within my document will be selected or
you could even use an attribute so maybe
the first element that has the four
attribute i would like to select
i will use a set of square brackets and
type four the first element with the
four attribute is selected if you need
all elements you can use query selector
all
so let's copy this paste it
let elements query selector all i would
like to select all list items and change
the background color but we'll need to
iterate over each of the elements
i'll use a for each loop
elements for each
element
i will change the background color of
each element there each list item was
selected how about anything with the
desserts class name
or anything with the v4 attribute
so yeah those are a few different ways
in which we can select html elements if
you would like a copy of this code i'll
post all of this in the comments section
down below and well yeah that's how to
select elements using javascript
hey guys for this topic i'm going to
show you a few different dom traversal
techniques but before we do that i need
to explain some family relationships
between elements say we select our body
element within my html document i have
three unordered lists a list for fruit
vegetables and dessert they are arranged
in a hierarchy a family tree if we
select our body these three lists since
they're contained within the body
they would be considered children my
list of fruit is a child same with
vegetables
and dessert
since my list of fruit appears first
within my body the fruit list would be
considered the first child kind of like
it's the firstborn
dessert is last that would be the last
child
it's the last born if we select this
middle list of vegetables
then my body element is considered the
parent of this list the body element is
the parent
the two other lists would be considered
siblings
sibling
and sibling
since fruit appears before vegetables
fruit would be considered the previous
sibling
dessert would be considered the next
sibling
my unordered list does have children too
each of these list items would be
children of my unordered list yeah
that's a quick overview of the family
relationships between elements with that
out of the way here's my html document
within the body i have three unordered
lists
each has a unique id fruit vegetables
and dessert
suppose i would like to select the body
of my document i'll store that within a
variable let
element
equal
document
dot body
to select the first child that would be
the first unordered list
i'll store that within another variable
let child equal
element dot
first element child
let's color the background of this child
element green child
dot
background color
equals
light
green
this entire unordered list is now green
let me show you what happens when i
select the last element child of my body
so nothing appears to change
let's take a look at this child using
console.log console.log
child
so when i selected the last element of
my body we selected the script element
this element is the last child of my
body so that's something you need to pay
attention to
let's select our vegetable list
document dot
query
selector
i will select
vegetables
we will select the
parent element
i'll rename this as parent
the parent of this list would be the
entire body of my document that's why
the entire background color is now green
we can choose the next element sibling
sibling
sibling
if we select our list of vegetables the
next sibling would be my list of dessert
and the previous element sibling
is my list of fruit
what if you need one of these list items
i'll select my list of fruit
then select one of these elements
first element child
that would be the apple list item
last element child is the banana
another way to access the children of an
element is via an index
this time i will follow element with
children and list an index number
0 is the beginning
and we will change the first element at
index
0. one would be the second element
orange
two is the next element banana
if you need all the elements you can
simply use children this will return a
collection we would need to convert that
to an array this collection doesn't have
the for each method
i will surround
element.children with
array
dot from method
and we can iterate over the elements of
this array
let's rename child as children
children
dot
for
each method
we have our parameters child arrow
function
we'll change the style of each of the
children of this list
now each child is green
we could select a different list like
vegetables
or
dessert
so yeah those are a few dom traversal
techniques elements are arranged in a
family tree whatever element you select
that element can have a parent maybe
some children or siblings
so yeah those are a few basic dom
traversal techniques in javascript
hey guys for this topic i'm going to
show you how we can add and change html
elements i need to create an h1 header
tag to do that i will type document dot
create
element
within the create element method and
within quotes i can list a tag that i
would like to create i would like to
create an h1 header tag i'll assign this
to a variable
constant maybe name tag we'll store our
name name tag is an h1 header tag
however it doesn't contain any text
that's where changing html elements
comes in two ways in which i could add
some text to this h1 header tag is to
either use inner html or text content
text content is the preferred way
because inner html is vulnerable to
something called cross site scripting
attacks i'll give you a demonstration
momentarily if we were using inner html
i would take my tag dot
inner
html
set the sql to some text maybe your
first name then to add this element i
would need to declare where i would like
to add this tag specifically the body of
my document would be a good place
document dot
body and i will use the append method
and place my tag within the append
method as an argument this will create
an h1 header tag then add it to the body
of my document what if we accept some
user input instead
window
dot prompt
enter your name
enter your name type in your first name
press ok and there's your h1 header tag
now here's the problem with using
innerhtml we could also assign some tags
along with some text if i was to run
this again i could place a malicious
script within the user input this would
be an example of a cross site script
attack i'm going to blur this section
just because i don't want to give you
guys any ideas then if i were to press
ok this would activate my script this
script that i wrote just has a pop-up
that says virus the preferred way of
adding some text to an element is to set
the text content when i run this program
again and enter my malicious script this
script will be instead parsed as text
setting text content is a much safer
approach than using innerhtml this time
we're going to add a list item to an
unordered list heading to our html
document we'll create an unordered list
i'll give this list an id of fruit
then we will add some list items
apple
orange
banana
okay here's my list
to append an item to my list well i need
to know what my list is
i'll store that within a variable
constant
my list
and i would need to select this list
i can do that with document dot query
selector
pass in an id
the id was
fruit
then i can create a list item element
construct list
item equals document
dot create
element
what kind of element would we like to
create let's create a list item element
to set the text of this list item
element i will take my list item then
set the text content property equal to
whatever i want i feel like a main go
then we just need to add this list item
to my list my list use the append method
then pass in my list item
there we have added a mango if you would
like this list item at the beginning of
your list you can use prepend
pre-penned
now we have mango apple orange banana
otherwise if you need to place an item
somewhere within the middle of the list
it's a little more complex but here's
how take your parent element my list in
this example
dot
insert
before method
pass in what's to be inserted our list
item then we need to get all of the
elements we can do that by taking my
list again
dot
get
elements
by tag name
we would like to select all list item
elements
then an index number to insert main go
before orange
the index would be 1. following the get
elements by tagname method i will add
the index of where i would like to
insert this list item so 1. now we have
apple mango orange banana
two would be
apple orange mango banana
and then three would be the end so yeah
everybody that's a beginner's way to add
and change html elements if you would
like a copy of this code i'll post all
of this in the comment section down
below and well yeah that's how to add
and change html elements using
javascript
hey what's up guys in this video i'm
going to show you how we can change some
css properties of elements heading to
our index.html file let's create a
simple h1 header tag
i'll give this header tag a unique id of
my title
then add some text
this is my title
then save
in order to change the css properties of
this element we first need to select
this element i'll declare this as a
constant
const
title
equals then to select an element you
type
document
dot
get
element
by id
within the parentheses and within quotes
we will list the id of our element we
would like to select
getelementbyid is a very basic way of
selecting an element in the future we'll
cover more advanced methods but for now
we'll stick with getelementbyid so we're
storing this within a variable title and
now we can do stuff with it
to change css properties of some element
such as my title i will follow the name
of this element title then access the
style attribute
dot then a css property
maybe i would like to change the
background color so i will list that
property
background
color
when accessing a css property through
javascript the format is in camel case
normally with css there's a dash between
words such as background dash color but
if you're using javascript you use
camelcase
the first letter of the first word is
not capital then the first letter of any
word after the first is capital
background color and set the sequel to a
color you can pick a color name maybe
blue
you can select rgb values rgb within the
parenthesis you have three numbers each
corresponds to the amount of red green
and blue
uh so maybe 50 200 250 i don't know what
this color is going to be
oh i kind of like that color or you
could use hexadecimal values
what's 2 two two two two two
okay that is a dark gray you have a
couple options when it comes to colors
let's change the font of my title what
element would we like we would like
title we'll access the style then a
property color
uh let's use rgb this time rgb
5200
250
there and we have that color again so
again you can use color names rgb values
or hexadecimal values and if you don't
know any you can always google hex color
picker
and pick a color that you like
here are the rgb values or the
hexadecimal values okay let's change a
few other properties
we're selecting our title
accessing the style attribute
then let's change the font family
property i will set the sequel to
pick a font i like this font
and there we go we have a new font i
would like to text align center this
element
title dot style
dot
text
align equals center
then add a border
title dot style
dot border
equals 2 pixels solid is good
yeah and we have a border
to hide an element we can access the
display property
title dot style
dot
display
equals none
this will hide this element or we could
set this to block to display it
so yeah everybody that is a very basic
way to change css properties you would
first need to select an element or
elements follow that element with dot
the style attribute dot
the css property and you can set it
equal to a new value that is how to add
and change css properties using
javascript if you would like a copy of
all this code i'll post this in the
comments section down below be sure to
look underneath the original video in
the 100 video playlist and well yeah
that's how to change some css properties
using javascript
hey guys in this video i'm going to
explain events an event is some action
that the user or the browser does many
html elements contain event attributes
for example let's create a button
i'll give this button an id of my button
for the text let's just say button
buttons have an on click event attribute
on click
i can set this equal to the name of a
function and invoke it
let's create a function that will do
something i'll cleverly name this
function do
something
all we'll do is create an alert alert
you
did
something
i will set the on click attribute equal
to the name of my function do
something
then invoke it
when i click on this button my on click
event attribute will invoke this
function do something
you did something in place of setting
event attributes directly within your
html elements you could do so within
your javascript file
i would first need to select my element
constant
element equals
document dot get element by id
the id was my button
i will take this element
and set the on click event attribute
equal to some function
do
something be sure not to invoke it this
is a callback
save everything then when i click this
button we activate the on click event
attribute so that's one event attribute
on click another event attribute is on
load when the web browser loads it does
something this time i'm going to select
the body of my document
constant element equals document.body
i will take this element and set the on
load attribute equal to some function
do
something
when the body of my document loads it
activates the onload event attribute
another option is that within the
opening body tag of your html file you
can directly set that attribute
do something and this would work too
that is the onload event attribute when
an element loads it does something
next we have the on change event
attribute
element dot
on
change equals
do something
when an element has been changed it
activates the on change event attribute
heading to our html document let's
create a text box
input
id equals my text
get rid of this
we will select our text box constant
element equals
document dot get element by id
we are selecting
my text
now when we make changes to this text
box
and then leave
it activates my on change event
attribute if used with a text box
you could format some text once you
leave
okay this next one is going to be fun
let's create a div tag
div
id equals my div
close it
then heading to our css style sheet
let's select my div
we'll change the background color
to light green
and the width to 100
100 pixels
and the height to be 100 as well
let's save we'll select this id my div
constant element equals document dot get
element by id
the id was my div
when we move our cursor over this div
tag we'll change the background color we
will take our element
and use the on
mouse over event attribute
set the sql to a function
do something
change the background color element dot
style dot
background
color
equals how about red
when i hover my cursor over this div tag
it's gonna change the color when you
leave an element
you can set the on mouse out event
attribute
element dot on mouse out we'll create a
function to do something else let's copy
this paste it
do something else
we'll change the background color to
light green again
so when i enter
the color is red when i leave it's green
red green red green red green so that is
on mouse over and on mouse out
okay we're on the last two on mouse down
element dot
on mouse down
equals do something
so when i click down when i click on
this element
it activates the on mouse event
attribute
by itself it's basically no different
from the on click event attribute but it
pairs very well with the on mouse up
event attribute
on mouse up
when we let go of our mouse
we can perform another function do
something else
when i click and hold down it's red when
i let go it's green red green red green
red green all right everybody so those
are a few events on click on load on
change on mouse over on mouse out on
mouse down on mouse up and in the next
topic we'll look at event handlers if
you would like a copy of all this code
i'll post all of this in the comments
section down below and well yeah those
are a few javascript events
hey guys in this video i'm going to
explain the add event listener method we
can link an event and a function to an
html element using the add event
listener method is the preferred way of
handling events a benefit is that one
element can have several event listeners
even the same event can invoke different
functions within my html document i'm
going to create a div
div
close it
i'll give this a unique id of inner div
eventually we'll create an outer div
then within my css style sheet i'll
select
inner
div
i'll give this a background color of
light
green light green
a width
of 100
a height of 100
and a border
one pixel solid is good
save everything and here's our div
element using the add event listener
method
this development can listen for multiple
events we'll need to select an element
i'll name this const
inner div
equals
document
dot get
element by id
we're selecting inner div
to add an event listener you take your
element inner div in this case
then invoke the add event listener
method
the first argument is an event
let's add mouse over
mouse
over
then a function
let's create a function to change the
color red
this will be a callback change red
let's define this function
function
change red
let's take our inner div
take the style
set the background color property
equal to red
when i hover my cursor over this div
element it changes red a benefit of
using the add event listener method is
that it's easy to wait for multiple
events
so to wait for another event
we can simply invoke the add event
listener method again
this time we'll also listen for the
event of mouse out
let's create a function to change
green
function change green
background color equals light
green
this development is listening for two
events mouse over and mouse out
using the ad event listener method it's
really easy to wait for multiple events
there's one more argument within the ad
event listener method
that is the use capture argument
suppose we have an element within
another element
i'll surround this inner development
with another div
div the id will be
outer div
be sure to enclose your inner div
i'll change the style of outer div
i'll get rid of the border
the width and the height will be 200.
save everything
so we have an outer div and an inner div
the inner development is inside of the
outer div element what would happen
exactly if both of these elements are
waiting for the same event mouse over
which event would be handled first the
inner element or the outer element well
we can set that with the third argument
the use capture argument let's add an
event to the outer div i'll store this
within a variable
outer div
the id is outer div i'll eliminate all
of this
i'll add an event listener to the inner
div
add event
listener
the event this time will be click
the function will be change
blue this time
we'll add the same event to the outer
div
outer
div
add event listener click change blue
let's define this function change blue
function change blue
we will take this
dot style dot background color
equals
light
blue
both of these div elements are doing the
same thing
but there's some overlap
the inner div element and the outer
development are within the same space so
when i click on the inner div element
we're also clicking on the outer div
element at the same time which element
handles its event first the inner
element or the outer element just to
test this within the change blue
function let's create an alert just to
slow things down
you
selected
then let's display the id of the element
that is being handled
this dot id
okay so when i click on this element
we're handling the inner div first
before the outer div
but with the outer element if you pass
in another argument true for use capture
well then we will handle the outer
element first before the inner element
so that's what that third argument is
use capture if two elements are taking
the same space and they're listening for
the same event you could specify which
one has preference yeah that's the add
event listener method it's the preferred
way of having an element listen for
events as arguments you can pass in an
event a function to be executed and a
preference if you would like an outer
element to be handled first so yeah
that's the add event listener method
everybody
hey everybody in this video i'm gonna
demonstrate how we can show and hide
html elements for this demonstration i
recommend downloading a picture here's a
picture of a card that i found place it
within the same folder as your
javascript file when i click on a button
i would like to toggle between showing
and hiding that image heading to my html
file let's create a button
button
id equals my button
i'll add some text toggle is fine
we will add our image
image id equals my image
set the source equal to where your file
is located this image is in the same
folder as my html file i just need the
file name my file name is card.jpg but
it's probably going to be something
different for you
car dot jpeg let's change the size it's
a little
massive heading to my style sheet i will
select
my image
set the width to something reasonable
like 300 pixels
that's a lot better at the bottom i'll
add some text a paragraph element is
fine
press the button
heading to my javascript file i'll
select my button and my image
const my
button
equals document dot
query
selector
i'm selecting
my button
do the same thing with image
my image
next i'll add an event listener to this
button
my button dot add
event listener
when we click on this button we're going
to perform a function i'll use an arrow
function expression
what we'll do is check the display
property of this image
i'll use an if statement
if
my image
dot style
dot display is equal to none
none means that this image is hidden
if it's block that means it's being
displayed if this image is hidden my
image dot style dot display
equals block
this will display my image
else let's hide our image
my image dot style dot display
equals
none
when i click on this button it hides my
image when i click on it again it
displays my image now it's hidden now
it's showing hidden showing hidden
showing there's one issue with this
though perhaps i would like this image
to be hidden from the beginning then we
display it to do that we can go to our
style sheet then set the display
property to none
now check this out when i click on this
button the first time it doesn't do
anything until i click on it a second
time then it performs normally the
reason that this is happening is that
the style from our style sheet is not
ready yet to demonstrate that i'm going
to console.log the display of my image
when i click on this button well there's
no value within my display
if the display of my image is equal to
the property none then we show the image
but this is technically null and not the
property none therefore we will hide
this image which it already is a quick
fix for that is that we can add some
inline styling to this element i'll add
this display property inline instead of
externally find your image tag set the
style attribute equal to that css
property
this should work now i will click once
to display my image then hide it display
hide it another option is that we can
set the visibility of this image when we
toggle the display property all the
elements that are underneath are going
to shift downwards but if we were to use
visibility this space will be reserved
let's replace display with visibility
in place of none we will check hidden
in place of block this will be visible
within the inline styling let's set
display to
visibility
our visibility will be hidden
make sure to save everything
all of the space is reserved for that
image you can see that my text down at
the bottom is way down here when i show
and hide this image there's no shifting
of elements this space is reserved so
that's another option too you can always
toggle the visibility of an element so
yeah everybody that is how to show and
hide html elements if you would like a
copy of this code i'll post all of this
in the comment section down below and
well yeah that's how to show and hide
html elements using javascript
hey yeah everybody in this video i'm
going to show you how we can detect key
presses to do that we can add an event
listener to our window
window dot add
event
listener
the first argument is the attribute
let's detect any key down events
second is a callback a function
expression or an arrow function
expression let's use an arrow function
expression there is one argument
event
arrow then what would we like to do when
we press down on a key let's display
what key was pressed
console.log
event
dot key and that's it let's test it
press some random keys
q w e r t y a s d
enter backspace one two three the arrow
keys would be up down left right okay we
know that that works let's have some fun
with this let's create a box within our
window and we can move the box with key
events heading to our html file let's
create a div tag pretend this wasn't
here
div id equals my div
close it
let's style it
my div
will set the background color
to whatever color you would like
set a width
100 pixels is good
a height
100
you could add a border if you would like
border one pixel solid
and we'll want to set a position
position
either absolute or relative
we'll move our box relative to the body
that it's in okay save everything
i'm going to select our development
const
my div
equals document dot
get
element by id
my div
and we'll add an event listener to our
window
in place of an arrow function expression
let's pass a callback as an argument
let's pass a callback to a move function
and we'll need to define that function
move
there's going to be one argument that's
provided for us within the parameters of
the move function let's add event this
argument is provided for us i think the
best way to detect certain keystrokes
would be with a switch let's detect
arrow down up left right switch
we're examining event dot key for any
matching cases
the first case will be arrow down
arrow
down
we'll have to keep track of some
coordinates of where our div element
currently is let's create variables x
and y
let x equal zero
let y equal zero as well whenever we
press down let's move y by maybe five
pixels down y
plus equals five then we will take my
div
take the style
access the top property
and set the sequel to whatever y is
plus pixels
then at the end of our case let's break
so when we save
by pressing down we should be able to
move down
yeah there we go let's do the same thing
with the other arrow keys
arrow up we will decrement y
so we should be able to move down
and up
arrow right
x plus equals five
my div dot style dot left
equals x plus pixels
now we should be able to go right
arrow
left
x
minus equals five
now we can go right
down
left
and up
then you could add a default case too if
you would like default
break
so yeah that's how to detect key presses
everybody you can add an event listener
to your window the event attribute is
key down you could also switch this to
key up when you let go of a key then it
triggers the event the second argument
is a callback a function expression or
an arrow function expression so yeah
that's one way to detect key presses if
you would like a copy of this code i'll
post this in the comments section down
below and well yeah that's a very basic
way to detect key presses in javascript
hey guys in this video i'm going to show
you how we can create a few simple
animations using javascript we'll create
a button and a development heading to
our html file let's create a button
i'll give this an id of
my button
i'll add text begin
this button will begin the animation
i'll create a development
id equals my div
let's style our development
my div
choose a background color
i'll pick light green
but choose whatever color you like
a width of 100 is good
a height of 100 is good as well
then set the position property to
relative
we'll position this element relative to
the container that it's in the body of
our document
okay save everything in our javascript
file let's store our button element
constant my button equals document dot
get element by id
my button
then let's get our development
i'll name this my animation
get element by id
my
div
when we press on the button we'll begin
an animation
we'll want to add an event listener to
the button
my button dot
add event listener
the event will be click
then we will pass a call back begin
let's define this function
function
begin
what would we like to do i'm going to
declare a timer id we'll use the set
interval method
let
timer id i'll set the sequel to null for
now we'll need some coordinates to keep
track of our position of our div element
let x i'll set this equal to zero
let y
equal zero as well
we will use the set interval method
passing a callback to a function
we'll name this frame
after how many milliseconds would we
like to invoke this function
what about every five milliseconds
that's a good speed
set interval returns an id of the timer
that we're using
so let's assign this to timer id
we will use this timer id to stop the
animation when it's completed we're
going to create an inner function
function frame
this inner frame function will be in
charge of updating our div
every five milliseconds
but when would we like to stop let's
slide our div element to maybe like 300
pixels out so i'm going to write an if
statement
if
x
is greater than or equal to
200
then we will stop set interval we can do
that by using the clear
interval method
pass in our timer id
this will stop the animation
else if we would like to advance one
frame
let's increment x by one
x plus
equals one then we just need to adjust
the left property of this development
we'll take myanimation
access the style
access the left property
set the sql to whatever x is currently
then add
pixels
so when we begin this animation it
should slide to the right
and stop right about here now let's move
this animation down instead of right
if y is greater than or equal to 200
y plus equals one
myanimation.style
dot top equals y plus pixels
now this animation moves down
we could combine them both if x is
greater than or equal to 200
or
y is greater than or equal to 200
then we will increment both x and y by
one x plus equals one
my animation dot style dot left equals x
plus pixels
now this animation moves diagonally
that's a simple slide animation let's
make this element rotate i think that
would be cool let's eliminate some of
these lines of code
i'll post all of this in the notes so
don't worry about that
okay we'll need a variable degrees
set this equal to zero
let's perform a full 360 degree rotation
if
degrees is greater than or equal to 360.
then we will stop our timer
else we will rotate by increasing
degrees by one or a different number if
you would like this to be faster
take my animation
dot style
dot transform
set the sequel to this string is going
to be a little bit awkward
let's rotate
x
parentheses we'll need to insert our
degrees within quotes
plus degrees
plus
d e g
okay and that should be it
so this will rotate my element on the
x-axis
and it does a full 360 degree turn
okay rotate on the y-axis
pretty cool right
or z
hey just for fun let's rotate this
element and have it move diagonally
across the screen this will just be
practice
let x equal zero
let y equal zero
we'll continue this as long as x is
greater than or equal to two hundred
or y is greater than or equal to two
hundred
increment x by one
increment y by one
my animation dot style
dot left equals x plus pixels
myanimation.style.top equals y plus
pixels
okay this should move diagonally and
rotate
okay let's make the spin a little bit
faster i'll increase degrees by two
or three
or a higher number like five
okay last one we can scale the size of
an image
so let's get rid of what we have written
currently
okay let's create two new variables
let scale x
equal
one one means one hundred percent
let
scale y
equal one as well
let's scale this image twice as big our
condition to stop is
if
scale x
is greater than or equal to two
else
scale
x plus equals
maybe 0.01
this would be one percent then we will
take my
animation
dot style dot transform
set the sequel to
scale
then within parenthesis
we'll need to insert scale x and scale y
plus
scale x
plus
comma
plus scale y
plus
and that should be good if we're only
scaling x upwards then this element will
expand horizontally
if we stop where scale x is three it
would expand to be three hundred percent
on the x-axis okay let's do this with y
scale y
y plus equals 0.01 this element will
expand on the y-axis
then let's do both if
scale x
is greater than or equal to 2
or scale y is greater than or equal to 2
then increase both scale x and scale y
then this element will expand in both
directions or we could shrink an element
by scaling down scale x is less than or
equal to what about 0.1
do the same thing with scale y
less than or equal to
0.1
then let's decrement scale x and scale y
this will cause an image to shrink
so yeah those are a few simple
animations you can do with javascript if
you would like the code that i've
written here i'll post this in the
comments section down below and well
yeah those are a few simple animations
with javascript
hey guys in this video we're going to
draw some simple shapes using the canvas
api it's a means for drawing graphics
it's useful for animations games and
data visualization heading to our html
document we'll need to create a canvas
element
canvas
close it
i'll give this an id
my canvas
and we should probably set a width and a
height
width equals maybe 500
and height equals 500 as well
let's save there's no apparent change
but we do have a canvas here to better
visualize it heading to our css file
make sure that you link it within your
html file
we can begin styling the canvas i will
select my canvas
i'll add a border
border one pixel
solid
black
yeah and there's our canvas
you can also change the background color
too
background
color
and pick a color
maybe sky blue
that's pretty nice so this is our canvas
but just for demonstration purposes i'm
going to turn this line into a comment
we can begin drawing some shapes
let's head to our javascript file
i'm going to store my canvas within a
workable variable
let canvas
equal
document dot get
element by id the id is mycanvas
to draw on the canvas we need to get the
context
and i will store that within another
variable let context
equal
canvas dot get
context
and there's one argument
2d
imagine that context is a painting
within a picture frame and the canvas is
the picture and the frame together
that's how i imagine it at least to draw
on the canvas we need to draw on the
context the painting itself and not the
frame let's begin with a simple line i
would like to draw on the context to
begin drawing a line i will use the
begin
path method then we need starting
coordinates we'll begin in the top left
corner type context dot
move
2
then pass in a pair of coordinates the
top left corner of our canvas is zero
zero think of the move to method as if
we're placing our brush on the canvas
we're picking a starting position to
draw a line we have to use the line two
method
context
dot line two
then pass in another set of coordinates
so the bottom right corner over here
would be five hundred five hundred
then we will follow this with the stroke
method
context dot stroke
there and there's our line let's pick a
different set of coordinates what about
right in the middle so 250
250
you can continue this line in a
different direction just invoke the line
two method again
i'll take this line from the middle of
our canvas to the bottom now i'll follow
line two with another line two method
if i need to connect the line down here
i'll follow line two with two fifty
five 500
there so we have drawn two lines i would
like to draw a line from the top right
corner to the middle my brush is
currently down here i need to move this
brush to the top right corner
i will invoke the move two method
and the top right corner of my canvas
would have coordinates of
500 0.
then again invoke the line 2 method
and the middle is 250 250.
cool we have drawn some lines
we can set a line width currently the
width is one pixel
context dot line
width
equals what about 10
so we have some extra thick lines
you can also change the stroke color
context dot stroke
style
equals and pick a color this can be a
color name rgb values or hexadecimal
values
i'll say just purple
i like purple
we have some purple lines now that's how
to draw some lines on our canvas draw
lines this time we're going to create a
triangle to create a triangle we have to
use the line two method
we'll type context dot begin path
and end this with context dot stroke
we'll need to place our brush somewhere
maybe the top middle
to place our brush down we will use the
move to method context
move
two
so the coordinates of the top middle
would be
250
zero let's draw a line to the middle of
the left border
context
line
two
that would be
zero two fifty
let's draw another line
line two
maybe the opposite side
that would be 500
250
and another line
let's bring it back to the top
is 250
0.
there we have a triangle there is a fill
method to fill this triangle
in place of stroke you can use fill you
can pick a fill color
maybe you want more options than just
black
so that would be context
dot fill
style and pick a color
maybe yellow
if you need a border you can use the
stroke method along with the fill method
there we have a border around our
triangle
we can increase the border width
technically that's the stroke width
context dot line
width
equals maybe five
let's change that to maybe ten
there that's better to change the color
of the border all you have to do is set
the stroke style context dot stroke
style
equals
currently it's black maybe we can pick i
don't know gray
there we have a gray border
so that's how to draw a triangle next
we'll move to rectangles
to draw an empty rectangle we will use
the stroke rect method
context dot
stroke
rect
we'll need starting coordinates maybe
the top left corner that is 0 0
followed by a width and a height
so for the width 250 and the height 250
as well
there
we have a rectangle to change the stroke
style we can set the stroke style
property
context dot stroke
style
equals let's pick i don't know red
there so we have a red border
i think i'll change that to black though
if you need a filled rectangle
use the fill rect method so i'm going to
copy this paste it
and this would be
fill rect
so this will fill our rectangle if you
need to change the fill color we can set
the fill style property
context dot
fill
style
and pick a color maybe red again
there we have a red rectangle with a
black border to change the border
thickness you just have to change the
line width property
i'll keep that as it originally was
okay let's create another rectangle
so i'll copy this
paste it
i'll make the original one black let's
place the second rectangle directly
underneath the first
so the starting position would be
0
250
and the stroke would be 0 250 as well
there let's create another this will be
a
green square and the starting corner
will be 250 250 same thing with the
stroke okay last one let's fill in this
empty space
a blue square
and this will begin at this point
that is
250 0
for the coordinates
so yeah we have successfully drawn four
squares okay this time we're going to
draw a circle
context
dot
begin
path
and we will end the section with context
dot stroke
to draw a circle we will use the arc
method
context.arc
and there's a few arguments
starting coordinates for the center of
our circle
if i place the starting coordinates at 0
0
the center of my circle will begin in
the top left corner of my canvas
then a radius what about 100
for the next two arguments we need a
starting angle and ending angle in
radians
for a full circle that would be zero 2
then multiply 2 by
math dot pi
there well it's a part of a circle
but the center is starting the top left
corner i'll set the x and y coordinates
to 100
there that's much better
what about the middle 250
250
i'll increase the radius to maybe 200.
the starting angle and ending angle are
in radians
so you can change these for an
incomplete circle
if you ever need to reverse these
pass in true for the last argument
this would probably be helpful to you if
you have a pie chart to work on
okay let's fill the circle
context dot fill
let's change the color
that would be fill style context
fill style
i'll set this to maybe light blue let's
try draw bubble
and i'll give this a thicker stroke for
the border
context dot line with property equals
maybe 10.
i'll change the color as well
context dot stroke
style
equals
maybe dark blue
sweet
so yeah that's how to draw a circle
and for this last section we'll draw
some text
draw
text
to draw some text you would type context
dot
fill
text
what's some text we would like to add
maybe you win
then we need some coordinates let's
begin at zero zero
you can't really see it right now it's
above the top left corner let's bring it
down a little bit 100 100
there although it's very small let's
change the font
context
dot font property equals and pick a font
maybe 50 pixels and the font style will
be you know pick whatever you want but i
like mv bully
that's better
we can change the fill style that's the
font color
context dot
fill
style
equals maybe gray
now if you need to center some text
within a canvas this is what you can do
we'll need to calculate half of our
canvas's width
so as the second argument within the
fill text method type canvas dot width
divided by two do the same thing with
the height
canvas dot height divided by 2.
we're almost there
we will need to set the text align
property to center
preceding our fill text method
context dot
text
align
equals center
and that's how to center some text
so yeah everybody those are a few simple
shapes along with text that you can draw
on a canvas
if you would like a copy of this code
i'll post this in the comments section
down below and well yeah that's an
introduction to the canvas api in
javascript
hey guys in this video i'm going to
explain the window object it's an
interface used to talk with the web
browser and actually the dom the
document object model is a property of
the window let's examine this window
object i will use console.dir
and pass our window as an argument
here's our window object
it has its own properties and methods
one of which is document the document
object model by interacting with the
properties and methods of our window we
can change the behavior of our web
browser let's cover a few
i need the width and height of this
inner window to do that i would type
window dot inner width
and window dot inner height
i'll place these within console.log to
display it console.log
the inner width of this window is 383
pixels and the height is 263 but we
could change these
now the width is 488 and the height is
208 there's also outer width and outer
height
so these are now respectively 871 and
984 another is scroll x and scroll y but
we'll need some scroll bars within our
window i'll create a very large
development div
id equals my
div
i'll close it
and add these properties a width of 1000
a height of 1000 and a background color
so we have these scroll bars now within
our window
i can get the scroll x and scroll y
properties to shown how far that we have
scrolled console.log
window dot scroll x
and scroll
y
scroll x is this value 631 and scroll y
is this value 758. if i were to place
these back in their original positions
well then these values are both zero
that is scroll x and scroll y i'll get
rid of this div element
we can change the href property of this
window so that it redirects somewhere
else i'll display that
console.log
window now href is found within location
dot window.location.href
the current href property has this
address it's basically my web address
but we could redirect it somewhere else
window.location.href equals pick a
website maybe google https
colon2forwardslashes google.com
this should redirect me to google
yeah
hey if you need the host name that would
be
window dot location dot host name here's
my host name it's just a local ip
address
127.0.0.1 if you need the path name that
would be
window dot
location dot
path name
and my path name is forward slash
index.html for me this would be the
landing page here's a few useful methods
we're going to create a button though
button id equals my button
let's close it
i'll add some text just buttons fine
i'm going to select this button constant
my button
equals document
dot i'll use query selector this time
query selector
the id was my button
and let's add some event listeners
when i click on this button i would like
to open a new window
i'll take my button invoke the add event
listener method
when we click
i will perform a function i'll use an
arrow function expression
and i will invoke the windows open
method
when we click on this button it opens a
new window
you could pass the url within the open
method
i'll place this address for google as an
argument
then when i click on the button it takes
me to that website
another is close
window dot close
this will close the current window when
i click on this button it closes the
window okay another method is print
window dot print
and we can print the current page so
when i click this button
we initiate the process of printing this
page
we do have a few pop-ups too
window dot alert
i'll just display the message hello
hello
there's also window.confirm we can have
a user confirm something
press ok to continue
press ok to continue
window.prompt is another
window dot
prompt enter your age
let's store this within a variable
let age equal
window dot prompt
if age is less than 18
let's create an alert
window dot alert
you must be 18 plus to visit this site
then we will close the window window dot
close
okay enter your age let's say that i'm
12 i press ok
you must be 18 plus to visit the site
then it closes the window
well okay then everybody that is the
window object it's an interface used to
talk with the web browser there's a lot
of useful properties and methods related
to the window object if you would like a
copy of all my code i'll post all of
this in the comments section down below
and well yeah that's an introduction to
the window object using javascript
hey guys in this video i'm going to
explain cookies a cookie is a small text
file that is stored on your computer
it's used to remember information about
a user data within a cookie is saved in
name value pairs in order to check to
see if we have cookies enabled within
console.log i can type navigator dot
cookie
enabled
for me that's true i have cookies
enabled to add a cookie we would type
document.cookie
we will set the sequel to a string but
the string has certain components first
is a name value pair i would like to
create a cookie to store a user's first
name the name of this pair will be let's
say first name set the sequel to some
value the value that i will pick is
spongebob
then end it with a semicolon now you can
add an expiration date when the current
time has passed a certain expiration
date well then this cookie will be
deleted to set an expiration date set
expires equal to then pick a date i'll
pick sunday
first january
maybe a date that's really far out like
20 30.
at midnight
utc
then semicolon we're also able to set a
path for this cookie i'll use the
default path that would be path equals
forward slash okay let's take a look at
this cookie
console.log
document dot cookie even though this
appears to be a string it's actually an
object the expiration date and the path
aren't displayed all that's displayed is
the name and the value you can add more
than one cookie so again we will type
document.cookie
let's copy this text
paste it
last
name
last name equals square
pants
then let's take a look at our cookie
again
the cookie property of our document can
hold more than one cookie but to access
it you would just type cookie to
overwrite a cookie you would just change
the value of a name value pair if i
overwrite the first name and the last
name they'll change this time let's set
first name to patrick
last name star there we go first name
patrick last name star if we change the
expiration date to a date that has
already passed that will delete this
cookie it'll expire so maybe the last
name expired in the year 2000
that last name portion of my cookie is
no longer there so that's how to expire
a cookie at this point we're going to
create a function to create a cookie
instead of doing so manually
function set
cookie we'll need a few things
a name because these are a name value
pairs
a value
and an expiration date although that's
optional for the third argument let's
name this parameter days to live as an
argument you'll pass a number of days
that you would like this cookie to be
set to expire 365 would be one year
let's create a date object
const
date equals new date i will set the time
of this date date
dot set
time method within the parentheses we
will take date dot get time
this will return the current time in
milliseconds then add the amount of days
to live converted to milliseconds
days to live
times 24 hours
times
60 minutes
times 60 seconds
times 1000 for 1000 milliseconds our
future date is currently in milliseconds
we'll convert that to utc string date
to
utc
string method i'll assign this to a
variable
let
expires
equals
and then we'll use some string
concatenation we'll need to set this
expires value
so within quotes expires
equals plus
our future date converted to a utc
string then we can assign our cookie
document.cookie equals i'll use a
template literal
we're inserting our name that we pass in
equals
our value
add a semicolon to finish this section
then the expire section
expires
then you could also add a path if you
would like
path equals forward slash that's the
default path okay now let's create some
cookies i will invoke our set cookie
function
pass in a name value pair and the amount
of days i would like this cookie active
what about an email address
make up some email address
sponge
gmail.com
i would like this cookie to live for 365
days then let's display our cookies
console.log
document dot
cookie
and here's our cookies we still have our
first name and last name because we
never deleted them but we do have an
email now email equals sponge gmail.com
how can we delete a cookie all we have
to do is set the expiration date to a
pass date here's one easy way to do that
let's create function
delete
cookie
all we'll need is a name
what we'll do is invoke set cookie
pass our name as an argument
null for the value and null for the days
to live if i was to invoke the delete
cookie method and pass in the name email
well that email cookie is no longer in
here so it's gone let's delete the other
cookies too
delete
first name
delete last name
and those three cookies are cleared
let's create a function to get the value
of a cookie by a name let's declare this
function function
get
cookie
we'll accept a name as an argument what
we'll need to do is decode our cookie
i'll store this within a constant
constant
c for cookie
decoded
equals
decode
uri
component
then pass in
document.cookie
let's take a look at this
console.log
c decoded let's make sure we have at
least two cookies
set cookie
first name
spongebob
365 days to live
set cookie last name
squarepants
then i will invoke the getcookie method
then pass in a name first name is fine
okay let's see what we have this is
what's stored within c decoded we have
our name value pairs what we'll need to
do is split each of these name value
pairs at each of these semicolons that's
how to separate them so after this first
statement we'll take
c decoded
and split at each semicolon semicolon
space this will return an array we'll
store that within const
c
array
cookie array let's display cookie array
console.log cookie array each of those
name value pairs is now within separate
elements what we're going to do is for
each element we'll check to see if
there's a match between each of these
element names and the name that we're
looking for let's take our cookie array
c array
and use the for
each method
i'll use an arrow function expression
there is one parameter element arrow
what would we like to do for each
element
i'll use an if statement
let's check to see if
our element
at index of
the name that we're looking for
is equal to zero say that we're looking
for last name we'll iterate over each
element of our array and see if there's
a match we check the first element these
don't match but this one does if there's
a match then let's return the result
results
equals
and we'll create a substring
element.substring
name dot length plus one the length of
the name plus one will create a
substring and return this text so let's
declare
let result
at the end
return
result
actually i'm going to set result to null
okay let's see if this works
so we have two cookies
and i'm going to console.log
getcookie
pass in my first name
and that first name is spongebob
let's get last name
last name
spongebob and squarepants okay yeah
that's how to set delete and get cookies
let's take this a step further let's
create some text fields a submit button
and a get cookies button heading to our
html file let's create some text fields
and some labels
label
for
equals
first text
first name colon
close the label
input
id equals first text
i'll add a line break
let's do the same thing with last name
last text
last name
id is last text
i'll create a submit button
button id equals
submit
now let's name this btn for short submit
button
will be
submit
then a get cookies button
cookies btn for button the text will be
get
cookies
okay heading back to our javascript file
let's select these elements
const
first text
equals document
dot
query selector
we're selecting the id of first text
let's do the same thing with last text
our submit button
submit button
then cookie button
cookie
button
i'm going to add an event listener to
our submit button
submit button dot add
event
listener
the event attribute will be click
when we click we're going to perform an
arrow function expression
we will set the cookies according to
what these values are within these text
boxes we will invoke the set cookie
function
the name will be first name
the value will be whatever's within our
text boxes
first text
dot value
and days to live i'll set this to be a
year
365 days
let's do the same thing with our last
name
set cookie last name
last text.value
let's add an event listener to our
cookie button that will populate the
fields that function will search for any
cookies and return a value okay we have
cookie button add event listener
click
first text
dot value
equals
get
cookie
then the name of the cookie first name
do the same thing with last text last
text
value gut cookie
last name
whoops looks like i misspelt this id
cookie button now before we run this i'm
just going to delete our cookies
delete cookie
first name
delete cookie last name
then save and run it
so when i press get cookies well we
don't have any first name or last name
cookies there's nothing to populate
these text fields so i'm going to type
in a first name and a last name
spongebob
squarepants
press submit
this first name and last name are stored
as cookies now so i'm going to refresh
this page press that get cookies button
again that will populate these text
fields with the cookies i have so yeah
everybody that's an introduction to
cookies their small text files stored on
your computer they're used to remember
information about the user and they're
saved in name value pairs if you would
like a copy of all this code i know
there's a lot here i'll post all of this
in the comment section down below and
well yeah that's an introduction to
cookies using javascript
hey what's going on everybody it's you
bro hope you're doing well and in this
video we're going to create an
interactive stopwatch using javascript
so sit back relax and enjoy the show
sup guys let's create a stopwatch head
to your html file then we will create a
container to hold our stopwatch
div
id equals i'll name this time
container
then we're gonna close it within our
time container let's add a div for the
time display
id equals time display i'll add a time
zero zero
colon zero zero colon zero zero hours
minutes and seconds
let's close that div section we'll add
three buttons start pause and restart
button id equals
start button
i'll put this within a class class
equals
timer button
let's close the button add some text
the text will be start
let's copy this button
paste it two times
the second button is a pause button
the text will be pause
next will be a reset button reset the
text is reset
that is everything for our html file
let's head to our css file let's begin
by adding some properties to the timer
button class
i'll set a width
of 80 pixels
a height
of 30 pixels
a border
3 pixels solid is good
a border radius of
12 pixels
a background color
uh let's select a hexadecimal value pick
whatever color you want i'm going to
pick a dark gray color you can always
use a color picker to select the color
i'll set the color to be white
i'll set the cursor to be a pointer
when we hover our cursor over that
button then we have a cursor pointer
then i'll change the font family font
family
i'll pick this font
with the backup of monospace
yeah cool
let's change the time display right here
this is an id
time display
i'll edit the font size font dash size
this will be 75 pixels
i'll select a color
uh go ahead and pick a color
i'll select maybe
that that looks good
sweet i'll change the font family
then let's add a background color and
center everything
this will be our time container
text align
center
i'll add a border
3 pixel solid
border
radius of 25 pixels
background
color
of this is a dark gray color six twos
yeah there we go so there's our css
styling our css styling is done our html
file is done let's head to our
javascript file
let's select all the elements that we'll
need first is the time display let's get
that id
time display i'll store this as a
constant const time display equals
document
dot
query
selector
we're selecting an id
the id is time display
next is our start button let's copy this
paste it
start
button
start
button
then our pause
button pause button
pause button
then reset button
reset button
the id is reset button
here's the variables we'll need
let
start time
i'll go ahead and set this to zero right
away
let
elapsed time
equal zero
let
current time
equal zero
let paused this will be a boolean
variable
if our timer is currently paused we'll
set this to be true false if it's
running
let
interval id
let hours hrs is fine
equals zero
let
mins for minutes equals zero
let then sec four seconds
equals zero here's what we're going to
do we're going to add event listeners to
each of our buttons
start pause and reset
add
event
listener
i'll fill these in momentarily
pause button
then reset button
then we'll declare a function to update
our time
function
update time
let's fill in these event listeners
these will each be
click
we'll use an arrow function expression
i'll just copy this and paste it
okay let's begin with our start button
we'll check to see if paused is true
if
paused
we'll take paused
set it to false
calculate the start time
start time equals date dot now method
the now method of date will give you the
current date and time in milliseconds
minus elapsed
time which will initially be zero to
begin with
then we'll begin our timer
interval id
equals set
interval
we'll need a callback the callback will
be update time
let's invoke this function every maybe
75 milliseconds that should be good
enough
let's fill in the update time function
we'll calculate how much time is passed
elapsed time
equals
whatever time it is right now date.now
method
minus the original start time
this will be a time in milliseconds
we'll have to format it so that we can
display it within our timer
let's take our seconds
set the sql to
math.floor method
we will pass in our elapsed time
divided by 1000 because it's normally in
milliseconds modulus 60.
i'm going to put these within
parentheses
it's a similar process for minutes
except this section is 1000
times 60.
that will be 60 000 milliseconds in
every minute
let's calculate the hours
hours
1000 times 60
times 60.
then we'll need to update our display
that is time display
dot text
content
equals i'll use a template literal
will display the hours
colon
the minutes
then the seconds
let's take a look to see what we have so
far
we'll have one issue
let's press start
you can see that it's currently running
but when we display zeros i would like
two zeros let's add a zero as padding
for any single digit numbers
i'll create an inner function
function
pad
will accept a unit
we will return
this will be a ternary operator
it might be a little difficult to
understand
so we're going to add a zero to the
front of our unit whatever we pass in
hours minutes and seconds
we'll access the length property
if we add a zero to our unit
what's the length is that length greater
than two question mark
if it is
we'll simply return unit
otherwise
we'll prepend a zero plus unit
then we'll invoke the pad function
our seconds equals invoke pad
pass in our seconds
do the same thing with minutes and hours
minutes
hours
then let's move this line down
right about here
okay we should have some zeros as
padding now
yeah there we go one two three
so we have no way to pause this timer
let's work on that next
let's head to our pause button
we'll check to see if
not
paused
then we will set paused equal to true
we'll calculate the elapsed time
equals date dot now
minus our start time
this will save how much time has passed
in milliseconds
then clear our set interval method
clear
interval
we'll pass our id as an argument
okay now we should be able to start our
timer
one
two
three and pause
and you can see that it's paused
lastly reset this one's kind of easy
head to our reset button
we'll take paused
set that to true
clear our timer
take start elapsed and current time
set them all to zero
take hours minutes and seconds
set them to zero
then lastly change our time display to
all zeros
time
display
dot text
content
equals
zero zero colon zero zero colon zero
zero
oh then make sure you don't add this let
keyword then we're creating a local
variable
this should work now
one two three we can pause
we can reset we can start again
and reset all right everybody that is a
simple timer if you'd like to make a
more advanced version you could add
milliseconds and well yeah that's a
basic stopwatch using javascript
hey guys in this video we're going to
create a game of rock paper scissors
using javascript so sit back relax and
enjoy the show
all right then everybody in this video
we're going to be creating a game of
rock paper scissors we'll be using html
elements javascript code and styling
with css
let's head to our html document
i'll create a div section to contain our
game
div
id equals i'll name this game
div
we'll close it
i'll create three labels one for the
player the computer and the result who
won
these will be h1 header tags
i'll give each of these header tags a
class
class equals
game
text
i'll give the first h1 header tag a
unique id of player text
the second header tag will be computer
text
third will be
result text
the first h1 header tag will have this
initial text
player colon space
then
computer
colon space
result colon space
let's add three buttons
for rock paper scissors
button close it
each of these buttons will have a class
class
equals
choice
button
we'll need three buttons
add some text
rock
paper
scissors
that's everything for now
let's head to our javascript file
let's select all of the elements that
we'll need
we'll begin with the player text
const
player text
equals document dot
query
selector
we are selecting
an id that id was player text
we'll select the computer text
const
computer text the id was computer text
we'll select the result text
const
result text the id was result text
then we will select all of the buttons
const
choice
buttons
equals
document dot
query
selector
all
we are selecting the choice button class
we'll create three variables let player
to store the player's choice
let computer
for the computer's random choice
let result
to display who won
we'll iterate over our choice buttons
using the for each method
choice buttons
for each
we'll use an arrow function expression
for each button within our choice
buttons array
we will use an arrow function i'm going
to add an event listener to each of
these buttons within the arrow function
expression
button
dot
add
event
listener
the event is
click
when we click on a button we're going to
do something
within the ad event listener we'll add a
second arrow function expression
there are no arguments
arrow
we're gonna do a bunch of stuff
so let's expand this
when we click on a button what are we
going to do
let's take our player
this is our player's choice
set the sequel to
whatever button we select
and get the text content
if we click on this rock button then our
player variable contains the string rock
same thing goes with paper and scissors
if we select those then we will invoke
the computer's turn
computer
turn
function
we'll need to declare this function
outside of our for each method let's
declare this computer turn function
function computer turn
we'll select a random number between one
and three
const brand number
equals
math.floor
we'll need a random number
math.random method
there's only three choices we'll
multiply this by three
then add one
this will give us a random number
between one and three
we can examine this random number with a
switch
switch
rand number
we'll find any matching cases
case one
computer
will equal the string
rock
then break
case two computer equals paper
case three computer equals scissors
and that's it for the computer turn
function
the player variable will be assigned a
string as well as the computer
next what we'll need to do is set the
text with our choices
player text dot text
content
equals i'll use a template literal
player colon space
i'll add a placeholder
player
let's do the same thing with computer
computer text
text content
computer
computer
then the results text
result text dot text content
we will set the sql to
invoke a check winner function
we'll need to define this function
let's do that after the computer turn
function
function
check winner
first we'll compare if our player and
computer strings are the same
if player
is equal to computer
we will return a value
this will be a string
draw it's a tie
else if
computer
is equal to
rock
i'm going to return
then use the ternary operator our
condition is if
player
is equal to paper
question mark
if the computer is equal to rock
is the player equal to paper
if so then we will return a string
you
win
if this condition is false we'll return
a different string
you
lose
okay let's create another elsif
statement else if computer is equal to
paper
and the player is equal to
scissors
add another else if statement
else if the computer is equal to
scissors and the player is equal to rock
and that should be it let's test it
okay rock
it's a draw paper you lose
scissors you win
alright so that is the logic of our game
hey for fun let's style this using css
let's begin with our game development
that surrounds our game
let's take this id we will style game
div it's an id
i'll set the font
family
to
brush
script
mt
if my web browser can't display this
font i'll have a fallback of cursive
i'll add a border
three pixels solid
i'll round the corners
border
radius
25 pixels
that's better but let's add some padding
padding
10 pixels is good
i'll add a background color
background dash color
maybe light gray
i'll align the text in the center
text
align
center
okay we're getting somewhere
let's select these buttons they all have
the same class
that class is choice button
i like to add classes at the top
choice button class
let's change the line
height to
30 pixels
then set a width because all of these
buttons have different widths to
accommodate the text
i would like them all to be uniform
width
of
pixels is good
uh let's expand this a little bit
there let's select our player text
id player text
i'll change the color of the text color
pick a color
i'll be blue
let's do the same thing with computer
text
id computer text
i think the computer should be red
okay let's try this one last time
rock
paper
scissors
well alright everybody that is a basic
game of rock paper scissors for
beginners
if you would like a copy of my
javascript code as well as the html and
the css markup i'll post all of this in
the comments section down below and pin
it to the top be sure to check
underneath the original video in the
playlist but yeah that is a basic game
of rock paper scissors using javascript
hey what's going on everybody it's you
bro hope you're doing well and in this
video we're going to create a game of
tic-tac-toe using javascript so sit back
relax and enjoy the show
well all right everybody let's create a
game of tic-tac-toe let's create a div
element to contain our game
div
this will have an id of what about game
container
let's close it
i'll add a title
this will be an h1 header tag
the title will be
tick
tack
toe we'll create a div section for a
grid
div id equals
let's name this cell
container
it will contain nine cells for each of
the spaces
then let's close it
within our cell container div we're
going to create nine div tags
div
we'll create an attribute named
cell
index
i'll set the first equal to zero
add them to a class the class will be
cell
then close the div tag
let's copy this development and paste it
eight additional times so we should have
a total of nine
we have cell index zero one
two three four
five
six
seven
eight
outside of our cell container that ends
right here it looks like
we'll create an h2 header tag to display
some messages like whose turn it is who
won
so let's close this h2 header tag i will
give this an id of what about status
text
then we'll need a button
button
the id will be restart button
add some text
restart
okay that should be everything within
our html file let's head to our css
style sheet be sure to save everything
let's begin with the cell class
this is a class so use dot the name of
the class cell
i'll set a width of 75 pixels
a height
of 75 pixels
i'll add a
border 2 pixel solid is good
okay here's our div elements so far but
we got to put them in a grid they're all
in a single column
i'll select our cell container
we're selecting this by an id cell
container
the display
will be grid
grid
template
columns
repeat
three
auto
then we gotta set a width
width
225 pixels
margin
auto
yeah
let's head back to our cell class
let's add a box shadow
box
shadow
zero zero zero two pixels
all of these lines should have an even
thickness
i'll add a line height
of 75 pixels
just to test the x's and o's i'm going
to add an x like right here and an o
here
let's edit the font
font
size
50 pixels
when i move my cursor over these cells i
would like my cursor to be a pointer to
indicate that we can click on something
so cursor
pointer let's test that yeah there's our
pointer okay let's select our game
container i'm going to center everything
and change the font
game
container
i'll add a font
family
i'll select
permanent
marker i like that font
and a backup of cursive
then we just got to center everything
within this container
text align
center
yeah and that's our css style sheet
so let's get rid of this exyno that we
have i was just writing that there to
test it
okay so our html file is done our css
file is done let's head to our
javascript file
okay now we're within our javascript
file let's declare all of the variables
that we'll need
const
cells
equals
document dot
query
selector
all
we're selecting a class the cell class
dot cell
then let's select status text const
status text
document dot query selector
not query selector all
we are selecting
status
text
then our restart button
const
restart
button id
restart button
we need a constant of all of our win
conditions
const win
conditions
win conditions will be a two-dimensional
array of indices
if three cells all have the same
character we would need to check that
but we'll have to know what cells to
check
let's begin with the first row these
would have indices of 0 1 2 so let's add
that
zero one two
then the second row
three four five
six seven eight
then columns
zero three six
one four seven
two five eight
then the diagonals
zero four eight
two four six
and that's it
we'll need an array of placeholders i'll
name this options let options equals
options will be originally
an array of empty strings
we'll need nine of them
one for each cell
okay let's make sure we have nine
one two three four five six seven eight
nine
we'll need to keep track of the current
player
let's current
player equal x
then we'll need a boolean variable to
keep track if our game is running
let running equals
false
we'll switch this to true when we
initialize our game
let's create all of the different
functions that we'll need
function
initialize
game
function
cell clicked
function
update cell
there will be two parameters cell as
well as index
function
change player
function
check
winner
function
restart game
okay and that's the functions
when we begin our game let's initialize
the game
we'll use this function initialize game
to take care of any setup before we need
to start
we'll have to add some event listeners
to our cells
take our cells
then use the for
each method
we'll use an arrow function expression
for each cell
we will take our cell
add event
listener
the event will be click
we will add a callback of cell clicked
the second line will add an event
listener to our restart button
restart button
dot add event
listener
when we click
we are going to invoke the restart game
function
for the third line let's update our
status text
status text dot text
content
set the sequel to i'll use the template
literal
current
player
it's their turn
okay looks like we have one problem
looks like i accidentally capitalized
that l in current player okay let's work
on the cell clicked function
when we click on a cell what are we
going to do
i'll create a local variable
const
cell
index
i will set the sequel to
this
this refers to whatever cell that we
click on
we will get an attribute get
attribute
the attribute that we're getting is cell
index
we have an index number what we would
like to check to see is if that index
number within our options our
placeholders
are not empty we'll only want to update
a cell if there's nothing there
if
our options
at index of cell index
does not equal an empty space or if the
game is not
running
then we will return not do anything
otherwise
we will invoke the
update cell function
pass in this as an argument as well as
cell index
followed by
check
winner
function
okay let's head to the update cell
function
take
options
at index of the index parameter
set the sequel to the current player
so we're updating our placeholders
then change the text content of one of
these cells
whatever cell that we click on
originally
cell dot text
content
equals current player
now we should be able to click on at
least one of these cells
oh i forgot one thing when we initialize
our game we have to set running to true
running equals true
there
so we can click on one of these spaces
x
x x x
then we just need to change the player
take our current player
then we will set the sequel to then use
the ternary operator our condition is if
change player
is equal to x
if current player is equal to x we will
reassign our current player with
o
otherwise
x
then take status
text
dot
text
content
set the sequel to i'll use the template
literal
current player
it's their
turn
yeah just temporarily i'm going to
invoke this function after updating a
cell
now we should be able to alternate
between x's and o's
x o x o x o yeah we're good i'm going to
remove this i was just testing it to
make sure it works okay then head to our
check winner function we have a lot to
do here we'll create a temporary
variable of round one
i will set the sequel to false if
somebody wins we'll flip this to be true
we'll use a for loop we haven't used
those for a while
we will iterate over all of the win
conditions within our two-dimensional
array the first statement will be let i
equal zero
we'll continue this as long as i is less
than
our win
conditions dot length property
increment i by one we will iterate over
each inner array within win conditions
but let's store each of these arrays
within a temporary variable const
condition
equals
when condition
at our current index of i
each row has three indices
const cell a equals
our options
but at what index
while the index is going to be our
condition
at index 0 then we have cell b
cell b condition at one
cell c
condition index of two let me explain
how this is gonna work
let's head to the top we're iterating
over all of these inner arrays we'll
begin with the first we have three
indices zero one two we're going to
check within our options at these three
indices
zero one two at least that row to begin
with
if these three are not spaces and
they're all the same that means somebody
won if there is no winner we'll check
the next set of win conditions three
four and five
these are indices within our option at
these three indices
three four and five
if there are no spaces and they're all
the same character that means somebody
won we'll repeat this process for each
set of win conditions
so heading back down to our check winner
function we'll need to check if there's
any empty spaces
if
cell a
is equal to an empty space
or
cell b
is equal to an empty space
or
cell c
is equal to an empty space if there's an
empty space
we'll continue and skip this iteration
so if there are no empty spaces that
means all the spaces are full let's make
sure they're all the same character
if
cell a
is equal to
cell b
and
cell b
is equal to
cell c
that means we have a winner we'll take
our local variable of round one set the
sql to true
then break we don't need to continue
this for loop anymore we can break out
of it
outside of our for loop
if
round one is equal to true
let's update our status text right here
status
text dot text
content
is equal to i'll use a template literal
current
player
wins
running equals false the game is over
else if
so if there's no spaces left it's a draw
we could check that with this condition
take our options
then use the includes method
we'll check for any spaces
does our array include any spaces
precede this with the not logical
operator
if our options does not include any
spaces if this is true then we will
update our status text
to equal
draw
running equals false
else
we can change player change
player
okay let's try this
x o x o
x o
uh we should have a winner here yeah x
wins let's work on this restart button
to restart the game
we'll take current
player
set the sequel to x
take our options
i'll just copy this we're going to reset
them
so they're all empty spaces
status text
dot
text content
equals
i'll use a template literal
current players
turn
we'll have to clear each cell
take
our cells
use the for
each method
use an arrow function expression
for each cell
we will take that cell
update the text
content
equal to an empty space
then set running equal to true
okay let me make sure the game's a draw
first
okay draw i'm going to restart and we
have a new game
so yeah everybody that is a basic game
of tic-tac-toe if you would like a copy
of all this code i'll post this in the
comment section down below underneath
the original video in this playlist and
well yeah that's a basic game of
tic-tac-toe using javascript
hey what's going on everybody it's your
bro hope you're doing well and in this
video we're going to create a game of
snake using javascript so sit back relax
and enjoy the show
hey what is up everybody in this video
we're going to create a game of snake
let's head to our html file i'll create
a div as a container
div id equals game
container
let's close it
we'll be using a canvas to draw our
components
canvas the id will be
game
board
i'm gonna go ahead and set the width and
the height attributes right away
500 for the width
the height will be 500 as well
then close the canvas
i'll add a score
div
id equals score
let's close the div section the initial
score will be set to zero
then we'll need a reset button
button
close it
id equals
reset button the text is reset
okay let's work on our css styling
that's everything for our html file
let's select our game board
game
board
this is an id i'll add a border
border
3 pixel solid is good
let's enter everything within our game
container
game container
text align
center
i'll change the font of the score you
can barely see it
font
family
pick whatever font you like
one font that i like is permanent marker
permanent
marker
then a backup of cursive
let's change the font size font size 100
pixels
then let's work on our button next
reset button
i'll pick the same font family
the font size will be 22 pixels
a width of 100 pixels
a height of 50 pixels
border
4 pixels solid
border radius to round the corners
15 pixels
then cursor
pointer when we hover our cursor over
this button okay that is our css style
sheet and our index.html file let's head
to our javascript file
we have a lot of variables to declare
let's begin with the constants
const
game board
equals document dot
query
selector
we are selecting an id
that id is game board
that's our canvas
with a canvas to paint on the canvas we
have to get the context
const
ctx for context
equals game board
dot get
context
then pass in 2d
we'll store our score text as a variable
const
score text
equals document dot
query selector
we're selecting an id the id is
score
let's change this id to score text we're
already going to have a score variable
hey this is future bro so i forgot to
change that within my css style sheet
make sure you make that change here as
well
let's select our reset button
const
reset button
equals document dot
query selector
we are selecting our reset button
i'm going to create a variable to hold
the width of our game board
const
game width
equals
game board dot width
then game height
const game height
equals game board dot height
width and height are the attributes that
we assigned within our canvas
initially when we run this javascript
file if we would have declared those
within the css file they wouldn't have
been available to us right away that's
why i assigned these attributes within
the element itself inline we're going to
assign some colors the first is for the
board background
const
board
background
equals pick a color i'll just pick white
pick a color for your snake
const
snake color
i'll pick light green
but feel free to pick a different color
i'll add a black border around the snake
snake
border equals black
then we'll need some color for the food
const food color
equals
red it's an apple okay then a unit size
what's the size of everything within our
game
const
unit size
equals i'll pick 25 pixels now we'll
create a couple more variables
let
running equal false
we'll examine running to see if our game
is currently running or not
let
x
velocity x velocity will be how far we
move on the x-axis every single game
tick i will set this to be the unit size
we'll be moving 25 pixels on the x-axis
every game tick if x-velocity is a
positive number we'll move to the right
if it's negative we'll move to the left
then we have y velocity
let y
velocity equal zero that means we're not
moving up or down if we would like to
move down we would set this to unit size
if we would like to move up we would set
that to negative unit size to move up up
or down one space one unit but to begin
we'll just be moving to the right we'll
need the coordinates of our food
let
food x coordinate
let
food
why
we'll calculate these randomly later
within a function
let
score
equal zero
then we need our snake our snake is
going to be an array of objects an array
of parts
let
snake
equal
straight brackets it's an array
and we will create objects an object for
each body part each body part will have
an x and a y coordinate
let's begin with the tail
the tail will begin in the top left
corner so i will set those coordinates
0 0 is the top left corner
initially let's create 5 body parts to
the snake but after it eats its food
it's going to increase by one
let's add a second body part this is a
separate object separated with a comma
but i don't want this in the same space
i'll place this next body part to the
right of the first one so let's say x is
unit size
times one or just unit size i suppose
okay let's add another body part
unit size times two
so we'll have three squares
okay two more body parts unit size times
three
unit size times four
and that's our snake
it's an array of objects
body parts each object is a body part of
the snake they each have their own x and
y coordinates
let's add an event listener to our
window to listen for key events
window dot add
event
listener
the event is key down
we'll pass in a callback to a change
direction function
then we'll add an event listener to our
reset button to restart the game
reset
button
dot add
event
listener
when we click
we will invoke the reset game function
which we still need to declare
then we will invoke game start
let's declare the functions that we'll
need
let's begin with the first
function
game start
function
next tick
function
clear
board
clear board is going to be in charge of
repainting the board
function
create food
the create food function will find a
random place within our game board to
place a food item
function
draw food
we'll need to paint the food within our
game board
function
move
snake
function
draw snake
function
change direction
function
check
game over
function
display game over
then lastly
function
reset game
those are the functions
let's begin with the create food
function
we'll create an inner function
function
random food
there will be two parameters min
then max
within this function we'll return a
random number
return
rand
number
so to calculate this number we'll store
this within const rand
num
set the sequel to math
dot round
math
dot random
we will multiply this by
max
minus min
plus the minimum if there is one i think
i'm going to expand this
all right just to demonstrate this i'm
going to invoke the random food function
and store this within food x
food x equals random food
we'll pass the minimum zero
then the max
game
with
minus our unit size
temporarily i'm just going to display
whatever food x is i have to explain
something
then we will invoke this create food
function temporarily
i gotta explain something
currently when we're generating a random
number that random number is between
zero then our game width minus our unit
size every time i run this i have a
random number between that range however
i would like to divide the width and the
height of my game in two spaces
i will take this part of this expression
divided by
unit
size
now we'll receive a random space between
0 and 24 because 500 divided by 25
our unit size
is 25 available spaces
to accurately place the food in the top
left corner of one of these spaces
i will multiply all of this by unit size
so every time i refresh this you can see
that all of these numbers are divisible
by 25
and that's what we're looking for let's
create food why
food y
equals the same thing
okay that is our create food function
let's move on to the draw food function
this is fairly easy we'll take our
context
set the fill
style
equal to our food
color
take our context
fill
rect to fill a rectangle
we need a pair of coordinates
food x
food y
we need a width and a height
they are both going to be unit size
now if i were to invoke the draw food
function
after the create food function
this will draw a random food item every
time we refresh the page
that's what we're looking for that
completes the create food function and
the draw food function i'm going to
eliminate these two function calls
we're going to fill in the game start
function
we will set running equal to true our
game is currently running
we'll update the score
text
text
content to equal
whatever our score is initially it's
going to be zero
we'll invoke the create food function
then the draw food function
then lastly next tick
next tick is what we want to do every
round every time we update the clock
okay every time i refresh this an apple
should appear randomly within your game
board let's close the game start
function we'll work on the next tick
function we'll check to see if our game
is currently running
if
running
let's invoke the set timeout method
set timeout we'll use an arrow function
expression
there's a lot we have to do
we'll list an order of steps first we'll
clear the board clear board function
followed by
draw
food
move snake
draw snake
check game over
then invoke next tick again
so after the right curly brace
how often do we want a game tick to
occur
maybe 75 milliseconds that's a good
speed if you would like a slower speed
you can increase the number or decrease
the number for a faster speed i'll just
pick 75.
then we'll add an else statement
else
display
game over
if our game currently isn't running that
means the game's over
so that is the next tick function
let's work on clear board
this is fairly simple
we'll take our context
set the fill
style we'll take our fill style set the
sequel to board
background
this is a color that we picked
take our context
fill
wrecked
will begin in the top left corner zero
zero
will end in the bottom right corner
we will take our game width
for the width game height for the height
that's it for this function
let's work on draw snake
we'll need to change the fill style
context dot
fill
style
equals
snake
color
for my snake i picked green
if you have a border we can set the
stroke style context dot stroke
style
equals snake
border
we'll take our snake it's an array of
objects
so there is a for
each method
i'll use an arrow function expression
the argument is snake part
for every snake part
then within curly braces
i will take our context
fill
rectangle
snake
part each snake part has an x coordinate
and a y coordinate so we'll begin
painting wherever that snake part
currently is on the x-axis
and the y-axis
what's the width and the height of the
snake part well our unit size 25 pixels
and the height is 25 as well unit size
hey if you have a border we can fill
that in
let's copy this paste it
stroke
wrecked
looks like i misspelt something clear
board phil
rhett
not rexed okay and that will draw our
snake so now how do we move our snake
let's go to the move snake function
to move the snake we're going to create
a new head of the snake in the direction
that we're moving then eliminate the
tail
const
head
equals
then within curly braces
the x-coordinate will be r snake's
current head so that has an index of
zero take the x-coordinate of that
plus
our x velocity
how far are we moving on the x-axis this
will be a positive number if we're going
right a negative number if we're going
left okay then do the same thing with y
y equals snake
at index of zero
dot y
plus the y
velocity
then to add this new head to our snake
we can use the unshift method
snake dot on
shift
head
okay so our snake is just expanding now
we need to eliminate the tail
after each move i'll use an if else
statement
if
else
else will be snake dot pop
that will eliminate the tail every time
that we move
uh but i gotta fill in something for now
i'm just going to set this to be false
just temporarily
okay our snake should move now
within this if statement we'll check to
see if the food was eaten
if
food is eaten so that's a comment if the
head of our snake snake
at index zero
take the x-coordinate we will use the
comparison operator
is the x-coordinate of our snake
equal to the x-coordinate of our food
food x
and
let's copy this portion
the y coordinate of the head of the
snake is equal to
food y
if the head of the snake and the food
are overlapping
well then the snake has eaten the apple
let's increment the player score by one
score plus equals one
change the score text
score
text
dot text
content equals the new score
then create a new food object
create
food
we have no way to test this until we can
control our snake let's close out of
this function
then go to the change direction function
the change direction function should
have one parameter event we invoke this
function every time we press a key our
window is currently looking for the key
down event we'll store this within const
key
pressed set the sql to event
dot
key
code
so i'm going to display whatever key
pressed is currently with console.log
i'm going to click on my window and
press
up
down left right
each of those four arrow keys has a key
number that's what we're looking for
in fact i'm going to store those
let's say const
left
equals 37
const
right equals 39
const
up
equals 38
const
down
equals 40.
actually i'm gonna rearrange these so
that they're all in numeric order
much better this is how to determine
which way our snake is headed
i'll store these within some constants
const
going up
equals
we'll write a condition
is the y velocity of our snake
equal to
negative
unit size
so our unit size is currently 25. if the
y velocity of the snake is negative 25
that means we're moving up so let's do
the same with the other directions
going up
going
down
going
right going left
going down is going to be y velocity is
equal to
unit size positive then x velocity is
equal to
positive unit size
going left is x velocity is equal to
negative unit size
so these will be boolean variables
i'm going to write a switch
switch
will examine true against many matching
cases
the first case will be
key
pressed
is equal to left
and
we are not
going
right
we don't want to be able to move like to
the left then immediately to the right
because according to the rules of snake
if any body parts touch then we lose the
game we don't want to accidentally go
back into any body parts so if we're
going left we can continue to go left
otherwise up or down but not right
because then we lose the game if we
would like to go left then let's set the
x
velocity equal to
negative
unit size
take our y velocity
set that equal to zero we're no longer
going up or down
then break
let's add another case keypressed equals
up and we are not
going down
x velocity equals zero y velocity equals
negative unit size
we need another case
key pressed equals
right and we are not going left
x velocity equals unit size y velocity
equals zero
okay last one
key pressed equals down
and we are not going up
x velocity equals zero y velocity
equals unit size
okay we should be able to control our
snake now yeah there we go we can go up
left down right
so let's eat the apple and we should
expand and our score increases now let's
work on getting a game over because we
can go off the screen currently which we
should not be able to do
okay let's close out of this function
check game over
if we pass one of these borders then we
have a game over i'll write a switch to
check that
switch
will examine true
against many matching cases
the first case will be
is the head of our snake
snake at index zero
take the x coordinate
is that less than zero
that means we went over the left border
if this case evaluates to be true well
we have a matching case so let's take
running set the sequel to false
then break
so if i go over the left border the game
stops running okay let's add another
case
if the x coordinate of the head of our
snake
is greater than or equal to the game
width
now if we go over the right border
the game ends
take the y coordinate of the head of our
snake
check to see if it's
less
than zero that means we go over the top
the game's over then the last one is
case
y is greater than or equal to
game
height we shouldn't be able to go over
the bottom border yeah
awesome there is another game over
condition two if any body parts of the
snake overlap to check that i'm going to
use a for loop to iterate over the body
parts
four
then our index is going to be i we don't
want to begin at the head
let i equal one that's why i'm not using
the for each method our condition to
continue is i is less than snake dot
length property
increment i by one
we'll write an if statement
if
our snake
at index of i that's going to be one of
the body parts besides the head because
we're starting at one
if the x coordinate of that body part
is equal to
snake at index of zero
take that x coordinate
and let's copy this
paste it
change x to y
if the head of our snake is equal to one
of the body parts that means the game's
over
running equals false okay let's test
that
yeah the game just ended now we'll want
to display game over let's close out of
the check game over function then head
to display game over i'll take the
context
access the font set the sql to a font of
your choosing i'll pick 50 pixels
mv
bully
context dot fill
style
pick a color i'll just pick black
i'll center the text context
text align
equals
center
to draw some text on a canvas we'll type
context dot fill
text
add a string of text
game over
then your placement
i'll put this right in the middle
game
width divided by two
comma
game
height
divided by two
then set running
equal to false
okay so when we hit a border
it's game over
then when the head of our snake runs
into a body part it's also game over
the last thing we need to do is set up
the reset game function
we'll take our score set that back to
zero
take the x velocity
set that equal to unit size
take our y velocity
set that equal to zero
we'll recreate our snake
copy that
paste it but we're not going to use the
let keyword
then invoke the game start function
so after we get game over we should be
able to reset our game
yeah sweet well okay then everybody that
is a game of snake using javascript if
you would like a copy of all this code
i'll post this in the comments section
down below be sure to check the original
playlist and well yeah that's how to
create a game of snake using javascript
hey what's going on everybody it's you
bro hope you're doing well and in this
video we're going to create a game of
pong using javascript so sit back relax
and enjoy the show
all right let's begin everybody let's
create a div section to contain our game
div
close it
the id will be game
container
we'll add a canvas
canvas
close it
the id will be
game
board
i'll set a width and a height in line
the width will be 500
the height will be 500 we'll add a score
this will be another div section
id equals score
text
the initial text will be 0
colon 0
then a reset button
button
close it
the id is reset button
the text is reset
cool that's our html file let's head to
our css style sheet
id game board
border
3 pixel solid
let's change our score text next
score text
pick a font family font
family
pick a font that you like
then i'll add a backup
i'll change the font size to 100 pixels
that should be readable
okay let's work on the button
reset button
i'll set a font of permanent marker
then a backup of cursive
font
size
22 pixels
a width of 100 pixels
a height
of 50 pixels
border 4 pixels solid
border
radius
15 pixels
then cursor
pointer
when we hover our cursor over this
button the cursor is now a pointer then
let's enter everything i will select our
game container
text align
center
all right there we go so that's our css
style sheet and our html file let's head
to our javascript file
let's declare all the constants first
const game board
equals document dot
query selector
we are selecting our game board
const
context
equals game board
dot get
context
2d
context is what we draw on
const score text
equals document dot
query selector
we are selecting the score text
i'm just going to copy this
then we have our reset button
id is reset button
let's store the game with within a
variable what's the size of our canvas
const
game with
equals
game board dot width attribute
then we have height
game
height
equals game board dot height i'm only
storing them within a variable so that
they're accessible let's select some
colors
const
board
background
what color
i'll select forest green kind of like
it's a tennis court
const paddle one color
what color would you like the first
player to be i'll pick light blue
then paddle two
paddle two color
player two will be red
if you want you can add a border
const
paddle border
equals black
const ball color
i'll make this yellow like it's a tennis
ball
const
ball
border
color
i'll pick black
so what do we want the size of the ball
to be i'll store that as a constant
const
ball
radius
i'll set this to be
12.5
then the full diameter is 25 then our
paddle speed how far do we want our
paddles to move when we press down on a
button
paddle speed
equals 50. that's good enough
feel free to change this number if you'd
like now we have let
interval
id
let
ball speed
i'll set this to be one that will be the
lowest speed
then ball x and ball wide they will be
coordinates let ball x
equal initially i'll place the ball
right in the center of our game board
i will take game
width divided by two
then ball y is going to be
game height divided by two
let
ball x direction
i'll set that to be zero ball x
direction will be the direction in which
the ball is headed on the x axis
then ball
y direction
let player one score equal
zero
let player two score equal zero
we'll define two paddle objects
let paddle one
equal
this paddle will have a width property
of 25
a height
of 100
these are in pixels the starting x
coordinate will be zero all the way at
the left border
then y zero
so this petal will be in the top left
corner initially
so let's copy this paste it
change paddle one to paddle two
the width and the height will be the
same i would like paddle 2 to be on the
other side of my canvas
i will set x to equal game
width then i'm going to subtract
negative 25 whatever the width is if i
set x to be game with the left border is
going to be lined up with the right
border of my game board so i'm just
going to shift it over by the width 25
pixels so that you can actually see it
then y is game height
minus the height of our paddle
and those are the two paddles
let's add an event listener to the
window to listen for key down events
window dot add
event
listener
we will listen for
key down
then we will invoke a change direction
function
let's add an event listener to our reset
button
reset
button
dot add event listener
we are waiting for click
then invoke the reset game function
we'll still need to declare these two
functions when we would like to start
our game we'll invoke the game start
function then we'll need to declare
these functions the first function is
function
game start
we'll fill these in momentarily
function next
tick function
clear board
function
draw paddles
function create ball
function
move ball
function
draw ball
function
check
collision
function
change
direction function
update score
function
reset game
okay those are all the functions
why don't we begin by drawing the
paddles we'll start with the easy stuff
so we will take our context
set the stroke
style equal to the paddle
border
let's begin by drawing paddle one
context
dot fill
style
equals
paddle
one
color
context
fill
rectangle
the first two arguments are the x and
the y coordinate of the top left corner
of the rectangle
that will be
paddle one dot x
then paddle
one dot y
the next two arguments are the width and
the height of this rectangle
the width will be paddle one dot width
then paddle one dot height
to test this i'm going to invoke draw
paddles right after game start
temporarily okay there's our first
paddle but let's add a border we can
just copy this
paste it
change fill rect to stroke
rat
okay there is our first paddle let's
copy these three lines of code
paste it
change paddle one to paddle two
and there's our second paddle i'll
eliminate this function call
let's fill in game start when we begin
the game what are we going to do first
we'll create a ball
then invoke the next tick function
let's fill in the next tick function
we will take our set interval id
set this equal to
set
timeout method
we'll pass in a callback
then we'll add a routine what are all
the things that we're gonna do first we
will clear and redraw our board
clear
board
then draw
paddles
move
ball
draw ball
draw ball is going to have two arguments
ball x
ball y
and we should probably fill that in
within the parameters
there
then we will check collision
then invoke next tick
for another round i would like to repeat
this routine every 10 milliseconds
that is the next tick function let's
fill in the clear board function
all we're doing is redrawing our board
let's take our context
set the fill
style equal to the board
background
context dot
fill
rect
will begin in the top left corner 0 0
the width will be game width
the height will be game height
and that's our background
so that is the clear board function
we're redrawing our canvas
let's head to the change direction
function this will be in charge of
moving the paddles
but we'll need to know what key that we
pressed i'll store that as a constant
key
pressed
equals our event dot
key code
uh so we do have one parameter that's
event so fill that in let's display
whatever key pressed is
console.log key pressed
w has a key code of 87
s is 83.
the up arrow key is 38
the down arrow key is 40. so we can use
that for something
const paddle 1
up
equals 87
const paddle 1
down
equals 83
const paddle 2 up
is 38
const paddle 2 down
is 40. let's write a switch to look at
key pressed
switch we're examining key pressed
against many matching cases
the first case is
paddle one up
if we press up we will take
paddle one
axis the y property
minus equals our paddle
speed
you could also think of paddle speed as
paddle distance how far we're going to
move then break
so we should be able to move up
but we can't move down
paddle one
down
the y property of paddle one
plus equals paddle speed
by pressing s we can move down by
pressing w we can move up but currently
we're exiting the game board let's write
an if statement to check that
if
paddle 1 dot y is greater than zero
then we will move
then within the second case paddle one
down we'll write another if statement
if the y property of paddle one is
greater than
game
height
okay now check this out so we can't go
above the border
but we can go below the border up to a
certain point from game height we need
to subtract the height of our paddle
game height
minus
paddle
one
axis the height property we cannot go
above the game board
or below okay let's work on paddle two
case paddle 2 up
we'll check to see if paddle 2's y
property
is greater than zero
then we will take the y property of
paddle two
minus equals the paddle speed
so we cannot move paddle two above the
game board then our last case is paddle
two down
okay let's copy what we have here
within paddle one down
paste it but change paddle one to paddle
two
y property of paddle 2 plus equals the
paddle speed with paddle 2 we shouldn't
be able to go below or above the game
board these paddles are complete let's
close out of the change direction
function let's work on the draw drawball
function
we'll take the context
set the fill
style equal to the ball color
context dot stroke style
equals ball border
color
we can set a line width if we'd like
context dot line with
equals to
context
begin
path
context
arc to draw a circle
ball x
ball y
then the radius ball radius
zero this is for radians
two times math dot pi
context dot stroke method
context dot fill method
and there's our ball okay that is the
draw ball function let's head to the
create ball function when we create a
new ball let's set the ball
speed equal to one let's begin with the
x-axis
if
math
dot round
math
dot random
is equal to one
this part of the condition will give us
a random number between zero and one
if that number is one let's move to the
right if not let's move to the left so
if we would like to move to the right
let's set ball
x direction
equal to one
else
ball x direction
equals negative one we're moving to the
left okay let's copy these if else
statements
then change ball x to ball y
then when we create a new ball we'll set
it to be right in the middle set the
ball x coordinate equal to game width
divided by two
set the ball y coordinate to game
height divided by two
then invoke the draw ball function
pass in as arguments ball x ball y
that's the create ball function then we
need to move the ball
ball x plus equals
the ball's speed
times
the ball's direction ball x direction
then do the same thing with y
ball y plus equals ball speed times ball
y direction
so our ball should move in a random
direction
let's just test that by refreshing the
page
so let's close out of the move ball
function
now we'll need to check collisions
let's check to see if we hit the top
border if so then we'll bounce off of it
if
ball y
is greater than or equal to zero
plus
the ball radius remember the center of
the ball is where we place the x and y
coordinates so that's why we're adding
the ball radius to account for that if
we touch the top border let's change the
y direction
ball
y
direction
times equals negative one that will
reverse the direction
i'm just going to test that so we should
bounce off the top yeah let's check to
see if we hit the bottom border if ball
y
is greater than or equal to
game
height
minus ball radius
then we will change direction
okay let's check that
yep we just bounced off the bottom
what if we touch the left border
if
ball x is less than or equal to zero
let's update player two score
player two score
plus equals one
we'll update the score
create a new ball
then return
once we hit the left border that should
create a new ball yep there it is okay
let's copy this if statement
if ball x
is greater than or equal to
game
width
then we will update player one score
when we hit the right border
that creates a new ball
okay now this is the tough part we're
going to bounce off the paddles
i'm going to maximize the screen
if
ball x is less than or equal to this is
for paddle one
paddle one
take the x property
plus
paddle one
axis the width property
plus the ball radius
on the x-axis if so let's check the
y-axis
if
ball y
is greater than
paddle one
take the y property
and
ball
y
is less than
paddle one
dot y
plus paddle one
dot height
that means there's a collision
we'll take ball x
direction
multiply this by negative one
hey if you want for fun you can increase
the ball speed ball speed
plus equals one
okay we should be able to bounce off
this paddle yeah there we go okay let's
do the same thing with the right paddle
so i'm going to copy this section
paste it
is greater than or equal to
the x property of paddle 2
minus the ball radius
if ball y is greater than the y property
of paddle two
and
ball y is greater than the y property of
paddle two
plus paddle two's height
so we should be able to bounce off these
paddles now
then the ball speeds up
so we do have one situation where the
ball might get stuck
kind of like this
if that happens i'm just going to push
the ball out of the way
and move it forward
ball x equals
paddle one
take the x property
plus
paddle
one dot width plus
ball radius
this is if ball gets stuck
this line of code helps prevent the ball
from getting stuck within the paddle
this statement will be ball x equals
paddle two dot x
minus the ball radius
okay now let's update the score
update score
this one's easy
score text
dot text content
equals i'll use the template literal
player
one score
colon
player
two score
so we should be able to keep track of
the score
okay that's one
and one
lastly we have the reset button
reset game
player one
score equals zero
player two score equals zero
let's reset these paddles i'll just copy
them
paste them get rid of the let
keyword by setting the x and the y
coordinates that will put them in their
original positions
to demonstrate i'll press reset and they
go back to their respective corners
ball x equals zero
ball y equals zero
ball x
direction
equals zero
ball y direction
equals zero
will update the score
we'll invoke the clear
interval method pass in our interval id
then invoke game start again
okay we should be able to restart this
game
yeah there we go well okay then
everybody that is a game of pong using
javascript if you would like a copy of
this code i'll post this in the comment
section down below be sure to check the
original playlist and well yeah that's a
game of pong using javascript
you
Can't find what you're looking for?
Get subtitles in any language from opensubtitles.com, and translate them here.