Introduction to JavaScript
JavaScript is a programming language that enables dynamic and interactive web pages by responding to user actions and changing content dynamically.
Getting Started
- Setup a project with three files:
index.html,style.css, andindex.js - Use VS Code with the Live Server extension for automatic browser refresh.
- Basic HTML structure with linked CSS and JavaScript files. For a deeper understanding of HTML and CSS setup, refer to Comprehensive Guide to HTML and CSS: From Basics to Advanced Techniques.
Basic JavaScript Concepts
Output Methods
console.log()for debugging output in developer console.window.alert()for popup messages.- Changing HTML content by selecting elements via IDs and modifying
textContent.
Variables and Data Types
- Use
letto declare variables. - Data types: Numbers, Strings, Booleans.
- Variable assignment and reassignment.
- Template literals using backticks ` for embedding variables in strings.
Operators
- Arithmetic Operators:
+,-,*,/,%(modulus),**(exponent) - Augmented assignment:
+=,-=,*=,/= - Increment and decrement:
++,-- - Operator precedence important in complex expressions.
User Input
- Simple prompt with
window.prompt. - More professional input via HTML text boxes and buttons.
- Reading input values with
element.value.
Type Conversion
- User input is string by default; convert to number using
Number()or parse methods. - Convert between booleans, strings, and numbers as needed.
Control Flow
If Statements
- Conditional execution with
if,else if,else. - Nested conditions and logical operators (
&&,||,!). - Strict equality with
===and inequality with!==.
Loops
whileanddo whileloops for repeating code.forloops with initialization, condition, increment.- Loop control:
continueto skip iteration,breakto exit loop.
Functions
- Declaring and invoking functions.
- Parameters and arguments.
- Returning values with
return. - Function expressions and arrow functions for concise syntax.
Objects and Classes
- Objects with properties and methods.
thiskeyword reference to current object.- Constructors and class syntax for creating reusable blueprints.
- Inheritance with
extendsand usingsuperto call parent class constructor. - Static properties and methods belong to class itself.
- Getters and Setters for controlled access and validation of properties.
Arrays
- Arrays hold multiple values; access by index.
- Methods:
push,pop,shift,unshift,length. - Iterating arrays with
for, enhancedfor..ofloops,forEach. - Array transformation with
map, filtering withfilter, reduction withreduce. - Spread operator
...to expand arrays. - Rest parameters to bundle function arguments.
DOM Manipulation
- Selecting elements:
getElementById,getElementsByClassName,querySelector,querySelectorAll. - Changing styles, classes, attributes, and content.
- Creating, appending, and removing elements dynamically.
- DOM navigation: parents, children, siblings.
- For complementary knowledge on HTTP and Express.js related to web development, see Comprehensive Guide to HTTP Protocol and Express.js for Web Developers.
Event Handling
- Mouse events: click, mouseover, mouseout.
- Keyboard events: keydown, keyup.
- Adding event listeners with callback functions or arrow functions.
- Event object provides details about the event.
Asynchronous JavaScript
- Callback functions to handle async operations.
- Callback hell: nested callbacks that reduce readability.
- Promises: objects representing future completion or failure.
- Async/await syntax for writing asynchronous code in a synchronous style.
Working with APIs and External Data
- JSON data format for exchanging data.
- Fetch API for making HTTP requests.
- Handling errors and status codes when fetching data.
- Parsing JSON strings to JavaScript objects.
Sample Projects
- Digital Clock displaying real-time with zero-padded time and 12-hour format.
- Stopwatch with start, stop, reset and milliseconds display.
- Dice roller simulating multiple dice with images.
- Random password generator with configurable options.
- Rock-paper-scissors game with score tracking and colored results.
- Image slider with automatic cycling and manual navigation.
- Weather app fetching data from OpenWeatherMap API with city input, weather display, and emojis.
Summary
This course covers everything needed to begin using JavaScript for practical web development, starting from setting up the environment, learning the language basics, manipulating the DOM, handling events, working asynchronously with APIs and promises, and building engaging interactive projects. It provides a strong foundation for building your portfolio and advancing in JavaScript development.
For learners interested in broadening their programming expertise, recommended courses include Complete TypeScript Course: From Basics to Advanced React Integration and Comprehensive Python Course: From Basics to Advanced Mega Projects.
hey everybody today I decided I'm going to teach you everything you need to know to get started working with JavaScript
throughout this course we'll be working on a few projects you could add to your portfolio which include but are not
limited to a digital clock a stopwatch a functioning calculator a game of rock paper scissors an image
slider and our final project will be a weather app that fetches data from an API if that sounds good to you I
encourage you to sit back relax and enjoy the show hey if you don't mind please give this video a like post a
random comment down below and subscribe if you'd like to be a fellow bro it doesn't cost you anything thank
you JavaScript is a programming language used to create Dynamic and interactive web pages JavaScript runs on a web
browser such as Google Chrome Safari Edge whatever you use to browse the internet basically by using JavaScript
we can respond to user actions and transform user input whenever somebody interacts with our site in this example
I have a calculator written with HTML it's not very pretty and it doesn't function we have the framework that we
need at least though by applying CSS we can add color and style to this calculator but unfortunately it still
doesn't function by including JavaScript code this calculator can perform actions and is well useful so in this video I'm
going to show you everything you need to know to get started working with JavaScript I would recommend knowing
HTML and CSS before starting the series I do have a full free course on my channel if you're interested in learning
those or if you need a refresher if you don't know either you could probably still get by watching this video I'll
walk you through both as we go along throughout the series now before we do begin you will need a text editor one
text editor that I recommend is VSS code which you can download from code. visual studio.com for a step-by-step
instruction of how to install it feel free to check out the HTML and CSS series with that out of the way let's
Dive Right In so what we'll need to do is create a new project folder in vs code you can go to
the left toolbar go to explore we will open a folder I'll place this folder on my desktop just for convenience I will
create a new folder which I will name website to contain my website files let's select this
folder and we are now within our website folder we'll need three files an HTML file CSS file and JavaScript file we'll
begin with the HTML file we can close out of this welcome window I will name my HTML file
index.html in a website the index.html file is typically used as the homepage we have our HTML file next
comes the CSS file mine will be named style.css the CSS stylesheet is in charge of the overall appearance of the
web page this can include fonts colors positioning stuff like that then lastly we have the JavaScript file which I will
name index.js the Javascript file is in charge of the interactivity of a web
page so alt together we have structure style and actions so rearrange these tabs however you like I switch back and
forth between the JavaScript and HTML file quite often so I tend to put them right next to each other but do whatever
is most convenient for you so to generate the necessary text to create a web page in your HTML file in vs code
you can type exclamation point then hit tab so here you can change the title of your web page if you want I'll change my
title to be my website and that's all we'll need for
now now we'll need to link the stylesheet to the HTML file now we are going to create a link tag we can link
an external stylesheet to our HTML file within the link tag there is a relationship attribute shortened to re
the relationship ship will be stylesheet we are linking a stylesheet then the next attribute we need is the hre
attribute where is the CSS file located well it's right next to each other we only need the file name so we are
linking the CSS Styles sheet now our CSS stylesheet is linked to our HTML file now we need to link the Javascript file
to our HTML file we can do that by adding a pair of script tags we will set The Source attribute to
be the name of the JavaScript file index.js all right everything should now be linked together the last thing we'll
need is the live server extension in VSS code go to extensions we will search for live
server it should be this one we are going to install this extension so whenever we save any
changes to our files the web page should refresh automatically so now let's test this you
can go to file save or use the shortcut I'm just going to save everything I'm going to rightclick on
our HTML file then open with live server and here is our web page but it currently doesn't have anything uh let
me just minimize this I will readjust this window throughout this course I'll have VSS code alongside a web browser
with our HTML file we can add elements such as an H1 element these are typically used as headers I'm going to
say hello then save and that should update automatically or you can press the refresh button but since we have
live server installed we shouldn't need to then paragraphs are typically used for a paragraph a text in vs code to
generate a random paragraph of text you can type lauram then hit tab now we should have a random paragraph I believe
it's Latin at least it looks like it to change the style of our web page we can go to our stylesheet to change the style
of the body of our document we will select body I'll change the font family to something else font family how about
verdana there we now have a different font to increase the font size you can set the font size property to be either
in pixels or em personally I'm a fan of using em 2 em means 200% where 3 em is 300% but that's a
little too big let's stick with 2 em all right and that is everything we need to get started oh important note you do
want your script element at the bottom of the body of your document just in case there's an error with your
Javascript file you do want all of the HTML elements to at least render first before running any JavaScript code all
right so let's delete our H1 elements and our paragraph element we no longer need them for
now be sure to save everything we'll work with some basic output I'm going to zoom in a little bit to Output some text
you can type console.log add a set of parenthesis then a semicolon at the end within the
set of parentheses to Output some text you can either use double quotes single quotes or back ticks personally I'm a
fan of using these back ticks this is known as a template literal they're helpful with inserting variables which
we will discuss in the next lesson using either double quotes or single quotes or back ticks we can output some text let's
say the word hello be sure to save I'm holding contrl s on Windows there's no apparent output we have to go to Dev
tools so right click on your web page go to inspect then console and here's our
basic output hello for an additional line of output we can console.log again let's print print a different message I
like pizza let's save and here's my second line of text I like
pizza and I'm just going to move these windows a little bit that's better throughout much of the series we will be
working with this window again you have to right click on your web page go to inspect then go to
console now within our web page to create an alert box you can type window. alert at a set of parentheses semicolon
to the end we'll use a template literal we'll need a set of back ticks this is an alert this should
create a pop-up window this is an alert let's create
another let's copy what we have paste it I like pizza let's
save this is an alert okay I like pizza not sure why we need to tell a user that but we can now we have comments to
create a comment you type two forward slashes comments aren't used for output they're used as notes for yourself or
for other developers this is a comment so when I run this program then if we were to go
to our Dev tools we don't see this comment at all they're not displayed as output they're either used for notes for
yourself or for other people for a multi-line comment you can type a slash asterisk anything that comes after will
be a comment this is a comment you can see that the text is green that means it's a
comment again we should not be able to see these comments they're hidden I'm going to turn this JavaScript code into
comments just for the next part because these window alerts are kind of annoying to be
honest all right now what we're going to do is populate our web page page with some text within our HTML file I will
create an H1 element H1s are usually used for headers or titles there will be no text content
yet but I will set an ID I will give this H1 element a unique ID of my H1 feel free to pick a
different ID something you'll remember I will also create a paragraph element I will set the ID to equal my P
meaning my paragraph so remember there is no text content currently using JavaScript we will add some text content
first we need to select these elements by their ID my H1 and my p uh let's do that here we will type
document meaning the document of our web page do get element by ID do pay attention to the
capitalization what id are we getting let's start with my H1 so copy the ID paste it within the set of parentheses
be sure you're including quotes as well follow this with DOT text content we will set this equal to how about the
word hello let me zoom out a little again this can be back ticks single quotes or
double quotes all right let's type the word hello now when I save and and refresh the page that H1 element should
display the word hello now this time let's get our paragraph element with the ID of my P my
paragraph document. getet element by ID the ID that we're getting is my P will change the text content equal to uh what
can we say I like pizza there we go hello I like pizza all right
everybody so that's the basics of JavaScript when working with basic output you can use console.log which we
will be using a lot to create an alert you can use window. alert to change the text content of an HTML element you
first have to select that element then change the text content then set it equal to some text of you're choosing
all right everybody so that is the very basics of JavaScript and in the next topic we will cover
variables all right well it's time that we discuss variables do you remember from middle school or elementary school
when you learned algebra you had to solve for what the value of x was X was some representation of a value well
that's kind of what a variable is in programming it's a container that stores a value the variable behaves as if it
were the value it contains there's two steps to creating a variable declaration and assignment to use a variable we have
to first declare it it we'll use the let keyword then a unique variable name like X then a semicolon so what we've done is
declaration each variable name needs to be unique if I were to declare another variable named X we would run into an
error a syntax error identifier X has already been declared so your variable names need to be unique I can declare
two variables X and Y and they both have different names that is fine but they can't have the same name the next step
to create a variable is to assign it a value once you declare your variable you don't need to declare it again so I'm
going to assign X to equal some number like 100 we can use this variable X and it will behave as if it was the value
100 let me demonstrate so if I was to console.log X well then it's going to display 100 if
I were to change this value to 123 well X is now 123 you you can do both declaration and
assignment together that would look something like this let x equal
123 this is both declaration and assignment if you're creating a program and you know what your value should be
you can assign them a value right away sometimes you may want to accept some user input so then you might do
assignment later in two steps it's really up to how you write your program there's a few different data types in
JavaScript the first is number like 123 let's create a descriptive name for our variable like age we will store a user's
age according to my analytics in YouTube the average age of my viewers is 25 so let's say that my age is
25 then if I was to console.log my age variable it would behave as if it were the number 25 let's
create a few more variables another example of a number could be price let price equal 10 .99 maybe it's
$110.99 or some other unit of currency of you're choosing then we will console.log price
$10.99 what about a GPA a grade point average my grade point average is a solid 2.1 it's not great but C's get
degrees console.log GPA 2.1 using a template literal we can insert a variable using a placeholder
within console.log I will use back ticks let's write a sentence you are then to insert a variable use dollar sign curly
braces place your variable name within the curly braces then we can continue our sentence you are variable age years
old let's create another sentence using console.log the price is dollar sign curly
braces price the price is $10.99 I'm going to insert a dollar sign
before our price and that looks better feel free to choose some other unit of currency okay
let's add a sentence to display our GPA console.log your GPA is colon space we're inserting a variable we need
dollar sign curly braces we're displaying our GPA your GPA is 2.1 now if you need to
display the data type of a variable you can use console.log then preedee the variable
with the type of keyword what is the type of age age is a number type price is also a number type same
thing with GPA they're all numbers let's go over a different data type let's go over strings a string is a
series of characters let's say we have a user's first name to create a string you can either
use double quotes or single quotes personally I like double quotes then you can type in some characters like a first
name let's say my first name is bro feel free to pick your own first name I will display the type
of my first name variable and it says it's a string a series of characters then I will display my name
console.log first name and it is bro or whatever your first name is whatever you put here
let's include our variable within a template literal your name is add a placeholder
first name your name is bro what are some other examples of string maybe somebody's favorite food
favorite food my favorite food is pizza type in your favorite food
console.log you like at our placeholder favorite food you like pizza maybe if I like
something else like sushi well you like sushi okay another example of a string could be an email let email equals then
type in your email I'm just going to make one up bro
gmail.com console.log your email is email
your email is bro gmail.com let me make the G lowercase now an important thing with strings is that strings can contain
numbers after bro I'll add 1 two 3 so a string is a series of characters they can include numbers but we can't use
these numbers for any sort of math strings have a different behavior from numbers numbers we can use in arithmetic
Expressions strings not so much all right let's turn these lines into comment
then I will discuss booleans okay booleans are either true or false typically they're used as Flags
in your program let online equal true booleans are either true or false is somebody
online or are they offline this is either true or false I will display the type of my
variable online console.log type of online so online is a Boolean variable let's display our variable
within a template literal type in whatever your first name is bro is
online then I will insert a placeholder add my Boolean variable of online bro is online that is true if I
were to change this to false bro is online is false booleans are typically used as a sort of flag so another
example could be for sale is something for sale or not let's say that we are
selling I don't know cars is this car for sale I could set this to be true or
false let's console.log is this car for sale then I will add my Boolean variable
for sale is this car for sale that is true another example let's say that somebody
is enrolled in school like in college courses we could say let is student is somebody a student are they enrolled
this can be true or false console.log
enrolled colon space is student is the student enrolled in
classes that is true so those are booleans they're either true or false typically we don't use
them as direct output like you see here we usually use them with if statements to check something like if somebody's
online do this if not do something else is a car for sale if that's true then display the car if it's not then hide it
we'll have more practice with booleans when we reach if statements all right now what we're going to do is we will
close out a Dev tools we'll display some variables within our web page so let's delete everything we
have I'll create three variables let full name equals type in your full name feel free to add a space between
your first name and last name let age type in your age and
let student equals if you're a student type true if you're not in school type false
I am not in school anymore so I will type false we will go to our HTML file then add some HTML
elements I will add three paragraph elements so that's one 2 3 I will give my first paragraph an ID of
P1 then let's do the same with the other two paragraphs let's rename the second as P2 and the third as
P3 so to change the text content of an HTML element we're going to type document meaning the document of our web
page then we will get our element by its ID get element by ID then within a set of parentheses within a set of quotes we
will select the ID that we need let's start with P1 then add do text content to change the text content
then we will set this equal to a variable or a template literal let's begin with a variable so full
name our P1 element should display your full name let's do this with P2 I'm going to zoom out a little
bit P2 textcontent equals age it says that I'm 25 and then P3 let's display student or
better yet is student let's change that is student false I am not a student but you
might be though that might be true then let's display our variables along with some text using a template
literal let's copy our full name your name is add a placeholder place our variable name your name is Bro
Code or whatever your name is let's cut our age variable you
are variable age years old you are 25 years old and then let's cut is
student add a template literal let's say enrolled are you enrolled in
school add a placeholder paste our variable enrolled that is false I am not in school anymore more all right
everybody so those are variables it's a container that stores a value the variable behaves as if it were the value
it contains there's a couple different basic data types you have strings which is a series of text numbers and booleans
there's more advanced data types but we'll cover that later and well those are variables in
JavaScript yeah what's going on everybody so today I need to explain arithmetic operators because well
programming can sometimes involve a lot of M operand are values variables Etc in this equation 11 x and 5 are all operand
operators they can include but are not limited to addition subtraction multiplication and division in this
equation the addition sign would be the operator so there's a few things you should know regarding arithmetic
operators in JavaScript so let's begin let's pretend that in the scenario we are a teacher we have a group of
students let students equals what's a good class size maybe 30 students then I will
console.log my students variable and it should be 30 let's say that a new student joins the class and I
need to change this variable to increase students by one I can say students equals this will reassign my variable
equals the current value of students + 1 now we have 31 students now for subtraction that is the minus sign to
subtract a student we can reassign our variable students equals students minus one now we have
29 then we have multiplication which is represented by an asterisk we will double the number of
students we have students equals students as Risk 2 to multiply by two we have 6
students division is a forward slash we will split our class of students into two students divided two we now have
15 all right then we have exponents exponents is represented by double
asterisks what is students to the power of two 900 students that is a very large
class maybe it's a lecture or something in a college so students to the power of three that would be students to the
power of three would be 27,000 double asterisks is the exponent operator here's another helpful one it
is the modulus operator it gives you the remainder of any division so let's say we are going to divide our class into
two so modulus which is represented as a percent sign two well 30 divides by two evenly so the
remainder is zero if we had a class of 31 students well there's one remainder one
student students modulus 3 would divide my class of 31 students into three we would still have one student remaining
since we're reassigning students we would be replacing 31 students with the value of one if you're using the modulus
operator I would recommend creating a separate variable entit ly let extra students equal our students modulus 3 we
have one extra student just one okay that is the modulus operator there is a shortcut for writing
these Expressions because it can be kind of tedious to write the variable name twice so let's set students back to 30 I
will console.log students we'll use what is known as augmented assignment operators to increase students by a
number if we're reassigning it we can say students plus equals 1 or some other number students is now 31 if I were to
change one to be2 it's now 32 and 33 let's do the same thing with subtraction students minus equals
1 we now have 29 students multiplication students times equals 2 that would give
us 60 students students divided by equals 2 we have 15
students all right then exponents students to the power of equals 2 900
students then modulus students modulus equals 2 we have no remaining students 30
divides by 2 evenly so another place where modulus could be helpful is if you're determining if a number is even
or odd 30 is an even number divided by two the remainder is zero 31 is odd the remainder is one there's also the
increment and decrement operator there's a couple different ways to add one to a variable but you should be aware of all
of them to increase a variable by only one you can take the name of the variable then add Plus+ Plus+ is the
increment operator 30 incremented by 1 is 31 then there is the decrement operator which is minus
minus 30 decremented by 1 is 29 all right then lastly we're going to cover operator
precedence this is pretty important given a very complex equation such as this example in which order do you solve
each part of this equation so with operator precedence beginning with the left working our way to the right you
would solve anything with parentheses then exponents multiplication and division and modulo otherwise known as
modulus then lastly addition and subtraction let's go through the step by step let's see what the result variable
is I will console.log result so the result is 23 so if we were to walk through this
step by step let's solve anything with parentheses es starting from the left and then working our way to the right
there are no parentheses we can skip this step next is exponents there is one exponent here so we would solve 4 to ^
of 2 which is 16 then we will solve multiplication and division and modulus that's addition we
skip that we have multiplication 2 * 3 is 6 there is no more multiplication
division or modulus then lastly addition and subtraction 1 + 6 is 7 7 + 16 is our
result of 23 all right I'll give you a few more exercises how about this
equation the result is going to be six so there's no parenthesis no exponents we do have a modulus operator
here so we solve that first 12 modulus 5 gives us a remainder of two we have some division we would solve
that next 8 divid 2 is four then addition and subtraction the result is six all right here's a challenge
round the result is going to be 0468 we solve anything with parenthesis first 2 + 5 that is
7 then exponents 2 the^ of 7 I might need a calculator 2 * 2 3 4 5 6 7 that's 128
then we have 6 / 128 then we have 6 / 128 which is 046 875 and that is our result all right
everybody so that is everything you need to know about arithmetic operators you have operand which are values and
variables and arithmetic expression and operators there's also augmented assignment operators which is a shortcut
to writing these equations if you're you're going to reassign a variable then you have increment and decrement
operators to increase a variable by one or decrease it by one then with operator precedence if you're solving a complex
equation you solve each part of the equation following this order and well that is everything you need to know
regarding arithmetic operators and JavaScript yeah what's going on people so uh today I'm going to show you how we
can accept some user input in JavaScript generally there's two good ways of doing this the easy way is to create a window
prompt the professional way is to create an html text box of some sort and you'll likely need a button to submit the user
input let's begin with the easy way we'll create a window prompt the first thing we should do is declare all of the
variables we're going to use let's create a variable named username we'll declare it but not yet assign it then
when we assign it we can set username equal to then to create a window prompt we can type
window. prompt parentheses then within the parentheses
our window prompt can contain some text let's ask what's your username okay let's run this and see
what happens what's your username I will type in my username press
okay we have this variable username it will have a value but we should do something with it let's
console.log our username let's try that
again what's your username I'll type in my username feel free to type in yours let's check our Dev
tools and here is my username so that's the easy way to accept user input with this window
prompt you could assign declaration and assignment together if you want to you know that would also work now we will
accept user input the Prof profal Way by creating an html text box we will navigate to our HTML
file okay let's create an H1 element that says welcome we'll need a text box we'll use
a self-closing input tag I will set the ID of this text box to be my
text I'll create a label for this text box too because if we're a user we don't know what we're supposed to to type in
here I will create a label the text within the label will be username then a submit
button button the text will be submit I'll put this on a new line I'll
add a Break Tag maybe two to make it look nice for the ID of the button I'll set the ID to
be my submit let's see if this works this is a little Advanced when we click on this button we're going to
execute a function but we need to select this button we will access the document of our web
page get element by ID the ID that we're getting is the ID of the button my
submit So within quotes type the name of the ID follow this with DOT onclick
equals here we'll write everything we're going to do after clicking the button we need a function function parenthesis
curly braces everything between this set of curly braces is everything we'll do when we click on the button so first we
need a username variable outside of the function when we click on the button get the text from this text box we will
reassign our username then set this equal to the text from the text box we'll use document. getet element by
ID the ID that we're getting this time is my text we need the value of the text box
so follow this with DOT value all right then to test this let's console
log the username all right let's type in our username press submit then check Dev
tools yeah there it is okay let's replace console.log we'll change the text
content of our H1 element I will give this H1 element a unique ID let's say my
H1 we need to select my H1 ele El document. getet element by ID the ID was my
H1 we are changing the text content equal to let's use a template literal
hello username all right let's try this again type in your username press submit and
that should change the H1 element hello whatever your name is all right everybody so those are two different
ways to accept user input you can use a window prompt or you can use an html text boox and that is how to accept user
input in JavaScript all right so uh yeah type conversion type conversion is the
process of changing the data type of a value to another data type for example we can convert strings to numbers
numbers to booleans booleans to Strings numbers to strings booleans to numbers I think you get the idea why might we want
to do this well when we accept user input the data type of that input is a string if we need to use it for any sort
of math we need to convert it to a number here's an example let's say we have variable age I will create a window
prompt window. prompt we will ask a user how old are you I'm going to add one to our age age
plus equals 1 then console.log age how old are you let's say I'm 25 press
okay let's inspect our page go to console it shows that age is 251 when we accept user input it's a
string data type a series of characters by adding one we appended one to the end of our string we're not increasing our
age by one we're doing string conation we are going to convert our user input into a number and this is how so after
accepting our user input and before making any changes to it let's reassign age equal to and this is a function the
number function it will convert another data type such as a string or Boolean into a number then we'll place our age
variable within that function so now this should work how old are you let's say I'm 25 press okay
26 so that's the reason you may want to type convert because different data types behave differently along with my
age variable I'm going to display the type of age what's the data type how old are you 25 press okay 26 and it shows
that the data type of age is number if we removed this type conversion and then run this
again it shows that our age is 251 and it's a string which is not exactly what we would like that's a
reason why type conversion is important let me give you another example let's create three variables
let X let Y and let Z I'll show you what happens when we convert different values into different data types let's say x is
the word Pizza same thing with Y and Z I will typ Cast X as a
number then we need to place X within the number function I kind of want to see what happens when we try and convert
pizza into a number it's probably not going to go well let's convert Y into a string then Z will be a
Boolean let's console.log X as well as the type of X let's do the same thing with y and
z all right what's going to happen if you attempt to convert
alphabetical characters into a number that variable will be Nan which means not a number the data type is still
number though as you can see the word Pizza is already a string so converting it into a string really doesn't do
anything that's why for this line the value is still pizza and the data type is still a string if you convert a
string into a Boolean booleans again are either true or false converting the word pizza into a Boolean returns true and
the data type is Boolean so basically as long as there's some value here and you convert it into a Boolean it will always
be true let's replace pizza with zero what will happen we can convert zero into a number
it doesn't contain any alphabetical characters X contains zero it's a number Y is zero but it's treated as a
string Z contains true and it's a Boolean what about empty strings just a set of quotes typ casting an empty
string as a number is still zero we have an empty string for y then with our Boolean it's false why might you want to
typ cast a string as a Boolean that's one way in which you can check to see if user input is empty like did somebody
type something in if a user skipped user input it's it's most likely going to be an empty string then you can check to
see like if this is false then the user didn't type in anything and you can let them know what about a variable that's
declared but not assigned a value converting an undefined variable to a number results in not a number our
string is undefined and our Boolean variable returns false so that's the basics of
type conversion it's the process of changing the data type of a value to another it's pretty important when you
accept user input because when you accept user input it's a string data type at times you may want to convert it
to a number if you need to include that number with any sort of arithmetic expressions or a Boolean if you're
checking to see if that user input was completed we'll have more practice with this in the future and well that is type
conversion in JavaScript why hello so today I need to explain const const short for constants
are variables that can't be changed changed once you assign them in this example we're going to create a program
to calculate the circumference of a circle given a radius let's define our variables first we have Pi we'll begin
with using let then I'll show you the benefit of using const so let pi equals I'll use the first few digits of pi
3.14159 then we have let radius which we will assign later we'll ask for user input then let
circumference I think I spelled that right I can never spell circumference all right now we need to
ask the user what the radius is I will just use a window prompt radius equals window.
prompt enter the radius of a circle then once we have our radius when we accept user input it's a string data
type we need to convert our radius into a number by using the number function then once we have our radius we
can calculate the circumference by setting circumference equal to and here's the Formula 2 * pi * our radius
that the user enters in then once we have our circumference let's console.log our
circumference let's see if this works enter the radius of a circle I'll enter 10 press okay their circumference is
62.8 so why might you want to use a const in this program you may accidentally or somebody else may
maliciously change the value of a variable so that the program doesn't behave as intended for example somewhere
within my program I will set pi to be a new number pi equal 420.69 let's run this program again enter the
radius of a circle I'll enter 10 press okay and my circumference is 8,413 I may not realize that this is the
incorrect answer just for an extra security measure I can turn any variables that shouldn't change to be a
const a constant replace let with const and it is a good practice if you have any constants to make all of the letters
in the variable name uppercase so Pi is now Capital Pi hey this is bro from the future there's one thing I needed to
clarify that I forgot to mention capitalizing your constants is usually only done with primitive data types such
as numbers in booleans reference data types such as strings don't normally followed this convention you'll see this
in the next few upcoming videos Pi is a constant and we're assigning a number that's why I'm making it all uppercase
but if this was a string normally we wouldn't that is all let's try and change that variable again Pi = 420.69
so we have an uncaught type error assignment to constant variable so JavaScript won't let us reassign
constants once they are assigned once we can't make any changes to it once you declare a constant you can't change the
value and that's pretty helpful in a lot of circumstances it's an extra security measure what we'll do this time is
within our web page we will accept some user input via a text box we'll rewrite the same
program let's create an H1 element I will set the ID of the H1 element to be my
H1 and the text will be enter the radius of a circle I'll create a text box
input I'll set the type equal to text the ID equal to my text I'll create a label for this input
text box let's say radius I'll add a
button the button will say submit the ID will be my submit then I'll add to break
right after the text box to make it look nice let's get rid of console.log when we click on the submit
button we will execute a function we need to select the button let's take our
document get element by ID the ID is my submit follow this with DOT onclick
equals a function parentheses curly braces when we click on the button we'll execute any code within the curly braces
we can eliminate our window prompt we need to get the value from the text box again we can use document.
getet element by ID but the ID is going to be my text the text from the text box dot value get the value from the
text box box and we will assign that to radius then we will typ cast our input as a
number then we will calculate the circumference but since Pi is a constant make sure that the letters are uppercase
uppercase Pi once we have our circumference let's change an H3 element so let's add that
as well H3 the ID will be my H3 there will be no
text content then again we will get element by
ID the ID will be my H3 change the text content of this element to equal our
circumference okay let's try this the radius is 10 press submit and here is our circumference maybe this will be in
centimet so let me change that I'll use string concatenation and just add plus CM so 10 submit 62.83 CM if I attempt to
change the value of pi maybe I'll do that here pi equal 420.69
rerun the program 10 submit there doesn't appear to be a result so if we go to Dev tools go to
console we have that uncaught type error assignment to constant variable so again we can't change the value of a constant
there are more graceful ways of handling this we'll learn about that when we get to exception handling however this is
what we wanted we do not want to be able to change the value of a constant all right everybody so those are constants
it's just a variable that can't be changed once you assign it a value and well those are constants in
JavaScript hey what's going on everybody so in today's video we're going to create a counter program using
JavaScript HTML and CSS so sit back relax and enjoy the show all right let's begin everybody so what we're going to
do is start with our index.html file We'll add any necessary elements then we will style those elements with our CSS
file then lastly we will add functionality via JavaScript so let's begin with our HTML file within the body
of our document I will create a label to store the count so I will create a label with an
ID of count label the text will be zero it's a little small but that's okay we'll increase the font size with
CSS I'll add a break afterward with the Break Tag we'll need three buttons decrease reset and
increase so we have button one let's copy this button paste it two additional times the ID for the first button will
be decrease btn4 button the text will be
decrease then for the second button the ID will be reset button the text will be
reset then increase ID increase
button the text will be increase what I'm also going to do is place our buttons within a div
section let's let's cut our buttons then place the buttons within the
div I will give the div a unique ID of button container we'll Center align our button
container so it's in the middle of the window okay that is everything we need with our HTML file let's move to our CSS
file let's style the count label it's a little small right now I will select the ID count
label I will display the label as a block level element I will text align Center so it's
in the center of our screen let's increase the font size I tend to like to use the EM unit
of measurement the text will be 10 times the size
then let's change the font family pick a font of your choosing for this example I'll use
helvetica let's Center the button container that should surround all three buttons as you can see
here the ID was Button container text align Center okay the buttons should be in the
middle one thing I forgot to do uh let's actually add a class to our buttons too class
equals buttons there all right we will select the
buttons class I'll add some padding padding
10 pixels and 20 pixels let's increase the font size font size 1.5 em that translates to
150% let's pick a font color I'll just pick white then a background color for the
buttons background- color I'll use hsl values
how's that not feeling it that's pretty
good let's round the corners with border radius five pixels I'll change the cursor into a
pointer when we hover over a button cursor
pointer then we'll add a transition animation transition
background-color after 0.25 seconds then we'll apply the hover sudo class when we hover over one of the
buttons take our buttons class use the hover PSE sudo class we will change the back ground
color after a quarter of a second then change the background color to something slightly
darker yeah that looks good there should be a delay when you hover over one of the
buttons our HTML file is done same with our CSS now we need to add functionality because well these buttons don't do
anything I will individually assign all of these buttons so that each is stored within a
constant so const decrease button equals then we need to
select each button by accessing our document. getet element by ID what's the id we're selecting we will
begin with our decrease button all right then we need our reset button
reset button the ID is reset button then increase button increase button the ID is
increase button we need our count label okay then we will set
const count label equals then we need to get the of our count label so document. getet element by ID
count label then we will use let count equal
zero we'll be reassigning count we'll be incrementing and decrementing count with our HTML elements we do not plan on
reassigning them so we can set them as constants now we need a few functions three
functions one for each of these buttons decrease reset increase let's begin with increase so we are taking our increase
button that we assigned with the onclick attribute of this button set this equal to a
function what's it going to do when we want to increase this value of our count label let's increment count by one count
Plus+ then we will set the text content of our label count
label. text content equals whatever the count currently is let's see if this works it looks like I misspelled on
click all right let's see if this works yep every time we press the button our counter label increases by
one okay let's work on decrease really we can just copy this function
paste it let's change increase to decrease count minus minus save
everything and we should be able to increase and decrease then the reset
button let's copy one of these functions change decrease button to reset button when we want to reset we
will set count back to zero then update our count label with the current count which should be zero we
can increase we can decrease and we can reset then increase and decrease again
all right everybody so that is a counter program with JavaScript HTML and CSS hey what's going on everybody so
today I'm going to explain math math is a built-in JavaScript object that provides a collection of math related
properties and methods for example if you ever need the value of pi you would type math with a capital
m.p then let's console.log this console.log math.pi Pi is 3.14 and the rest of the
digits if you need e e is known as ul's number it's used for the base of natural logarithms we won't really using e in
the series but if you ever need it it's there math does give you access to a lot of useful math related methods let's
create a few variables let X = 3.21 let y equal to and let Z will be undefined if you need to round a number
let's say Z equals you can type math.round method Place whatever value or Vari variable you would like to round
within the round method let's round X store the result within Z then display z console.log z so 3.21 rounded is three
even there's also floor floor will always round down let's change 3.21 to
3.99 let's copy this line paste it change round to floor floor always rounds down so 3.99 rounded
down is again three to always round up you can use seal as in sealing the opposite of
floor c l let's change 3.99 to 3.21 3.21 rounded up is four then there's
truncate trunk short for truncate will eliminate any decimal portion 3.21 truncated is three another way to raise
a base to a given power is to use the pow method P let's raise 3 to the power of 2 so x
to the power of Y which would be 9 y to the power of X would be 8 there's a square root function
sqrt let's find the square root of how about 81 the square root of 81 is 9 if you ever need to find the natural
logarithm of a number you can use the log function math.log let's set X to be 10 the natural logarithm of 10 is
2.3 if you need to do anything with trigonometry there's s cosine and tangent functions
let's begin with sign s n within this function you will place radians I'll set X to be
45 so Z is going to be 0.85 so that's s let's do cosine which is
cosos 0.52 then tangent
T and that is 1.61 let's change X to be 3.21
again to find the absolute value of a number you can use the absolute value function
math.abs it's basically going to give you the same number but it's going to be
positive the absolute value of - 3.21 is 3.21 basically we're eliminating the negative
sign to find the sign of a number you can use the sign function s i g
n so the sign of - 3.21 is1 If This Were a positive number it would be one if it's
zero then the sign is zero here's a pretty helpful method we can find the maximum or minimum value from a set of
values or variables let's set Z to be one y will stay as two and X will be three I will create a new variable named
Max it will store the maximum value from these three variables math.
Max comma separate each of the variables x y z then display the maximum within our console.log method the maximum value
from these three variables is three then there's Min for the minimum let
Min do min so the minimum of these three variables is one all right everybody so that's math it's a built-in JavaScript
object that provides a collection of properties which was pi and d and methods such as round truncate power
methods related to trigonometry and Max and Min methods they're pretty helpful if you ever need them and well that is
what math is in JavaScript hey hey what's going on everybody so in today's video we're
going to create a random number generator but first I need to explain how to create a random number in
JavaScript let's store our random number within a variable which we will name random num to create a random number in
JavaScript we can use the random method of math math. random method this will generate a random number between zero
and one uh but it looks like we forgot to Output our random number so let's do do that with
console.log console.log random num this will generate a random number between zero and one it will give us a number
with a long decimal portion most likely let's say we would like to roll a six-sided dice I need a random number
between 1 and six not including the decimal portion so the first step is that we will multiply math. random *
6 what this will do is give us a random number between 0 and 6 exclusive now I don't want the decimal portion I would
like a whole integer we'll enclose this equation with the floor method of math math. floor then we will enclose our
equation so now we have oops it looks like I misspelled math it should be Capital there so far a random number is
going to be between zero and five so there's zero and there's
five but I need one through six well we can increase the minimum by adding plus one or whatever you want the minimum to
be so now that should give us a random number between one and six there's
six and there's one for a random number between 1 and 100 I can set the maximum to be 100 math. random * 100 + 1 so now
the number is going to be between 1 and 100 if you're looking for a random number between a certain range let's say
50 and 100 well we're going to change our equation just to make this easier to
read I'm going to set two constants const Min what's the minimum let's say 50 and the max const max will be 100
let's replace 100 with our maximum and one with our minimum there's one additional change we need to make for
example our random number is 139 we're multiplying math. random times 100 our maximum then adding an
additional 50 to it so one change we're going to make is that we will subtract our minimum from our maximum then I will
surround this portion of our equation with the set of parentheses just to force operator precedence now the random
number should be between 50 and 100 so depending on the range of numbers you're looking for you can change the minimum
and the maximum all right now with that out of the way let's create our random number generator let's go to our HTML
file I will create a button the ID will be my button the text on the button will be roll we will roll
a six-sided dice within our CSS stylesheet I will set the text of the body of our document the font family I
will set to be verdana cuz I like that font two to Center align everything to make this easy I will set text align
Center all right we're getting somewhere let's work on the button I will select the ID of my button I will change the
font size of the button to be three em meaning 300% I'll add a little bit of padding
within our button 5 pixels by 25 pixels and I will set the Border radius to be 5 pixels
just to smooth the corners we're also going to need a label so let's go back to our HTML file I will
add a label with an ID of my label within our CSS stylesheet I will
select the ID of my label then change the font size to be 3 em so be sure to save your CSS file save your HTML file
then within our JavaScript file we will need to get our button and the label we'll store those within some
constants const my button equals document. getet element by ID the ID of the element we're getting is my
button then we will need to get my label my label the ID is my
label let's set a minimum const Min equals I'll set that to be one as if we're rolling a six-sided dice const Max
equals 6 then let random num we'll declare a random number variable but not assign it
quite yet okay when we click on the button we'll execute a function we will take my button
with the unclick attribute I will set this equal to a function what's the function going to do it's going to roll
a random number random num equals math. random times our maximum we'll enclose this equation with
math. floor to round it math. floor then add our minimum then we will change the text
content of my label to display it my label. text content equals our random num when we click on the button it
should roll a random number uh what are we missing not a number oh okay it looks like I made a
mistake I forgot to add a set of print this is after random there we go I'm going to put the
number on a new line so within our HTML file I'm just going to add a Break Tag there we go let's save everything roll
again so I roll a 6 3 1 2 5 3 let's say we would like to roll three dice not just one we'll make a few
changes I will replace my label with label one for the ID then I'm going to add a break after
okay let's copy our label paste it two times we'll need labels two and three I'll also give the labels a class
of my labels we can apply CSS styling to an entire class to make it easy all right
within our CSS stylesheet let's replace the ID of my label with the class of my labels be sure to save all of your files
then within our Javascript file let's replace my label with label one the ID is label one
copy this line of code then we need labels two and three label two label three let's rename random num as random
num one copy it paste it two times then we need random number two random number
three within our function for our button change random num to be random num one copy this line paste it two times then
we need random number two random number three we'll change the text content of my label to be label
one equals random num one copy this line paste it two times change one to B2 then for the third line change one to
be three what we'll do now is generate three random numbers between 1 and six as if we're rolling three dice 232 361
225 all right everybody that's how to create a random number generator in JavaScript Hey so uh what's going on
everybody today I got to explain if statements so in JavaScript if a condition of our choosing is true we can
execute some code if it's not true we can do something else that's how to put it simply for example let's say we have
a user's age let age equals 25 to write an if statement we can type if a set of parentheses then a set of
curly braces within the set of parenthesis we can check a condition let's check to see if our age variable
is greater than or equal to 18 if this condition is true we can execute whatever code is within the set of curly
braces if this condition is true let's console.log a message you are old enough to enter
enter this site my age is 25 this condition is true we will execute this code within the curly braces you are old
enough to enter this site what if my age was 13 well if this condition is true we
don't do this we don't execute it we skip over it if you would rather take a different course of action if you would
rather do something else you can write an else clause
if this is not true we will do whatever is within the else Clause let's display a different
message you must be 18 plus to enter this site my age is
13 we will end up displaying you must be 18 plus to enter this site basically speaking if this condition is true do
this else if not do this instead it's kind of like a fork in the road which path are we going to take here's
another example let's say we have variable time time will be in hours in military time if our time is 9 as in 9
a.m. let's write an if statement if time is less than 12 as in noon then
console.log good morning else if it's after 12 that means
it's at least the afternoon console.log good
afternoon the time is 9: as in 9:00 a.m. good morning what if our time was 14 like 1400 in military time well then we
will display good afternoon conditions also work very well with Boolean variables let's create a Boolean
variable is student if you're a student say true if not then
false now with a Boolean variable if you need to check the value with an if statement you can just place the Boolean
variable within the condition itself the condition either evaluates to be true or false
if is student is true then console.log you are a student
else console.log you are not a student is student equals false we will
execute the else Clause you are not a student If This Were true will execute the if Clause you are a
student you can even create nested if statements this time we will have two variables let age equals some age and
let has license as in a driver's license uh that's how to spell license has license will either be true
or false so in the United States you need to be at least 16 years old to have your Li
we'll check that first if age is greater than or equal to 16 let's
console.log you are old enough to drive else
console.log you must be 6 plus to have a license if I changed my age to 15 well I'm not old enough to have a
license at least in the United States it might vary depending on your country let me know in the comments section how old
you have to be to get a driver's license I'm kind of curious you can use another if statement within an if statement
after we check to see if somebody is old enough to have a license let's check to see if they do have a license or
not so I will add another if statement within our if statement pay attention to the
indentation if has license since we're checking a Boolean
variable that is going to be the condition itself it evaluates to be true or false if has license
console.log you have your license else again pay attention to the indentation
console.log you do not have your license yet my age is 15 I don't have a license this is the
result you must be 16 plus to have your license since this condition is false we skip over everything within curly Braes
entirely if I set my age to be 18 you are old enough to drive but I don't have a license that's set to false
you do not have your license yet so we execute this condition so we enter anything within this set of curly braces
we display this message then check this if statement my condition is false then we will execute the else
Clause if I set has license to be true well then you are old enough to drive you have your
license all right now I need to discuss else if statements we will keep our age variable
we have our if statement if age is greater than or equal to 18 then we will
console.log you are old enough to enter this site else
console.log you must be 18 plus to enter this site my age is 18 I can enter this site if my age was 12 I can't enter
the site if there's any other conditions you want to check before reaching your else statement you can add an else if
Clause then you can check another condition let's check to see if somebody's age is less than zero your
age can't be below zero let's let the user know console.log your age can't
be below zero I will set my age to be1 that's not
possible your age can't be below zero since this condition is false we skip over this Clause then move on to the
next condition else if this condition is true execute this clause which it was then it's not necessary to go to the
else statement because we already executed one of these Clauses you can add as many else if statements as you
would like let's add another else if let's check to see if somebody is over 100 years
old age is greater than or equal to 100 console.log you are too old to enter
this site okay now pay attention to this it's really important my age will be
101 you are old enough to enter this site so why didn't we execute this Clause our age is greater than or equal
to 100 the order of our Clauses does matter we start at the top and work our way down and check all the conditions on
the way down so with our first statement this if state age is greater than or equal to 18 101
is greater than or equal to 18 we will execute this clause and skip over everything else that comes after even
though this response is more appropriate for what we're looking for we still skip over it even though this is true because
we executed this one first so I would recommend that we move this Clause to the beginning and change it to an if
statement first let's check to see if age is greater than or equal to 100 else if age is greater than or equal
to 18 so this should work as intended our age is 101 you are too old to enter the site let's add another lsif Clause
so to check to see if two values are equal you got to use the comparison operator which is two equal signs let me
give you a demonstration else if let's check to see if somebody's age
is directly equal to zero so be sure you're using two equal signs for a comparison not one one equal sign is the
assignment operator you want two equal signs to see if two values are equal if somebody's age is exactly zero
will display a custom message you can't enter you were just born if somebody's age is zero they're a
baby or an infant so let's set our our age to be zero you can't enter you were just born
this condition is false we skip this Clause this condition was true we execute this clause and Skip everything
else that comes after using all this code let's work on an exercise we're going to create a text box and a button
so somebody can submit their age then depending on what they enter we will display a message so within our HTML
file we'll create a few things let's create a label the text on the label will be enter your
age let's add a break after then a text box the label will be input the type will be
text the ID will be my text I'll add a break we'll create a submit
button button type equals submit the ID will be my
submit the text on the button will be submit I will also create a paragraph element the ID let's say is
result element to display a result all right that is everything we'll need so we can't see the paragraph element quite
yet the text content of the result element will be one of these lines of text so let's go back to our index file
we'll create our elements I will set them to be constants
const my text equals document. getet element by ID the ID is going to be my
text and const my submit that's the submit button document. getet element by ID the ID is
going to be my submit then lastly result
element const result element equals document. getet element by ID the ID is result
element let's scoot these if statements down when I click on the button we will execute a function the button is named
my submit my submit onclick attribute equals a function when we click on the
button what are we going to do let's take all of our if else if and else Clauses cut them then paste them within
the function for the button when we click on the button then we will check our age let's set this variable to be
undefined then we will get our age from the text box age equals my
text. value get the value from the text box and assign it to age but remember when we get text from a text box it's a
string data type we need to typ cast it to a number so we will set age to equal then use the number function to
convert it to a number then we can check our age we'll replace console.log with the text content of the result element
result element. text content equals our message I'll use a template literal so I'll use back
ticks let's copy our text paste it within the template literal then I will delete the console.log message so we'll
just follow this pattern result element. textcontent equals our
message all right let's see if this works so we will type in our age let's say I'm 25
press submit and we have one problem let's see what's going
on oops okay so I forgot to add a set of parentheses after the function let's add that let's say I'm 25 press submit you
are old enough to enter the site let's say I'm 12 you must be 18 plus to enter the site what if I'm
101 you are too old to enter the site what if I'm zero you can't enter you were just
born I'm negative 1 your age can't be below zero all right everybody so that is everything you need to know to to get
started working with if statements in JavaScript hey uh so today I'm going to explain the checked property in
JavaScript the checked property determines the checked state of an HTML checkbox or a radio button element by
examining this property we can determine if a check boox is checked or a radio button is selected in this program if I
were to not select any of these buttons we have a different result within our HTML file we will create an input
element the type is going to equal checkbox then for the ID I will set this equal to my
checkbox and here is our checkbox we should probably add a label so that people know what this is
for so the label I will set the four attribute to be my
checkbox what's the label going to say let's say subscribe like a subscribe button
utilizing the four attribute if the four attribute is the same as the ID when we click on the label it should still
select the checkbox all right let's add a break then we will create some radio
buttons we will again need an input element the type this time will not be a checkbox it will be radio for the ID
this will be a Visa button I'm going to abbreviate button to BTN so pay attention to
that then I will create a label for this radio button we will set the four attribute to
be the same as the ID then the text will be Visa I'm going to add a
break okay let's copy this radio button paste it two times we'll change the second visa to be
MasterCard let's change the ID first Master Card let's copy the ID paste it within
the four attribute of the second label then change the text Master Card then the third ID will be PayPal
button then change the four attribute and the text
PayPal so with radio buttons they should all be within the same group currently they're not so I can select all of them
if I would like we should only be able to select one from any group we will group these radio buttons by their name
attribute they should all have the same name the name let's say is card so let's copy this attribute and paste it within
the other input elements now we should only be able to select one and that appears to work lastly let's create a
submit button we are creating a button the text will be
submit the type is submit and for the ID the ID will be my submit I will create a paragraph element
will populate it with some text depending if subscribe is checked or not same thing goes with our r
buttons I will create two paragraphs after our button the ID on the first
paragraph let's name sub result there will be no text content to begin with we'll change the text content of our sub
result paragraph with some text that states if the user is subscribed or not we'll create another paragraph for the
radio buttons again there's going to be no text content I'll set the idea this paragraph to be payment
result now before we move to our JavaScript file I'm just going to edit the CSS on the button to make it a
little bit bigger so you guys can read it so the ID of that button was my submit we are selecting an ID my submit
I will set the font size to be 1 em and that's probably good enough uh maybe I'll add one more break after the
Subscribe button and the PayPal radio button just so that it's not as
cramped that's decent enough okay so be sure to save your CSS file your HTML file then we are now within our
Javascript file what we're going to do now is get these elements by their ID and store them within constants so
they're easier to work with okay let's start with our checkbox so the checkbox had an ID of my
checkbox const my check checkbox be sure to pay attention to the capitalization feel free to change that if you would
like just be sure it's consistent with what you have currently with your HTML elements we are accessing the document
of our web page get element by ID the ID is going to be my checkbox and that's it so let's get the
other elements we have my checkbox then we have our Visa button const Visa button get element by ID Visa
button then let's repeat this with our MasterCard button again pay attention to the capitalization it's pretty
important then we have our PayPal button we need our submit button next my
submit then our paragraph elements sub result then payment
result all right here are all the constants that we'll need so when we click on the submit button we will
execute a function so we are taking my submit that's the name of the button dot on click I keep on spelling on lick on
click equ equal a function parentheses curly braces when we click on the button what are we going to do we recently
learned about if statements we will first check the checked property of the Subscribe button we'll place it within
an if statement so to create an if statement it's if parenthesis krly braces we are
examining my checkbox that's the Subscribe button dot checked property this will evaluate to be true or false
if this is true we will execute this code if not we do something else if somebody is subscribed let's change the
text content of our sub resultes paragraph So sub result we are accessing the
text content to equal maybe I'll use a template literal you are
subscribed else the user is not subscribed let's copy this line paste
it you are not subscribed Let's test this if I click on the check boox then press the submit button it states that I
am subscribed you are subscribed if I were to refresh the page I don't click the Subscribe button press submit you
are not subscribed all right we know that that works let's move on to the radio button
first we will check to see if somebody selected Visa we are accessing the Visa radio
button if Visa button. checked if this is true we are changing the text of the
payment result paragraph payment result. text content equals you are paying with
Visa let's see if that works I'll select Visa press submit you are paying with
Visa all right let's add else if the next radio button is Mastercard
button if this is checked MasterCard button. checked then we will change the text
content of the payment result to be you are paying with MasterCard you are paying with
MasterCard let's add another else if statement else if this time we are examining the PayPal
button PayPal button. checked if this is true change the text content of the payment result to be you are paying with
PayPal you are paying with PayPal else if none of these radio buttons are checked we will change the text content
of the payment result to be you must select a payment type I will press submit without
selecting a payment type you must select a payment type all right everybody so that is the
checked property by examining the checked property of of an HTML checkbox or a radio button element we can
determine if those elements are checked or not and well that is the checked property in
JavaScript hey y welcome back so today I'm going to explain the trary operator in JavaScript you write a condition then
add a little question mark kind of like you're asking a question how is this useful well it's a shortcut to if and
else statements it helps to assign a variable based on a condition you write a condition then use the tary operator
as if you're asking a question you can write some code if that condition is true what would you like to do then add
a colon then some code if that condition is false here's an example let's say we have a user's age age equals
21 I would like to check to see if somebody's age is greater than or equal to 18 age greater than equal to 18 then
I will use the tary operator kind of like I'm asking a question is age greater than or equal to 18 if this
condition is true we can write some code I'll create a string your and adult then what if the condition is
false I'll add a colon then I will execute this code if the condition is false you're a
minor this is helpful if you need to assign a variable based on a
condition so I'll create a new variable let message equals then we write our condition so if
age is greater than or equal to 18 if that's true we will assign this string to this variable this message if
it's false instead we will assign this one it's an alternative to writing something like this
so with programming we try not to repeat ourselves if we don't have to here we're assigning message to be either this
string or this one our trary operator is more condensed and I feel like it's easier to read than that if else
statement it's a shortcut if you choose to use it I tend use it a lot then just to test it let's console.log our message
just to be sure that it works fine console.log our message our age is 21 you're an adult if
my age was 12 you're a minor let's go over a few more exercises this time we will have let
time time will be between 1 and 24 like a 24-hour clock I will set time to be 6 16 16 I think would be 400
p.m. we will assign a greeting equals then we'll write a condition is time less than
12 then tary operator like we're asking a question if the time is less than 12 it's the morning good
morning we'll use a colon then write some code if it's false if it's not the morning it's at
least the afternoon good afternoon then let's
console.log our greeting good afternoon because it's 400 p.m. what if it was 99 good morning all
right I have a few more examples what if somebody's a student let is student this will be true or
false if you're a student let message message equals now with the Boolean variable you can just
write the Boolean variable itself is student question mark are you a student if so you are a student if not
you are not a student then let's console.log our
message we are a student you are a student let's set this to be false you are not a
student it's very easy to read with Boolean variables you write the Boolean variable then add a question
mark here's a challenge round we will have a purchase amount as if somebody's buying something if somebody's purchase
amount is over $100 they get a 10% discount so let purchase amount equal let's say
$125 or some other unit of currency of you're choosing
let discount equals then the condition is we're checking if purchase amount is
greater than or equal to $100 $100 question mark is somebody's purchase amount
greater than $100 if so they will get a 10% discount
colon if that's false they get no discount zero so then let's display the total
console.log I'll use a template literal your total is I need a dollar sign for our unit of currency then I
need a placeholder so I need another dollar sign the purchase
amount minus us the purchase amount multiplied by let me scoot over a
little the discount divided by 100 so the total since we get a
discount is $112.50 if our purchase amount was $99 well we don't get that discount your
total is 99 all right everybody so that's the trary operator it's a shortcut to an if else
statement it helps to assign a variable based on a condition you write a condition add a question mark as if
you're asking a question do this code if that condition is true else do this code if that condition is false I'll be using
the tary operator a lot just because I feel like it's helpful and well that is the tary operator in
JavaScript hey what's going on everybody so today I'm going to explain switches a switch can be an efficient replacement
to using many else if statements here's an example of a program I wrote without using a switch we have a day day will
normally be the number 1 through 7 if day equals 1 will console.log it is Monday which you can see here if day was
two well then it's Tuesday all the way up to 7 which is Sunday I do have an lse statement that states our day variable
is not a day for for example if I set day to be I don't know like a string of pizza well then Pizza is not a day but
it really should be if you find yourself using a lot of else if statements I would instead recommend creating a
switch here's how to create one we'll keep our day variable I'll set that to be one to create a switch we will type
switch parentheses curly braces within the parenthesis of the switch we will place a variable or a value what are we
examining let's examine our day variable we examine a value against matching cases to create a case type
case then a value or a condition we will see if day equals 1 so day case one are these two values equal if they are then
we can do something we can execute some code so add a colon then any code underneath this case will be executed if
there's a match between our value or variable day and this value so let's console.log it is
Monday then be sure to add a break I'll demonstrate why you need break later so day is
one it is Monday let's add another case for case two in case day equals 2 so let's copy and paste what we
have case 2 it is Tuesday let's change day to B2 it is Tuesday all right let's do this all the
way up to case seven all right we have cases 1 through 7 if I
change day to be seven well then it is Sunday you can also add a default case in case there are no
matches now what if we set day to be Pizza which doesn't make sense well there are no matching cases once we
review all of the cases and there's no matches we exit the switch you also have the capability to add a default case in
case there are no matches what's the default behavior of the switch if there's no matching cases
let's console.log I should probably use a template literal for this if we're
inserting a variable our day variable is not a day so now we should
execute this default case Pizza is not a day all right now the reason that that we have these break statements is to
break out of the switch once we have a matching case I'll demonstrate what happens if we remove
these all right let's set day to be two as in Tuesday it is Tuesday it is Wednesday it is Thursday it is Friday it
is Saturday it is Sunday two is not a day so the reason that we have these breaks is to break out of the switch if
we don't have them once we have a matching case we will execute the code found within that space then Cascade
down and execute any code that follows after including code within different cases so that's why you want these break
statements after each case to break out of the switch let's go over a more complex
example let's say we have a test score variable between 0 and 100 my score will be 92
92% I will also create a letter grade variable which we will declare but not aign I'm
going to examine our test score so another way in which you can write a switch is something like
this I'm going to examine the value of true against matching cases which contain a condition so case then I'll
write a condition is test score greater than or equal to 90 as in
90% this condition will eval valuate to be true or false if true is equal to true we will do some code if this is
false we skip over it if our test score is greater than or equal to 90 let's assign our letter grade variable to
equal an a then be sure to break then I'm going to test this with console.log we will display our letter
grade we have an A let's do this for anything greater than 80 the user will receive a
B test score greater than or equal to 80 letter grade will equal B let's change our test score to be 85
the user receives a b let's follow this pattern 70 will be a c yep
C 60 will be a d 60 is D then for the default
case I will set letter grade to be F letter grade equals F if I set my test score to be 33% so
with the test score of 33 the letter grade is f all right everybody so that's a switch if you find you're using a a
lot of lse if statements I would recommend using a switch instead it's not bad if you have a few but if you
have many I would use a switch instead and well everybody those are switches in JavaScript hey it's me again so today
I'm going to explain string Methods in JavaScript string Methods allow you to manipulate and work with text also known
as strings in this example I have a username username equals a string of text why don't don't you go ahead and
create a username variable and set it equal to either your username if you have one or your full name strings have
different built-in methods where we can manipulate this text one way or another here's a few examples suppose I would
like to get the first character of the string I can use the Char at method type a string or a variable containing a
string then follow this with DOT by adding a DOT we are accessing any Properties or methods that the string
has follow this with Char at then list an index the first character is zero the second character would be one so get the
character at index zero that should be a b however if I were to run this let's go to our Dev
tools uh nothing appears to happen because it's going to return a single character let's place that within
console.log just so that we can see it cut this code and and paste it within console.log so the first character in my
string is B but depending on what you wrote it might be different for you the character at index one would be R then
two is O so that is the Char at method the index of method will return the index of the first occurrence of a
character let's find the first occurrence of n o it will return an index and then again I have to
console.log whatever is returned so let's place this method within
console.log what is the index of the first occurrence of an o that would be two 0 1 2 otherwise for the last index
let's change the method to be last index of which would be four 0 1 2 3 4 so the length property this isn't a
method to get the length of a string type the string or a variable containing the
string dot length this isn't a method but it's very similar so the length of my username is seven characters 1 2 3 4
5 6 7 so that's how to get the length of a string now we are going to trim the
string maybe there's a bunch of white spaces after or before I will reassign username equal to
let's take our username variable Dot and use the trim method to trim any Whit space then I will
console.log my username there's my name and there's no wh space
after let's add some wh space before our name yep and there's no white space to make my name I'll uppercase
I can use the two uppercase method now my string is all uppercase then there's two lowercase to
make all of the characters lowercase there's repeat to repeat a string within the parenthesis of the
method how many times do you want to repeat the string if I were to type three we'll repeat the string three
times to determine if a string starts with a given character we can use the starts with method this will return a
Boolean I will store that within a result variable username
dot starts with method we will check to see if the string starts with an empty
space then let's console.log the result that is false my username does
not begin with the space but what if it did I'll add one then that returns true this could be useful within an if
statement if result if the string starts with a whit space let's
console.log your username can't begin with an empty
space else let's console.log the username my username has a whit space in
the beginning your username can't begin with Whit space if that were false then we will
display my username so that is the starts with method there's also ends withth does my username end with the
Whit space it does not but what if it did your username can't end with an
empty space next is the includes method does the string contain an empty
space I'll split my username into two your first and last name would work as well your username
can't include an empty space currently it does your username can't include an empty space if it didn't then we pass
the test we will display the username all right now this time we will create a phone number let phone number
equals make up some phone number including dashes 2 3 4 5 6 7890 so this phone number is a string
even though it contains numbers because strings can contain numbers but we treat them as
characters let's eliminate all the dashes in our phone number here's one way in which we can do that let's
reassign our phone number equals our phone number we will use the replace all method which character are we replacing
let's replace any dashes comma then the character to replace the dashes with or whatever you put for the first
character we will replace all dashes with no characters then let's
console.log our phone number and that should eliminate all of the dashes or otherwise you could replace it
with a different character let's do a forward slash so 1 2 3456 SL
7890 there's also the pad start method. pad start the first value within the pad
start method is a specified length how many characters should the string be I would like the string to be 15
characters long then for the second value make sure to comma separate it we can pad the start of the string with a
given character let's say zero so the result is a couple zeros than our phone
number pad this string with zeros until it's 15 characters long if I were to set this to 20 then we would have more zeros
there's more padding then there's pad end pad the end of the string with this
character until the string is 15 characters long all right everybody so those are string
Methods they allow you to manipulate and work with text also known as strings we'll have more practice with these in
the future and well those are a few useful string Methods in JavaScript hey everybody so today I'm
going to explain string slicing in JavaScript string slicing is the process of creating a substring from a portion
of another string this won't alter the original string just just to demonstrate let's create a constant for our full
name go ahead and type in your full name or you can copy me I'm going to extract the first name from my full name and
create a new string out of it so I'll declare this let first name equals Now to create a substring we can follow this
formula we take our string in this case our full name dot then use the built-in slice method
slice then we can list a starting and ending index where would we like to begin so the first character has an
index of zero we'll start at the beginning index0 comma where are we going to end 0 1 2 this isn't
necessarily going to work and let me demonstrate so let's console.log our first name so my first
name is BR so the ending index index is actually exclusive in my full name we're ending at o but we don't include it
within our substring because the ending index is exclusive I'll increase the ending index to three that should
include one more character which it does now let's get the last name let last name equals again following this formula
take our original string use the built-in slice method State the beginning index 0 1 2 3 4 mine will be
four yours may be different depending on what your name is and the ending index four 5 6 7 and remember that the last
index is exclusive so I'm going to increase that to be eight then we'll display our last name
console.log last name and there's my last name so the reason that I set the beginning index to
be four and not three is because we'll include that space within the result as you can see here if you're going to be
creating a substring from some position all the way to the end you don't necessarily need an ending index I'm
going to remove the ending index and this should work the same all right what if I need the first
character in the string let first Char meaning character equals take our string we will use the
slice method for the first character you can use 0 comma 1 then let's display our first
character and in my example mine is B for the last character let last character full name do
slice we can use a negative index even if you're using a negative index you'll begin at the end then by decreasing the
number you'll work your way towards the beginning so the last character in my name is is
e -2 would be de 3 is o four is c for code negative indices work as well with these specific
numbers that I've listed they're only going to work if my name is exactly this what if I were to change my first name
to be instead of bro broseph like Joseph then let's display our first name then our last
name first name bro last name f which is not correct to make this program more
Dynamic we can combine string slicing with the index of method we'll search the string for the first instance of a
space then depending on where that space is we'll take the first part of our full name and create a substring for the
first name anything after the space will be our last name so let's turn these lines into comments we don't need them
anymore let first name equals again take our full
name do slice we'll begin at the beginning index zero now where do we end we're not going
to count the number of characters this time we're going to calculate it the ending index will be take our full
name dot then use the index of method where's the first index of a space so that is the ending position
wherever there's a space then we'll display our first name uh let me get rid of our last name
there brosive now for the last name let last name
equals let's copy this line of code paste it the beginning index will be f full
name. index of space you can list an ending index but we don't need to we would like to
extract every character that comes after this position so we don't need an ending index all right let's see if this
works brosi space code we're including that space so to remedy this I can add plus one find the first index of a space
then start in the position after that's why we're adding plus one then give me every letter that comes after and that
works just fine broi code all right let's go over an exercise this time we will list an
email const email equals why don't you go ahead and type in your email I'll make one up for me bro [email protected]
I'll extract the first part of my email to be stored as a username let username
equals again we're going to take our string email do use the slice method where are we going to begin we'll begin
at index zero that's the beginning of a string where will we end we'll end wherever the at symbol is but we need to
search for it we'll use the built-in index of method of a string email. index of what are we searching for we are
searching for the at symbol and let's see if this works
console.log our username yep bro one then let's get the
extension let extension equals we can copy this line of code paste it make a few
changes this substring will begin where the last one ended then again
console.log the extension at gmail.com again like I said before I
would like to begin after this index I will add plus one my username is br1 my extension is
gmail.com all right everybody so that's string slicing it's the process of creating a substring from a portion of
another string when you create a substring you won't alter the original and I've proven that by setting this
string to be a constant you can't change a constant to create a substring you take the string use the built-in slice
method then you can list starting or ending indices and well everybody that is string slicing in
JavaScript what's up everybody so in today's video I got explained the concept of method chaining in JavaScript
method chaining is a programming technique it's where you call one method after another in one continuous line of
code I'll give you two examples of the same program one that uses no method chaining and another that does then
we'll be able to see some of the benefits of method chaining what we'll do in the first version of this program
is create a variable for a username and I will ask the user for some input using window.
prompt the text will be enter your username after typing in some username I would like to to trim any
white space around the username take the first character make it uppercase take all of the other characters make them
all lowercase and then display the output so this program will have a few steps let's reassign our username equal
to username use the trim method to remove any wh space before or after the name
then I will get the first character of my username to capitalize it we'll create a variable of let letter
equals our username follow this with the Char at method the character at index zero letter is going to be a variable it
will hold the first letter of my username to make my letter uppercase I will reassign it letter equals letter
use the two uppercase method to make that letter uppercase now with the rest of the characters I would like to make
them lowercase anything besides the first character I will create a separate variable for
extra characters let's say extra chars short for characters equals take our original
username use the slice method we will slice our username everything after the first character if my name was bro code
and I created a slice of everything but the first character extra characters would be R code without the B so then
let's take our extra characters make them all lowercase extra characters equals extra characters followed with
the two lowercase method then we will combine the first letter which is uppercase and the extra
characters which are lowercase then store them within our username username equals our
letter plus the extra characters then we will display our username
console.log our username so this program does have a lot of steps we will run this program
enter your username I will enter a few whites spaces type in my name but I'll mix up
the capitalization press okay and there's my username the first letter is uppercase
the rest of the letters are lowercase so this program does work but it is a lot to write now with method chaining we can
combine some of these steps together and avoid creating variables that we don't need such as letter and extra
characters so with method training what we'll do is start to combine some of these
steps after getting our username we will take our username equals take our username again use the trim method we're
not going to end this method with a semicolon we're going to end it with a DOT to write another method after
trimming the username get the character at index zero and then why sto there let's method chain again make that
letter uppercase following the two uppercase method so this will work it's kind of like in a video game how you can
have a combo well this is a three hit combo boom boom boom take our username trim it get the first character and then
make an uppercase all in one line of code not only that let's use some string concatenation we need to take the rest
of the characters of my username make them all lowercase then combine them together again let's take our username
use the trim method method chain the slice method slice the string after the first character then method chain again
use the two lowercase method and that should work
console.log my username we're using a lot less lines of code and I'll zoom out just so you can
see everything Ander your username I'll throw in some white spaces then mix up
the capitalization and that has appeared to work so that's
method chaining it's a programming technique where you can call one method right after another in one continuous
line of code it's like a video game combo so to say so in this case trim our username give me the first character and
then make it uppercase we did method chaining here here and then we combined the results using string catenation
which is something separate entirely by using method chaining this help helps you avoid creating named variables but
if your method chain is too long it can become difficult to read like here I am kind of pushing the limits and well
everybody that is Method chaining in JavaScript hey yeah it's a me so today I'm going to explain logical operators
there's three of them and or not they're used to combine or manipulate Boolean values Boolean values if you remember
are true true or false let's create a program const temp meaning temperature what I would like to do is see if my
temperature Falls within a certain range this will be in Celsius let's say the temperature is 20°
C without using any logical operators let's write this if our temp is greater than
zero then we will console.log the weather is
good else if the temperature is less than or equal to 30 30° C we will also output the
weather is good else the weather is bad currently my
temperature is 20° C the weather is good what if I were to change this to something ridiculous like 200° C well
the weather is obviously not good Earth probably got hit by an asteroid or something or if I were to change my
temperature to like 100° C well the weather isn't good either I don't know maybe the sun disappeared so what I want
to do is output the weather is good only if my temperature Falls between the range of zero and 30 so we're going to
change this program if our temperature is greater than zero and we'll check another condition
and our temperature is greater than or equal to 30 then we can eliminate this elif
Clause now let's check the temperature our temperature is -100° C well the weather is bad if our temperature was
200° C the weather is also bad in order for us to execute this if statement both these conditions need to be true this
one and this one to join two conditions you use double and per and meaning and if our temperature was 25 well that
falls within our range the weather is good this is true and this is true so we will execute this code if one of these
was false we don't execute it at all we'll skip over it so that that is the and logical operator you can check more
than one condition you can check one thing and something else now there's or which is double straight
bars with the or logical operator at least one of these conditions needs to be true this has to be true or that has
to be true if I were to run the same program well then the weather is good let's change the temperature to
250 the weather is good but it's not it shouldn't be so let's rewrite this program if our temp is less than or
equal to zero or the temperature is greater than 30 then the weather is bad else the weather is good
our temperature is 250 the weather is bad netive -250 the weather is also bad so with the orological operator we're
checking more than one condition is this true yes it is -250 is less than zero or is this condition true this one is false
but since at least one of these is true we will execute this code then we will cover the not logical operator let's
create a new program const is sunny is it sunny outside this will be true or
false we will create an if statement our condition will be is sunny is this true if it is we will
console.log it is sunny else we will console.log it
is cloudy is sunny is set to true it is sunny If This Were false then it is
cloudy using the not logical operator we can flip a Boolean from True to false or false to
true I will precede this Boolean with the not logical operator which is an exclamation point now we're checking if
it's not Sunny then we will console. log it is cloudy else it is sunny is it not sunny
outside it is cloudy let's change this to be true it is sunny so basic basally the not logical operator it'll change
true to be false and false to be true all right everybody so that's a short topic today logical operators they're
used to combine or manipulate Boolean values use and to check to see if at least two conditions are true with or at
least one condition needs to be true and with not not we'll do the opposite and well that is an introduction to logical
operators and JavaScript so uh yeah it's me again so today I'm going to explain the strict
equality operator which is represented by three equal signs before we dive in let me make a few important distinctions
a single equal sign is the assignment operator you usually see it when you assign a value to a variable the
comparison operator two equal signs is used to compare two values to see if they're equal now the strict equality
operator has a whopping three equal signs it not only Compares if two values are equal but if they have the same data
type as well let me give you a demonstration suppose we have a constant named Pi Pi equal
3.14 pi in my example has a data type of number I'll create an if statement we will check if
Pi is equal to the string 3.14 if it is let's console.log that is pi
else we will console.log that is not Pi is the number 3.14 equal to the string
3.14 well according to JavaScript that is pi that's because we're using the comparison operator we don't care about
the data type we only care about the value are the values equal now if I was using the strict equality operator which
is three equal signs well then JavaScript tells me that this is not Pi because with the strict
equality operator not only do we compare the values but we also compare the data types as well these values are both
3.14 but this one is a number data type and we're comparing it to a string so they don't match technically if we were
strictly comparing the number 3.14 to the number 3.14 well then we have a match that is pi one case where this is
pretty helpful is when you accept user input because user input tends to be a string data type and then just as an
extra measure you can use the strict equality operator and then be sure that the value is a number data type there's
also the inequality operator it will return true if two values are not equal so let's
take shut up this time we will examine if Pi does not equal the string 3.14 if these are not equal this
condition will evaluate to be true so this is not Pi else this is pi is the number
3.14 not equal to the string 3.14 well that is Pi still using the inequality operator these values are
still the same the inequality operator will return false then there's the strict inequality operator an
exclamation point and two equal signs are the values or the data type different so in this example that is not
Pi they have the same values but the data type is different if I turned my variable Pi into a
string well that is pi now the string 3.14 stored within Pi does equal the string 3.14 so this condition turns out
to be false so we execute the L state it might take you a little bit of time to get used to this and that's okay it
is a little odd but just in case you see these in the future you'll at least be familiar with them from now on we will
try and use the strict equality operator if we can and well everybody that is the strict equality operator and I guess
well the inequality operator and strict inequality operator in JavaScript hey what's going on everybody
so today I'm going to explain while Loops in JavaScript a while loop Loop will repeat some code while some
condition is true take this program for example we have a variable username if our username is equal to an empty string
then we will console.log you didn't enter your name else console.log hello username if I run this program then
check within our console well we didn't enter our username now if I were to change this program to a while loop
while our usern name is equal to an empty string repeat this line of code Forever Until this condition is no
longer true then when we escape the while loop we can print the message hello username this is what happens when
I run the program we just print this line of code forever and my computer is probably
going to crash I can't seem to stop help okay I think it broke a while
loop will continue some code infinitely while this condition is true if it no longer is true then we can escape the
while loop if I were to set my username to be something other than an empty string well we never actually enter the
while loop we skip over it entirely and go straight to console.log at the end so what we do first is check the condition
if it's true then we get sucked into the wild Loop and execute this forever you usually want some sort of way to exit
the while loop while you're in it otherwise you get what is known as an infinite Loop so let's rewrite this
program let username equal an empty string while our username is strictly equal to an empty
string let's ask the user to enter in their name username equals I'll use a window
prompt enter your name name okay let's try this again enter your name I'll press okay we can't seem
to close this window until we type in something you can see I'm clicking on okay nothing's happening I will type in
my name press okay then our console displays hello whatever your name is so that's a benefit of a wild Loop repeat
some code until this condition is no longer true since we populated our username our username was not not equal
to an empty string we filled username with some characters what if I instead press
cancel hello null null means no value username will equal null if I press the cancel button let's append to this
condition or username is strictly equal to null now I shouldn't be able to continue
until I type in something and I can escape if I hit canc cancel while one of these conditions is
true execute this code forever let's type in our name again and now we can escape the while
loop there's also another variation of a while loop it's known as a do while loop how that works is that you can move
while and the condition to the end so we'll place it here then preedee the set of curly braces with do so we
will always execute this code at least once then check the condition at the end using a do while loop I don't
necessarily need to set the username I can set it to be undefined if I set my username to be
undefined then use a standard while loop we never execute the while loop our username equals undefined it doesn't
equal an empty string or the value null so we skip over the while loop entirely so a do while loop is another variation
of a while loop do the code first then check the condition at the end so there's a few different ways you can
write the same program all right let's go over another example we'll create three variables let
logged in logged in will be false to begin with to log in we have to type in a
matching username I will declare a username but not a sign it and a
password so let's create a while loop how do we escape the while loop let's say while not I'll use the not logical
operator while not loged in once we're logged in once this is true we escape the while loop we will ask a user for
their username username equals window. prompt
enter your username let's ask for a password as well password equals enter your
password I'll add an if statement within the wild Loop we'll check to see if our username is strictly equal to then make
up some username my user
name and if our password is strictly equal to some password like my
password if our username and password both match these values then we can log in so logged in will equal
true then I'll console.log a confirmation message you are logged
in else let's console.log another message invalid credentials please try again all right
let's see if this works enter your username I am just going to press okay
enter your password I'll type in something legitimate so I'll type in my password uh invalid credentials please
try again that's because I didn't type in a username I'll type in my username be
sure it matches my username my password and we are now logged
in so since we set logged in to be true when we go back to the beginning of our while loop this condition is no longer
true while not logged in but since we're logged in we escape the while loop now another variation of this is the do
while loop let's cut the condition along with while add it to the end then add do to the
beginning so we'll check to see if we're logged in at the end it pretty much does the same thing but with one exception in
this program how this is different is that I can set logged in to be true to begin with we still receive that prompt
I'll type in my username type in my password we are currently logged in so we do not continue the wild Loop if we
used a standard while loop and We Begin by being logged in well we never ask for any of this we
never enter the while loop while not logged in do all of this but since we are logged in we don't do any of it all
right everybody so that's while Loops repeat some code while some condition is true while some condition remains true
execute this code forever and until it's no longer true and well everybody that's while Loops in
JavaScript all right what's going on people so today I'm going to discuss for Loops a for Loop will repeat some code a
limited amount of times with the while loop a y Loop can repeat some code infinitely with the for Loop we can do
something a certain or limited amount of times here's an example let's say we would like to display the word hello
three times with the for Loop we can write something like this now to create a for Loop type four parenthesis curly
braces within the set of parenthesis we have up to three statements the first is that we can create a temporary counter
much like we're assigning a variable let's create a counter named I let I I is a common naming convention for
counters within a loop I meaning index so let I equal what number would we like to start at let's start at zero then
semicolon this is the first statement we'll create a counter to keep track of the number of iterations the next
statement is the condition in which we continue the for Loop we will continue this for loop as long as I is less than
or equal to two that's if we're going to execute this for loop three times 0 1 2 that would be a total of three then the
third statement we can increment or decrement our counter I so let's increment our counter by one during each
iteration by typing i++ and that's a for Loop I is set to zero will continue as long as I is less
than or equal to two then during each iteration we will increment I by 1 that means we will execute this for loop
three times what are we going to do when we execute each iteration let's
console.log hello so this should display the word hello three times yep hello three now if
I were to instead console.log I we can see what I is so during the first iteration I our
counter is zero then one then two if I wanted to count up to 10 I could change my condition to be this I is less than
10 so we begin at zero then we count up to 9 so if I need 1 through 10 I'll set I in the beginning to be 1 then continue
as long as I is less than or equal to 10 there so we have numbers 1 through 10 using a for Loop we can even increment
by a different number instead of incrementing our counter by one let's increment by two so I + = 2 so then we
should count up by twos 1 3 5 7 9 if I want to start at two I can change our counter to start at two count from 2 to
10 but increment by two 2 4 6 8 10 if we would like to count down let's start at 10 then count down to
zero let I equal 10 will continue as long as I is greater than zero then iusus to
decrement hey for fun after we escape the for Loop let's console.log happy New Year it's as if we're counting down to
midnight on New Year's Eve 10 9 8 7 6 5 4 3 2 1 Happy New Year or we could count down by two i - =
2 10 8642 or three or whatever number 10741 happy New Year or whatever number you
want now I'm going to cover continue and break this time we will count to 20 we need a for Loop we'll create a
counter let I equal I'll set I to be 1 that's our first statement our condition is is we'll continue as long
as I is less than or equal to 20 then increment I by One during each iteration so to test this let's
console.log I so we have the numbers 1 through 20 so with continue we can skip an
iteration I'm going to write an if statement if I is equal to now there is a Superstition that 13 is an unlucky
number let's say if I is equal to 13 we will skip that iteration I know it's a weird example so if I is equal to
13 let's continue continue will skip this iteration of the loop else we will
console.log whatever I is so now when I run this program when I run this program we skip over 13 we jump
from from 12 to 14 so if you ever need to skip an iteration you can use the continue
keyword now there's break break will break out of the loop entirely we've seen this keyword in switches to break
out of the switch if I equals 13 then just exit the for Loop entirely so in this example we count up to 12 but since
I now equals 13 we break out of the loop entirely we don't continue the rest of the iterations all right everybody so
those are four Loops you can repeat some code a limited amount of times there's up to three statements we can write we
can create a temporary variable that serves as a counter a condition in which we should continue then we can increment
or decrement our counter and those are four Loops in JavaScript hey what's going on everybody
in this video we're going to create a number guessing game using JavaScript so why don't you go ahead and sit back
relax and and enjoy the show all right let's get started everybody so the first thing that we're going to need is to set
the minimum and the maximum numbers in our number guessing game so we'll create two constants const minum for the
minimum I will set my minimum to be one but feel free to pick a different number if you would like then a maximum const
Max num I will set my maximum to be 100 so what we got to do is generate a random number between our minimum and
our maximum inclusively so let's create another constant const answer then we'll
generate a random number between 1 and 100 our minimum and our maximum to do that we can type math.
random the random method of math will generate a random number between zero and 1 we will multiply this by within a
set of parentheses the range between our maximum minus our minimum then add plus one
let's see what we have so far just to test everything I'm going to console.log our
answer okay let's inspect go to console here's my answer currently 56 point and then a bunch of decimal places after I
will round our answer by enclosing this equation with math. floor to round down okay let's see what we get again 39
89 20 7 71 27 177 46 okay that seems like it's working what if we have a higher minimum let's say between 50 and
100 well I have 7 22 43 numbers that are below our minimum so if we have a minimum besides one I will add to the
end of this equation our minimum again okay let's see if that works so if I need a random number between 50 and
100 this equation should work 97 80 79 52 all right that seems like it's working so this is the equation you'll
need to generate a random number between your minimum that you set and your maximum but let's change our minimum
back to one and make sure our maximum is 100 all right let's move on to step two we'll create a variable named attempts
to keep track of the attempts it takes a user I will set attempts to be zero and let guess
I will declare this variable but not assign it quite yet we'll take care of that later I will also create a Boolean
variable named running and I will set this to be true the reason that we have the Boolean
variable running is so that we can exit the game when it's over we'll set running to equal false so to keep the
game running we'll use a while loop while running equals true now if this is a Boolean variable you don't necessarily
need this portion equals true you can just set this to be while running while this Boolean is true keep
the game going then when we want to exit the game we will set running to equal false so that will be at the
end now we need to accept some user input I'll do this with the window prompt we will set our guest to equal
window. prompt I'll use a template literal guess a
number between I'll add a placeholder our
minimum through add another placeholder our maximum all right to test this I'm going
to console.log the type of guess as well as what guess is there's
something I need to show you guess a number between one and 100 I'll guess something right in the middle 50 let's
inspect go to console so my user input of 50 is a string data type we'll need to convert it to a number for
comparisons so after we get our guess let's reassign it and typ cast it as a number
type let's try that again guess a number between 1 and 100 I'll type 50 okay inspect console we have our guess of 50
and it's a number data type what if you were to type in something that wasn't a number like a string of characters such
as Pizza here's the result if you type cast some characters
that are non-numeric you know the number Z through n you'll end up with not a number Pizza can't be converted to a
number unfortunately I will delete this line of code we no longer need it I'll add an if
statement there's a function to check to see if something is not a number is not a number
function if our guess is not a number if this evaluates to be true let's add an alert window.
alert please enter a valid number guess a number between 1 and 100 what if I type
pizza please enter a valid number now what if somebody types in a guess that's below our minimum or above our maximum
I'll add an else if statement else if our guess is below our minimum or our guess is above our
maximum will window. alert please enter a valid number again guess a number between 1 and 100 what if I type in 150
that's above our maximum please enter a valid number please enter a number between 1 in 100 netive -1 please enter
a valid number if the user's guess is a number and it's between our range between the minimum and the
maximum we'll execute an L statement if they reach the L statement that means they have a valid number we'll increase
our attempts variable by one attempts Plus+ to increment it if the
guess if the yes is less than the answer then will window. alert too low try
again else if the guess is greater than the answer will window.
alert to high try again if the guess isn't lower than the answer and the guess isn't higher than the answer that
means the guess must equal the answer within an else statement we'll congratulate the user
they have the right answer window. alert
correct the answer was and I should probably use a template literal for this if we're
inserting variables the answer we'll let the user know how many
attempts it took it took you the variable attempts then the word
attempts at the end of our lse statement we'll move running equals false to within the lse statement at the end to
exit the game we no longer want to play once we have the correct answer all right and this should work let's try it
guess or not number between 1 and 100 I'll guess something right in the middle 50 too low try again okay so the answer
is between 50 and 100 75 too high so it's between 50 and 75
62 two low 68 two high so it's between 62 and
68 65 too high 6 three to
low 64 yeah correct the answer was 64 it took you seven attempts and we can exit
all right everybody so that is a number guessing game in JavaScript hey welcome back so today I
got to explain functions in JavaScript a function is a section of reusable code you declare that code once and you can
use it whenever you want all you have to do is call the function to execute that code here's an example we'll create a
function to sing Happy Birthday whenever we call this function it's going to sing Happy Birthday so to declare a function
you type function a unique function name let's name our function happy birthday because it's well the happy birthday
function then you add a set of parentheses then you add a set of curly braces any code we write between this
set of curly braces we can reuse whenever we want so what do we want to do exactly with this function I'll
create the lyrics to my own happy birthday song
console.log happy birthday to you let's repeat that again happy birthday dear
you happy birthday to you trust me I'm going somewhere with this so we have a function when we run
the program it currently doesn't do anything to execute this code within the function function we have to call the
function by its name happy birthday then add a set of parenthesis so now we should execute this code yep happy
birthday to you happy birthday to you happy birthday dear you happy birthday to you so to call a function you type
the function name then you add a set of parentheses I like to think of the parentheses as two telephones talking to
each other that's how I remember it so if I were to call this function again what do you think's going to happen well
we're going to execute this function twice three times we'll execute it three times as many times as I want in fact
that's what a function is it's a section of reusable code reuse it whenever you want you just have to call it you can
send a function some values or variables let's change our happy birthday function I will turn this line into a template
literal let's replace you with the placeholder then we'll add a username I'll add one one more
line we'll use a template literal you are insert a placeholder age years
old so when I run this program we have an uncaught reference error username is not defined at happy birthday so our
happy birthday function doesn't know what our username is or the age so we can send some information to the
function when we call it so within the set of parentheses what would we like to send this function let's send our
name so whatever values you place within the function be sure to comma separate them so why don't you go ahead and send
the happy birthday function a name and an age but there's one step missing these are known as arguments they're
data that you send a function but you need a matching set of parameters within the parentheses of the Declaration in a
way we can Define some temporary variables and they're all comma separated we will Define a username
parameter as well as age now this function should work properly happy birthday dear bro code you are 25 years
old so these are parameters and what you send to the function are arguments let's call the function but send different
information happy birthday uh how about SpongeBob SpongeBob will be I don't know
how old he is according to SpongeBob lore but let's say he's 30 years old happy birthday dear SpongeBob you are 30
years old how about Patrick this time it's his birthday everybody gets a
birthday Patrick will be 37 happy birthday dear Patrick you are 37 years old so that's a benefit of
passing arguments to a function when the function receives this data it can do something with it now the order of the
parameters does matter if I were to switch age and username here's what happens happy birthday dear 37 you are
Patrick years old with the arguments that you're passing to your function you'll want to be sure that the
parameters match up all right now I'm going to cover the return keyword we'll create a few other function examples
we'll create a function to add two numbers function add then we'll need two arguments which
we will name X and Y so when we invoke this function I would like to add X and Y together I'll create a temporary
variable named result just to store the result result = x + y so I'm going to add two numbers
together let's add two and three together and let's see what
happens well nothing appears to happen well we can send some data back to the place in which we call a function but we
need to use this return keyword let's return the result so 2 + 3 should be 5 after this function resolves think of
this function becoming the value five so we'll probably want to do something with that value I'll store that with within a
variable let answer equal add 2 and three then let's console.log the
answer which should be five when you return something from a function after you resolve the function think of it as
becoming whatever is returned in this case it's our result or otherwise I can place this
function within console.log if we don't plan to to store it at
all so add two and three then display the result which is five there is a shortcut too you don't necessarily need
to declare a variable within this function we could shorten this to return x + y that is also valid so
that should return five okay let's create a subtract function function
subtract will return x - y but we need a matching set of
parameters because I forgot that okay let's see what happens when we subtract 3 from 2 that'll give us 1 Let's
multiply function multiply we'll multiply X and Y
together return x * y we will multiply 2 * 3 which is 6 divide we need parameters X and
Y then return x / y then we will invoke the divide function pass into two and three and the
result is 0.666 repeating let's go over a more complex example we'll create a function to determine if a number is
even or odd here's the function function is
even we have one parameter a number so when we invoke the function we'll have to pass in a number so when we receive a
number how do we check to see if this number is even here's one solution we'll use an if
statement if our number modulus 2 modulus gives you the remainder of any Division if this number
divides by by two evenly if this is equal to zero and yes I'm using the strict equality operator I'm trying to
use that more often if our number is divisible by two then let's return the Boolean value
true else will return false okay let's console.log let's check to see if a
number is even let's start with 10 is 10 even that is true how about 11 that is false 12 12 is even so that's kind of
cool if you would like a shortcut for this you can use the trary operator that would look something like this we are
going to return then a condition what are we checking is our number modulus
2 strictly equal to zero question mark so that is the tary operator the question mark
if it is true then we will return a Boolean value of true colon false if it's false is 12 even that is true is 13
Even no it's not it's odd how about 14 that is true all right last example I think we're probably getting the hang of
this now we'll create a function to see if an email is valid function is valid email
what kind of information are we going to send we'll set that up as a parameter we will need an email we'll invoke the is
valid email function and pass in an email why don't you type in your email I'll just make one up bro
fake.com so when we invoke this function this string of text will become our email we'll check to see if our email
contains the at character we'll use an if statement if email and there's a
built-in method for this the includes method if our email includes the at
character then we will return true that is a valid email they have the ad character else we will return
false is my email valid that is true let's remove the at character brof fake.com maybe it's a website or
something that is false let's try another email again we're going to invoke the
function is valid email elonmusk.com don't actually go there I
don't know what's going to pop up uh that is not a valid email all right how
about Zucker Borg ata.com
that is a valid email it contains an at character and for something like this if we're returning either true or false we
can use the tary operator return then our condition is we're going
to check if our email includes the at character then add the tary operator if this is true return true else we will
return false so these should be the same which they are all right everybody so that's an introduction to functions it's
a section of reusable code you declare some code once and use it whenever you want you call the function to execute
that code if you need to send your function some data you'll need a matching set of arguments and parameters
and you can return something too with the return keyword we'll have more practice with this in the future don't
worry and that is an introduction to functions in JavaScript
hey what's going on everybody so today I'm going to explain variable scope in JavaScript variable scope is where a
variable is recognized and accessible in this beginner's tutorial we'll be discussing the differences between a
local scope and a global scope suppose we have a variable let X = 1 each variable name needs to be unique within
that scope I couldn't declare another variable named X where I set X to equal 2 if I were to run this we have a syntax
error identifier X has already been declared you can reuse the same variable names in
your program as long as they're within different Scopes to demonstrate let's create two functions function Function
One within function one we will declare a variable x x = 1 then we will console.log whatever X
is then let's create function two by copying function one and then paste it function 2 x will equal 2 console.log
x if I were to invoke Function One X = 1 if I were to invoke function 2 well x =
2 so we have two variables with the same name in our program that's legal as long as they have different Scopes any
variable declared inside of a function has a local scope or anytime you declare a variable within a set of curly braces
there's no naming conflicts because they're within different Scopes that way you can declare variables with the same
name which we've done with X now functions can't see inside of other functions within function two we will
declare variable y equal 2 then console.log X within function one we will console.log
y if I were to invoke function one we have an uncaught reference error why is not defined at Function One
one functions can't see inside of other functions function one has no idea what Y is we've declared that within another
function it's kind of like functions are neighboring houses you can't necessarily see inside of your neighbor's house
function one has no idea what variable Y is likewise function two if I were to invoke it function two has no idea what
X's each of these variables are declared inside of a function so they have a local scope
a global scope for a variable is any variable declared outside of a function with Function One let's get rid of
X and we will console.log X function two we will get rid of y console.log x if I were to declare a variable
outside of these functions let x equal 3 I'll invoke function one we'll display x x is three let's invoke function two x
is three any variable declared outside of a function has a global scope it's available through the whole program a
global variable is recognized and accessible from anywhere hey this is bro from the future I was editing this video
and I thought of a really good analogy for Global variables let's say that a function is a house we live in function
one and our neighbor lives in function two we can see inside of function one but we can't see inside of our
neighbor's house at function two any anything that's declared in the global scope isn't found within any houses it's
outside everybody can plainly see it it's kind of like a creepy stalker that's under a street light at 3:00 in
the morning everybody while inside of their house can still see everything outside that's an analogy I thought was
kind of accurate to describe a global scope however it's not recommended to declare Global variables in a large
program just because you can have naming conflicts in a large program I might accidentally reuse the variable X or
change it somewhere X is a very common name for a variable so in a large program I would stick with local
variables but in a small program like this it's fine when inside of a function we'll use any local instance of a
variable first if it's not found we'll look at the global scope So within Function One let's declare X to be
one within function two we'll declare X to be 2 and then within the global scope we
have xal 3 if I were to declare function one do you think X will equal 1 or 3 well it's one if we have two variables
with the same name and they're in different Scopes we'll use the local version first that's why X is one and
not three if I were to invoke function 2 well xal 2 if these local variables weren't
available we would use the global version instead where x equals 3 all right everybody so that is variable
scope it's where a variable is recognized and accessible you have a local scope that's anytime a variable is
declared within a set of krly braces that variable is then only accessible to anything within that set of krly braces
and a global scope is where a variable is declared outside of any functions it's available throughout the whole
program and well everybody that is variable scope in JavaScript hey what's going on everybody
in today's video we're going to create a temperature conversion program using HTML CSS and JavaScript so sit back
relax and enjoy the show all right let's begin everybody we will begin within our HTML file make sure you've linked a
script to your Javascript file which we'll fill in later so within the body of our document we will create a form
element within our form we will create an H1 heading for the title of this program which we will name
temperature conversion is good after our H1 element we'll create
an input element this is a self-closing tag it's a text box since we're going to be
converting temperatures I will set the type to be number so that should give us some arrows to increase or decrease the
number or type one in if we need to I'm going to give this text box an ID of textbox we'll be referring to this text
box by its ID later I'm also going to go ahead and set an initial value of zero then we can increase or decrease the
number like I said before it is a little small but with CSS we will increase the size what I'm going to do now is create
two radio buttons along with labels so we have input input is a self-closing tag the type will be
radio and for the ID this will will be a radio button to convert to
Fahrenheit I can never spell Fahrenheit we'll want the radio buttons in the same group I will set the name of the group
to be unit oh looks like I misspelled type there we go so I'm going to place our
radio button on a new line so within our first input element I will add a line break all right so after our first radio
button I'll create a label for it label this lab will be 4 2
fah and the text will be Celsius to Fahrenheit or if you prefer you could create like an
arrow I don't really like the look of that let me use an emoji instead so on Windows to create an emoji you can hold
windows and semicolon is there an arrow that'll work so when you click on
the label you should also be able to select the radio button that's because the four attribute is the same as the ID
attribute of the radio button okay let's copy both the first radio button and the label then paste it but change
Fahrenheit to Celsius let's switch these around Fahrenheit to
Celsius to Celsius I'm also going to add a line break after our first label so right
here as well as here Google wants to translate my web page from German to English it's probably because of the
word fahrenheit I'm guessing now I'll create a button the type will be button the text
will be submit there is an onclick attribute for buttons
onclick when we click on this button we can execute a JavaScript
function eventually we'll be creating a function named convert actually let's take care of that now before we forget
So within our Javascript file function convert we'll fill this in later so when we click on the button we
will execute the convert function then lastly we're going to display a result whatever the new
temperature is we'll use a paragraph element the ID will be result and just as a placeholder for now I'm going to
type select a unit all right so far so good let's style this program with CSS now be sure
to save your HTML file we'll move on to CSS we will first change the body of our document let's change the font family of
the body of our document I'll pick aiel with a backup of son serif I'll change the background color too
background- color I like using hsl values let's type a color such as black we will change the color to be hsl I'll
go with a very light gray color like 95% so the background is going to be slightly light gray we'll fill in the
form section to be Pure White we will select our one element that's going to be the header I'll pick a color again
I'll be using hsl values let's go with I don't know blue feel free to pick a different color if
you would like that's not bad then we'll fill in the form our form contains pretty much all of these
elements so let's select our form I will change the background color I'll just copy this line and paste
it but I'll I'll make this Pure White I'll text align Center everything within this
form so everything should be centered I'll set a Max width of the form because right now it's taking up
100% of the width of the web browser so max width will be how about 350 pixels we would like this form to be
within the middle aligned horizontally we can set margin to be Auto to automatically Center that I'll
add a little bit of padding around the elements within our form
padding let's do 25 pixels I'll smooth the corners of the form using border
radius border radius 10 pixels then I'll add a box
shadow box Shadow the first value is the horizontal off offset let's set that to be 5
pixels then the vertical offset I will set that to be 5 pixels the third value is the blur radius because right now
it's fairly concentrated let's stick with 15 pixels not bad you can also select a color again I'm going to use
hsl values you can also change the transparency I'll set mine to be
30% or approximately 30% 0.3 not bad so that's my box Shadow now we're going to change the text box so
this text box does have an ID text box let's select this element by its ID I'll set the width to be
50% it's going to take up 50% of the width available let's text align
Center the number is going to be right in the middle let's change the font size let's do 2 em for
200% I'll add a border to pixel solid then I'll pick some hsl values for
the color I'll make it a little transparent maybe like
80% let's select a border radius for pixels to smooth the corners I'll add a little bit of margin
below the text box margin-bottom 15 pixels is
good that's going to push the radio buttons down further just to give this text box more space let's work on the
radio buttons next so we are selecting the labels so let's take every
label I'll change the font size so it's a little a little bigger 1.5 em for 150% I'll make the font weight to bold
just to bold it there let's select our button we are selecting our button I'll
add a little bit of margin above the button margin-top 15 pixels let's change the background color
of the button pick a color I'll pick red and again I'm going to use hsl values because I like
them Ah that's decent I'll change the font size of the button 1.5 em for
150% I'll remove the border border none I'll add some padding 10 pixels for the top and bottom
of the button 15 for the sides I'll round the corners with border radius border radius 5
pixels I'm going to change the font color color white then when I hover my cursor over
the button I will change the cursor to be a pointer and that appears to work
now so when I hover over the button I'll use the hover PSE sudo class to change the background color of the button we
are selecting our button then select the hover sudo class we'll make the background color just a little bit
darker we'll change the lightness of our hsl value to be like 10% darker so I have 60% I'll change that to be 50 so
now the background should change when I hover over the button lastly let's change the CSS properties of the
result so this should have an ID of result result I'll make the font size a little
bit bigger font size 1.75 em is good and I'll make the font weight bold font weight bold all right and that is
all the CSS we need be sure to save everything and then we will move on to our Javascript file all right so what I
like to do is at the top of my JavaScript program I will declare all of the constants and variables that I'll
need so let's get our text box I'll set this to be a constant const text box equals
document. getet element by ID the ID that we're selecting is our text
box we'll need the two Fahrenheit radio button let's copy this line paste it get the ID of two
Fahrenheit const 2 Fahrenheit get element by ID 2 Fahrenheit then 2
Celsius 2 Celsius const 2 Celsius the ID is 2
Celsius so that will be this radio button copy this line paste it then we need the result to display the
result result get element by ID result within our HTML file we don't necessarily need to select a unit
anymore We'll add that later if somebody presses submit without selecting a radio button
then we need let temp for the temperature when we click on the submit button we will execute this function
convert so what are we going to do within this function we'll begin with an if statement we'll check to see if our
two Fahrenheit radio button is selected so take two Fahrenheit we'll use the checked
property if this radio button is checked it's going to return true if it's not it's going to be
false else if 2 Celsius is checked to celsius. checked we'll perform some different
actions else let's change the content of our result so here result. text content
equals select a unit let's see if this works be sure to save everything I am not going to select a radio button
I'm just going to submit and that's correct select a unit we didn't select one let's be sure that these two radio
buttons are working just temporarily I'm going to change the result within the if and else if
statement you selected two Fahrenheit and you selected 2
Celsius I just want to be sure that these radio buttons are working so let's convert 2 Fahrenheit submit you selected
2 Fahrenheit we'll select to the second radio button you selected 2 Celsius okay
we know that this program is reading these radio buttons successfully so we no longer need these two lines of
code we're going to get the number from our text box we'll store that within temp temp for temperature temp equals
take our text box access the value within so when we accept user input it's
of the string data type I'm going to typ cast the value as a number so we can use it with
math okay then we're going to take our temperature and convert it to Fahrenheit here's the formula temp equals
temp * 9 / 5 + 32 then we're going to update the text content of the
result result. text content equals our temperature then I'm going to add plus Fahrenheit so to add the degree symbol
on Windows you can hold alt then type 0176 on the numpad so this will be
Fahrenheit let's type 100 De Celsius to Fahrenheit that gives us 212° fah 10 would be 50 1° c would be
33.8 0 is 32° F if you would like to add some Precision following our temperature there's a built-in method to
fixed We'll add one point of precision this will give us one digit past the decimal place 0° cus converted to
Fahrenheit is 32.0 De F 10° C is 50° F let's copy these three lines then paste them within the else if
statement we'll keep this line the same but we'll change the formula temp equals within parentheses
temp - 32 * 5 / 9 then change fit to Celsius so what is 32° fah converted to
Celsius that is zero 100 is
37.8 all right everybody so that is a simple temperature conversion program using JavaScript HTML and
CSS hey what's going on everybody so today I'm going to explain arrays in JavaScript think of an array as a
variable like structure that can hold more than one value for example let's say we had a variable named fruit go
ahead and pick pick a fruit I'll pick an apple our variable can store one value but we can turn a variable into an array
and it can store more than one value and we can do so by enclosing all values with a set of straight brackets now my
variable of fruit is now an array it can store more than one value just be sure that each value is comma separated this
time I'll add an orange and a banana just to make it more obvious that this is an array I'm going
to add an s so that my variable name is plural it's not mandatory but it helps with readability I now have an array of
fruits but let me show you something if I were to console.log my array of
fruits well JavaScript is going to print out all of the elements in this array each item each value is known as an
element we have three elements if you need to access an individual element following the array you have to add an
index number enclosed in straight brackets if I would like the element at the first position that would have an
index of zero that would give me an Apple fruits at index of one would be orange fruits at index of
two is banana if I were to attempt to access the element at index 3 well it's undefined we only have three elements
within our array 0 1 2 arrays always begin with zero you can even change one of these elements by accessing that
array at a given element let's access our array fruits at index zero I will set the equal to be a
coconut so now we have coconut orange banana let's change fruits at index one to be a coconut Apple coconut banana
index 2 will be a coconut Apple orange coconut if I set fruits at index 3 to be a coconut let me console that log that
too fruits at index 3 we can add a new element to that array otherwise to add an element there's a
built-in method of arrays fruits do push to push an element to the end I will add a coconut to the end of my array Apple
orange banana coconut then we have pop pop is going to remove the last
element Apple orange undefined the unshift method will add an El m to the beginning take our array use the unshift
method unshift I will add a mango to the beginning of my array mango Apple orange
banana then we have shift to remove an element from the beginning fruits. shift now we have an orange banana and
my last two elements are undefined to get the length of an array there's a length property let's create a new
variable let num of fruits to store the number of fruits that we have type the array name do
length then let's console.log the number of fruits we have we have three fruits I'll add another
I'll add a coconut to the end and we have four so that's how to get the length of an array there's a
length property type the array name do length we can find the index of an element if there's a match let index
equals let's search for an apple fruits. index of method what are we searching for let's search for an apple then I
will display the index so our apple is located at index zero let's search for an orange that's index one banana that's
two coconut three what if we search for an element that doesn't exist like a Maino well this method will return ne1
that could be helpful within an if statement you can check to see if this method returns negative 1 then if it
does that means the element wasn't found and you can let the user know if index equals -1 display that element wasn't
found now if you would like to Loop through the elements and display them there's an easier way to do that you can
use a for Loop so four there's up to three statements we'll need a counter or some
sort of index let I equal Z that's the first statement we'll continue this as long as
I is less than our fruits array do length property then we will increment I by One if we have four elements we
should execute this Loop four times during each iteration I will console.log our fruits array but the
index instead of being like Z 0 1 2 3 a hard number we'll use our counter our index of
I and let's get rid of that line now we should Loop through all of the elements of this array and print them out
individually using a for Loop we can even increment by different number like two i+ equals 2 so here we're only
displaying the apple and the banana if I set index to be one then increment by two will display orange then coconut so
using a for Loop there's a few different ways in which you can display the elements of an array if you need to
display the order of this array in Reverse we can change this around we will set our counter I to be the length
of our array then we'll continue as long as I is greater than or equal to zero then
iusus there's one change I'm going to make we have undefined coconut banana orange Apple so the length of my array
is four but if I were to access our array fruits at index 4 where would that be 0 1 2 3 that's out of bounds I'm
going to set our index to be fruits. length minus one 0 1 2 3 our length is 4 minus 1 is a total of three now we're
printing our array in Reverse coconut banana orange Apple there's also an enhanced for loop it's a shortcut to
displaying the elements of an array you can write something like this let fruit
of array fruits really this variable can be anything but I like to write a singular
version of my array name then during each iteration I will display each fruit apple orange banana coconut this is an
enhanced for loop it's kind of like a shortcut to displaying the elements of an array if this array name were I don't
know like meets you could say let meat of meats and then display each meat
but of course they're still fruit that's a shortcut you can use now to sort an array you can use the sort method
fruits. sort and that should sort the elements in alphabetical order apple banana
coconut orange to sort them in reverse order you can tack on the reverse method to the end fruits. sort method. reverse
method now they're all backwards in Reverse alphabetical order orange coconut banana apple all right everybody
so that's an introduction to arrays we'll have a lot of practice with this in the future so if you don't remember
everything that's okay an array is a variable like structure that can hold more than one value a variable can hold
one value an array can hold many and well everybody those are arrays in JavaScript hey everybody today I'm going
to explain the spread operator in JavaScript the spread operator is represented by three dots the spread
operator allows an iterable such as an array or string to be expanded in two separate elements what this does is
unpack the elements here's an example let's create an array of numbers pick some numbers I'll just pick
1 through five one 2 3 4 5 then just to test this let's console.log my array
numbers in this array what if I would like to find the greatest value well one way which I could do that is let's
declare a maximum let maximum this is going to be a variable equals I will use the max method of math what would happen
if I place our array within this method then I will display our maximum so we have not a number using
the max method we can't place an array directly within this method however by utilizing the spread operator we can
spread this array into different elements so we will preedee this array with the spread operator we are going to
unpack the elements now if I run this program again we have our result of five when you use the spread operator imagine
that you're opening a box and taking out all the contents inside like you're unpacking something let's find the
minimum this time let minimum equals math.min we will pass our array of numbers then use the operator to spread
our array into different elements what is the minimum value from this array that would be one you can also do this
with strings too you can separate a string into different characters let let's create a username
equals type your name first name and last name I will create an array named letters letters
equals we'll create a new array let's take our username it's a string and use the spread
operator then I will display our letters console.log letters and here's my name divided into
different characters what we have is an array of characters with my array of characters I can join them back together
and insert characters between each element I will method chain the join method after our
array We'll add a dash between each character so now my username is all one string but
there's a dash between each character okay now this time we're going to create an array of fruits we'll make a shallow
copy of an array using the spread operator add some fruits I'll add an apple an
orange and a banana then I will console.log my
fruits I can create a shallow copy of this array using the spread operator a shallow copy means it's a different data
structure but it contains identical values I'll create a copy of fruits named new fruits
equals an array let's take our fruits array then use the spread
operator let's display new fruits and it should be an identical copy yep there's no apparent change we have two different
arrays but they contain identical elements we can combine two or more arrays using the spread
operator let's create an array of vegetables let's add some carrots
celery potatoes I'll rename new fruits as Foods let's add our array of fruits
we're spreading it comma then we will spread sprad our vegetables
array then we will display our array Foods this array contains all of the elements from these two arrays fruits
and vegetables we can use the spread operator to combine arrays we even have the capability to append separate
elements along with unpacking these arrays I will also add eggs and milk we have all of the elements from
our two arrays plus a few extras egg and milk all right everybody so that's the spread operator it's three dots it
allows an iterable such as an array or string to be expanded into separate elements and well everybody that is the
spread operator in JavaScript hey hey hey what's going on everybody today I'm going to explain
rest parameters in JavaScript rest parameters is a parameter prefixed with three dots they allow a function to work
with a variable number of arguments by bundling them into an array it's very similar to the spread operator which we
talked about in the last video the spread operator expands an array into separate elements rest parameters do the
opposite they bundle separate elements into an array spread will spread an array into separate elements rest
parameters will bundle separate elements into an array it effectively does the opposite how could rest parameters be
useful let me give you an example say we have a bunch of different food const food one food one equals
Pizza we'll create a few different food variables let's start with four food one food two food three food four we have
pizza hamburger hot dog and sushi I'm going to create a function that uses rest
parameters it's going to Output all food that I send it we'll pretend that we're opening a
fridge imagine that all of this food is in a fridge oh open fridge fridge short for
refrigerator to use rest parameters I need three dots we're going to stick all of this food into an array but what
should the array name be let's say Foods that's descriptive then I'm going to console.log my array of
foods now I'm going to call this function open fridge I will send this function a variable number of arguments
this method is going to display an array we have food one pizza food 2 hamburger hamburger is also
within our array food three hot dog food four Sushi let me add one more food let's add Ramen food five will be
Ramen then I will add food five you can see that I can send this function any number of arguments that I
would like this function is is designed to accept any number of arguments I could combine this function with the
spread operator when I'm displaying my Foods array all of these elements are in an array but I could separate them back
into separate Elements by using the spread operator which is the same three dots as the rest parameters rest
parameters are used as parameters the spread operator is used whenever you have an array or any sort of collection
of something so now when I combine the rest parameters and the spread operator I can display all of my
separate elements you can even use rest parameters to stick all elements within
an array so this time I'm going to create a separate function to get
food we will use rest parameters our array name will be Foods all we're going to do is return
Foods take all of these separate elements stick them within an array then return that
array so I'm going to create a new array const Foods
equals call our get food method pass in a variable amount of arguments let's pass in food
one food two food three food four and food five and then we got to display
it console.log my array Foods so that's how the rest parameters can be
used to combine elements and bundle them into an array then if you want you can return the array or do whatever you want
with it let's go over a second example we'll create a method to sum a bunch of numbers together function
sum we will use rest parameter so we can accept any number of arguments our array name will be numbers what we'll do
within this method is have a result result equals equal 0 we'll keep track of the current sum within our result
I'll create a for Loop to iterate over our array for every let number of
numbers take our result plus equals the current number and then we are going to return
our result now we'll have const total equals in our some function pass in as many
numbers as we would like let's start with one oh then I should probably display the total
console.log I'll use a template literal your total is I'll add a placeholder
total your total is $1 let's add a few more arguments two the total is now $3 three
$6 4 is 10 5 is 15 let's create a function to calculate
an average let's copy our sum function let's name this function get
average all we have to do when returning our result to get the average is divide our result by the length of our numbers
array divided by numbers. length property that will give you the average so now const total equals get the
average maybe these are test scores one student got a 75 another got a 100 another student has
85 90 and a 50 let's console.log the total the average is
80 let's go over example three you can use the rest parameters to combine strings together we will create a
function to combine strings we'll send in a title like Mister a first name such as
SpongeBob a last name Square Pants he's the
third we still need to make this function though but const full name equals whatever string is returned
all right let's work on this function function combine string let's make this plural
strings we need to use rest parameters let's name our array strings an easy way to do this is to
return our array of strings and use the built-in join method to join all of the strings together but but we'll add a
space between each string all right we should now have a full name variable that's all of the strings combined so
let's console.log our full name Mr SpongeBob SquarePants the third
that's one way in which you could use the rest parameters to combine a bunch of strings into one such as if you're
creating a full name all right everybody so those are rest parameters they allow a function to work with a variable
number of arguments by bundling them into an array it's the opposite of the spread operator the spread operator
expands an array into separate elements the rest parameters bundle separate elements into an array and well
everybody those are rest parameters in JavaScript hey everybody so in today's video we're going to use JavaScript HTML
and CSS to create a dice roller program this is an optional project you will need some images of dice to work with if
you're able to find some images of dice I would save them somewhere maybe on your desktop once you have images of
your dice we're going to create a new folder new folder I'll name my folder diore
images then take all of your dice images move them to that folder and now we are ready to begin
we'll create all of the HTML elements that we'll need I will create a div section this div will have an ID of
container to contain our program I'll include an H1 heading with text of dice
roller after this H1 element I'll create a label the label will have text of number
of dice afterwards I'll use an input element I'm going to zoom in a little
bit temporarily with this input element I'll type in a number of dice I would like
such as 1 2 3 however I can type in characters which I would like to avoid I will set the type attribute of the input
element to be number we're indicating to the user to select a number and not type in anything although there are ways to
circumvent this this will be good enough for now for the input element we can set a default value I will set the value
attribute to equal one for the default we can go below zero I'll set a minimum with the Min attribute Min
equals 1 we can't go below one but we can select any number one or
above now we'll create a button the button will have text of roll dice
the button will have its onclick attribute I keep on spelling on lick onclick attribute set to a JavaScript
function let's say roll dice we'll still need to Define this function in JavaScript after our button I'll create
two div sections the first will have an ID of dice result this will display some text
the numbers of the dice we roll the second development will be for the images ID dice
images and that is all the HTML that we'll need let's head to our CSS file and I'll Zoom back to
100% let's select our ID of container # container I will change the font family to a sance s font such as Arial with a
backup of s serif I will text Al line Center increase the font
size in this project I'm going to use RM instead of em because we'll be working with a lot of different font sizes em is
the font size relative to the parent RM is for the root for this specific project I'll stick with
RM and I will set the font weight to be bold let's style our button next we are SEL cting our button I'll
increase the font size of the button to be 1.5 RM I'll add a little bit of padding 10
pixels by 15 pixels I will set the Border radius to round the
corners 10 pixels remove the Border because it's ugly border
none pick background color for the button I'll pick something blue but I like
using hsl values something like that looks good I will change the font color to be
white and I will set the font weight to be bold not bad when I hover my cursor over
the button I will change the cursor to be a pointer
let's change the background color of the button when we hover over it we are selecting the hover suda class of the
button let's take our background color I'll increase the lightness by 10% so that should change when we hover
over the button now when I click on the button I'll increase the lightness even more to show that it's active with our
button we will select the active pseudo class I'll set the lightness to be 70 % so when we click on the button it
should flash momentarily which it is let's style the input element cuz I can barely see
it with our input element I need to scroll down let's increase the font size to two
RM I'll set a width of50 pixels text align Center
and font weight bold with our HTML file we do have two
empty div elements currently we'll style these at the end once we get our images to populate we'll style that last with
the onclick attribute of the button we set a function of r dice now we need to Define it within our Javascript file we
will Define a function to roll dice we have a lot of constants to declare I'll create a constant for the number of
dice we would like what's the value of this input element I will Define const num of dice what is the
number of dice we need to roll equals document. getet element by ID the ID of this input element is I actually
forgot what was it oh we didn't set an ID okay let's do that okay so for input element the ID will
be num of dice num of dice but I would just like the value I
will access the value of whatever this input element is for the next constant we're going to get the dice result this
empty div section const dice result equals let's copy this line of
code but we don't need the value we just need that ID dice result then let's do this with dice
images so we can copy this paste it const dice images the ID was dice
images I'll create two empty arrays const values this will be an empty array we'll store all of the dice rolls the
numbers then we'll need an array of images const images this will be for the images of the dice at this point in time
we're going to create a for Loop that will Loop once for every dice that we roll we have to generate a random number
between one and six for each dice we're rolling if I'm rolling three dice I need a for Loop to iterate three times let's
create a for Loop let I equal 0 continue this as long as I is less than the number of dice
then increment I by One during each iteration I need to generate a random number between 1 and six I'll store that
within a constant const value that will be the random number equals math. random method this
generates a random number between 0 and 1 but I'm going to multiply it by six to give us a random number between 0 and 5
it's not going to be a whole number though so I'm going to round it using math.
floor then enclose this part of our equation now we should get a random number between zero and five but I need
a random number between 1 and six so I'll add one to the End plus one so now we'll get a random number between 1 and
six just to be sure that this all works temporarily I'm going to con console. log our value if I roll one dice we
should get one random number one let's try three dice
546 324 all right we don't need this console. log statement anymore we know
that it's working with these values I'm going to push them into our array of values take
our array of values use the push method add our value that we randomly generate during each iteration and let's see if
this works I'm going to console.log my array of values just to
be sure that there's some numbers in there let's roll for dice inspect
console I have an array of four elements the number 6326 so that does
work all right here's the tricky part I need to take my array of images use the push method I will create a string
representation of an HTML element I need to get one of the images found within the SCE images
folder using angle brackets I will create an image element I will set the source equal to
that folder name so my folder name was dice uncore images dice uncore Images slash
so with my images it might be different for you mine are labeled appropriately you know for one two for two three for
three so on and so forth I will use a placeholder add our value this number then follow this with the file extension
of the images my images are PNG images do pay attention to that after we exit this for Loop we should have an array of
HTML images then we're going to take our dice result constant change the text content to
equal all of the values all use a template string I will display the word dice at a placeholder I'm going to join
all of the elements together all of the values to do that you can take your array of values use the built-in join
method and I will join them all by a certain character or characters I will join all of these numbers by a common
and a space let's see if this works I'm going to roll one dice yep dice I rolled a
one I rolled a four I rolled a three let's roll two dice I have 2 comma 5 four comma 6 2 comma 2 comma 3 6 comma 3
comma 2 then we have to get the images let's take our dice images constant access the inner HTML set this equal to
take our array of images use the built-in join method I'm not going to join them by any
character I'll join them by an empty string and let's see if this works I would like one dice yeah there it is two
and three now for some reason if your dice isn't displaying with our image element I will set the alt attribute to
equal a string of dice space add a placeholder value let's say I get the folder name
wrong I will rename this as dice image I'll attempt to display one dice dice three dice four dice three so in case
our image can't display for some reason will at least display the alternative text this is good for troubleshooting
and for screen readers for accessibility let me correct the name of the folder again so with our dice images at least
for me they kind of big and I'd like to space them out a little bit our last step is we're going to go back to our
CSS stylesheet I will select the ID of dice result that's going to be for this title
right here I'll add some margin around this text right now it's kind of compressed I will set margin of 25
pixels then with our dice images ID dice images with my ID of dice images is take each child
image set a width of 150 pixels should be good yeah they're a lot smaller now I'll
add a little bit of margin too margin 5 pixels yeah that's not a bad looking
program all right everybody so that was a dice roller program you can make using JavaScript HTML and CSS impress your
friends and that's pretty much it hey what's going on everybody so in
today's lesson we're going to create a project where we Generate random passwords this will help us solidify our
understanding of functions and random numbers this will be an exercise for beginners by setting different options
we can change the format of the password and well let's begin everybody all right let's begin we'll need to let our
program know what the length of our password is going to be let's create a constant to store that const password
length set this equal to maybe 12 but we can adjust that accordingly we'll create a Boolean to specify if our generated
password is going to contain lowercase characters we'll create a constant include
lowercase do we want to include lowercase characters we can set this to be true or false we will set this to be
true do we want to include uppercase characters include
uppercase I will again set this to be true do we want to include numbers const include
numbers I will set that to be true do we want to include symbols const include
symbols we'll Define a function at the top of our program function to generate
password we have a lot of parameters to set up we're going to pass in all of these constants as arguments so we have
a length include lowercase include
uppercase include numbers and include symbols when we call this function we
have to pass in all of these arguments so we will call our generate password function pass in our password
length include lowercase include uppercase include
numbers and include symbols at the bottom of our function we will be returning a password but for now
I'm just going to write an empty string because we still need to determine what that password is going to be after
finishing the generate password function this will return a string a string password we will store that within const
password equals whatever is returned from the generate password function and just so that this is more readable
although not necessary I'm going to place each of these arguments on a new line because I'm OCD about things being
an alignment and then at the very end of this program I will display a template
string of generated password I'll add a a placeholder then we'll display our password that we
generate so right now it's not going to display anything we're returning an empty string but that is everything we
need outside of this function to generate our password basically we're passing in options when we generate our
password do we want to include lowercase characters uppercase characters numbers and or symbols we have a
number and a bunch of Boolean values within our password we're going to create a few constants within this
generate password function we will create one long string of all of the lowercase characters
chars equals I'm going to go through the alphabet we will have one long string of alphabetical
characters and I think I got all of them so there should be 26 now we're going to do this with uppercase characters
const uppercase chars equals I'm going to turn on caps
lock go through the alphabet we'll create a constant of number characters number chars
equals 0 through 9 and symbols const symbol
chars which symbols would you like to include I'll just add a bunch that's probably good enough for
now feel free to add more or less we will create a variable for allowed chars meaning
characters and an empty pth password let password equal an empty string if some of these constants are
true we would like to take that corresponding set of characters and concatenate it to the allowed Char
string so what we'll do is take our allowed characters variable use string concatenation by using plus equals we'll
check to see if include lowercase is true or false we can use theary operator for that if
we would like to include lowercase characters we will string concatenate our lowercase chars our lowercase
characters otherwise we'll concatenate an empty string let's do this with uppercase
characters with our allowed characters let's string concatenate and check if we're including uppercase characters
question mark if this is true we will concatenate all of the uppercase characters we've declared otherwise
we'll concatenate an empty string so we don't include them let's do this with number
chars include numbers are we including numbers within our password if so we will return our number Char
string and then symbols are we including symbols within our password if so concatenate our
string of symbol character all right just to test everything afterwards I'm going to
console.log our allowed characters so right now I'm going to switch all of these constants to be
false so right now we're not including any characters if I were to set include lowercase to be true we would include
all of the lowercase characters that's one long string Let's test uppercase yep we are including all of the uppercase
characters include numbers yes that works and include symbols that also works at this point in the program we're
going to have one gigantic string of all of the possible characters before we move on with the program I do want to
run some checks using some if statements first let's check to see if the password length is zero or less than zero right
now it's set to 12 using an if statement if the length the length of the password
is less than or equal to zero we need to let the user know that the password length must be at least one we will
return a string password length must be at least one right now we're not generating a
password we're returning an empty string if I set the password length to be zero we will generate this message pass
password length must be at least one or even a negative number like1 password length must be at least
one let's set that back to be 12 what if we don't select any options what if all of these character options were
false we can check the length of our loud characters variable so if our loud characters length property
is strictly equal to zero this will only be possible if all of these options are set to false we will return a template
string at least one set of characters needs to be selected and let's see if this works yes
it does at least one set of characters needs to be selected I can select any options that I would like like I will
set these all to be true now here's the hard part for as many iterations as our password is we
will select a random character from all of the different possibilities we will use a for
Loop we will let I be our index our counter we will continue this for loop as long as I is less than the length the
password length then increment I by One during each iteration if our password length is 12 we will execute this for
Loop a total of 12 times now we will generate a random index const random index equals we will use the random
method of math this generates a random number between 0o and one I can multiply this
number that's randomly generated by the length of our allowed characters let's say we're including
only lowercase characters well this is a total of 26 characters in the alphabet if I'm taking math.random * 26
I'll be given a random number between 0 and 25 but I will need to round it down let's enclose this equation with the
floor method of math to round down math. floor we'll use string concatenation with our password Cur our password is an
empty string but we will use string concatenation we will string concatenate a randomly chosen character from our
string of allowed characters password plus equals our allowed characters at the index of random
index then at the end of this program we will return our password and let's see if this works
let's close out of this function we don't need it anymore and let's see if this works yeah there's
our password so every time I run the program I get a new random password and I can turn these options on and off
let's set all of these options to be false to begin with and I will set the length to be
zero let's see what happens password length must be at least one all right how about a password of 10 10 characters
long at least one set of characters needs to be selected let's select only lowercase
characters yep we only have lowercase characters let's allow uppercase characters
now let's allow numbers I didn't get any of that time let's do it
again okay there's a number I guess numbers don't come up very frequently and let's include
symbols and there's a few symbols in there all right everybody so that was an exercise to Generate random passwords it
should give you some practice with functions and working with random numbers and well everybody that was a
random password generator in JavaScript hey welcome back everybody so today I got to explain callbacks in
JavaScript a callback is a function that is passed as an argument to another function they are used to handle
asynchronous operations such as reading a file Network requests or interacting with databases these activities take
some time to complete now with JavaScript we don't necessarily wait for a process to finish before continuing
with the rest of the program for example if we were to read a file if it takes a long time to read that file JavaScript
might continue on with the rest of the program we might attempt to display the contents of that file before we're
finished reading it that's where callbacks come in we're telling JavaScript hey when you're done call
this next when you're done reading the file then display the contents only after that process is complete I'll I'll
give you a few examples of the syntax of a call back we'll start with something really simple we'll create a function to
display the word hello this will be the hello function then I will
console.log the word hello so I can invoke this function
hello to execute it hello what if we were to create a function for goodbye function
goodbye we will console.log goodbye okay after hello let's invoke
goodbye we have hello then goodbye what if my hello function takes a lot of time to process well JavaScript isn't
necessarily going to wait around before executing the goodbye function I'm going to add a few lines of code you don't
need to copy this these few lines of code are going to make us wait for 3 seconds you don't need to write this
this down but do pay attention we will execute the hello function followed by the goodbye function but we're going to
pretend that our hello function takes a little bit of time to process so now we have goodbye already
executed followed by hello but it should be the other way around I would like to guarantee that the goodbye function
follows after the hello function well I can do that by adding a call back to the goodbye function after the hello
function is complete we'll get rid of the this goodbye function invocation to use a call back you pass a
function as an argument to another function we will pass the goodbye function as an argument to the hello
function So within the set of parentheses type the name of the function goodbye now be sure you don't
add a set of parentheses after the function name you'll call it right away we are passing the name of the function
as an argument but we need a matching parameter I will name this parameter callback and after everything within
this function is complete let's take our call back then invoke it by adding a set of parentheses
invoke meaning call all right now let's see what happens we have our hello function
followed by the goodbye function in that order let's create another function what about a leave function
we'll tell somebody to leave console.log leave I will pass pass the
name of this function as an argument to the hello function leave is now our call back after executing the hello function
we will execute our call back and in this case it's the leave function let's create another function for wait
function waight console.log wait we'll pass the name of
the function as an argument to the hello function wait is now our call back we will execute the hello function followed
by the weight function so by using callbacks we are guaranteeing that the function passed in will execute next you
can pass callbacks as well as other arguments to a function let's go over a second
example I will create a function to sum two numbers together X comma y I'll also add a call
back call back X comma y we have three parameters total within the sum function we will create a local variable of
result add x + y and then I will call my callback then I'll pass the result as an argument to
the Callback function then I will create a function to display the result to my console display console there is one
parameter we have a result argument we're receiving then
console.log my result all right now we will invoke the sum function but we have three arguments
that we need to pass in a call back a value for x and a value for y let's invoke the display console function as a
call back again be sure to not add a set a parentheses after the name because then you'll invoke it right
away X will be 1 y will be two and let's see the result the result is three So within our
sum function calculate the result first then after that process is finished then display the result to the console let's
create a separate function to display the result to our document object window our web page basically uh let's pretend
that this wasn't here I'll create an H1 element with an ID of my
H1 I will create a separate function display page
to display on the web page I think display Dom would be more appropriate but I haven't explained what the
document object model is yet so let's just work with display page we will accept a result I will
change the text content of the my H1 element document. getet element by ID the ID was my H1 we will change the text
content to equal our result that we receive as a callback we will use the display page
function display page there and the result is three after this calculation processes execute the
call back and this time we are passing it to the display page function that we created all right everybody so that's a
call back it's a function that is passed as an argument to another function they're used to handle asynchronous
operations operations that may take a variable amount of time such as reading a file Network requests or interacting
with databases we're not exactly sure when these processes are going to complete by using a callback we can
ensure that a function executes after these processes are complete and not before accidentally all we're doing is
saying hey when you're done call this next we'll have more practice with callbacks especially in the upcoming
topics and while everybody those are callbacks in JavaScript hey it's me again today I'm
going to explain the for each method in JavaScript the for each method is used to iterate meaning Loop through the
elements of an array and apply a specified function to each element you have an array we can use the built-in
for each method of arrays and send each element through a call back to a function here's an example I'll create
an array of numbers let numbers equals 1- 5 then I'm going to create a function to
display each element function display there will be one
parameter an element we will individually display each element within this array
console.log each element I can display each element of this array by using the for each
method we will take our array dot use the built-in for each method then pass a call back as an
argument we will pass our display function as an argument so this should display all of the elements in my array
to the console 1 2 3 4 5 believe it or not the element argument is provided for us with the for each method behind the
scenes the for each method will provide to a callback an element index and array argument an element for the current
element that we're on when looping through this array an index that keeps track of the current index number and
the location of the array itself in this case it would be numbers that's why when we pass the display function as a call
back we're already provided with an element argument behind the scenes so we're using the for each method to
display all of the elements of this array let's use the for each method again to double each element before
displaying it I will create a new function function double to double the value of each
element element index and array are provided for us automatically for each element what are
we going to do let's take our array at index of index index keeps track of the current index number so during each
iteration it's going to increment by one starting with zero we will take our element multiply it by
two all right so let's take our numbers array use the for each method then pass a call back to our double
function so now all of these elements should be doubled let's triple them now we'll create a function for triple
function triple we will set the parameters to be the same but we will multiply each element by three then
passing a call back for triple so now we have 3 6 9 12 15 they're all tripled let's Square each
element function Square again the element index and array arguments are provided for us take our
array that we receive at index of the current index number set this equal to to square a number we can use the power
method of math then raise a base to a given power we are raising our base of element to the power of two if I pass
our Square function as a call back to for each we will now Square each number before displaying it 1
49625 then this time let's create a cube function function Cube raise our element to the power of
three pass our Cube function as a call back to the for each method and now each number is cubed 1 8
27 64 125 let's create a more practical example I will create an array of fruits
let fruits equals some fruit we have an apple we have an orange a
banana and a coconut we'll create a function to display each element function display it's kind of
like what we did before an element argument is going to be provided to us during each
iteration let's console.log each element and then we will use the built-in for each method of our array fruits fruits.
for each we will pass our function as a call back to display each element of this array Apple orange banana coconut
let's create a function to make all of these strings uppercase
function uppercase we'll need an element index and
array element index array during each iteration let's take our array that we receive at the index of our index equals
take the element that we receive use the two uppercase method so we have an uppercase function that utilizes the two
uppercase method remember that a method usually belongs to something this method belongs to the element that we receive
functions are Standalone before displaying each element within my array of fruits let's take our fruits array
use the for each method then apply a call back to uppercase to make all of the elements uppercase before displaying
them what I'm going to do is copy all of these elements so they will begin uppercase I'll create a lowercase
function function lowercase we have our element index and array with this line of code we will use the two
lowercase method within the for each method we will pass our lowercase function as a callback to make all of
the elements lowercase let's set the elements of our array to be all lowercase
again this will be a challenge round we will capitalize the first letter in each element of this
array we will create a function function capitalize the element index and array
arguments are going to be provided to us take our array that we receive at the current index set this equal to we're
going to get the first character in each element we will take our element get the first character Char at
index of zero method to uppercase to make this letter
uppercase then we will strink catenate our element use the slice
method we'll create a substring begin at index one this portion is going to create a substring of every character
besides the first the first character we're going to make uppercase so now this should work so
let's take our capitalize function pass it to the for each method and now the first character in each element is all
uppercase all right everybody so that is the for each method it's used to iterate over the elements of an array and apply
a specified function as a callback to each element you take your array use the for each method then pass a call back as
an argument it's really useful if you need to apply a function to each element of this array and well everybody that is
the for each method in JavaScript hey it's me again today I got to explain
the map method in JavaScript the map method accepts a callback and applies that function to each element of an
array it's very similar to the for each method however it returns a new array that's a key difference for example
let's create an array of constants I'm picking constants just to demonstrate that we're not changing any elements in
this array we have const numbers I'll select the numbers 1 through 5 to keep it simple
I will create a function to square each number function Square we have one parameter we have an
element all I'm going to do is return math.pow this will raise a base to a given power we are raising our element
to the power of two then returning it we're going to take our array of numbers use the built-in map method then pass in
our function as a call back the map method will return a new array we will create a new array to store the values
that are returned so I will create const squares equals numbers. map and then
let's display our squares I'll use console.log for now console.log our squares here are all the
numbers squared 1 4 9 16 25 let's create a function to cube these these numbers now we'll copy and paste our Square
function but change it to cube we'll raise our element to the power of three const cubes equals take our
original array numbers dot use the map method pass in a call back to the function we would like to use
Cube then we will console.log R array of cubes and we have some new numbers 1 8 27 64 125 the map method is very similar
to four each but after completion the map method returns a new array we still have our original numbers whereas in
four each we'll change them that's a key difference let's go over a new example we'll create an array of
students const students equals for my first student I will pick SpongeBob then
Patrick Squidward Sandy that's good enough I will create a function to make all of
these strings uppercase function
uppercase there is a single element remember the element is going to be provided for us with the map method
element index and array but we only need element in this case I will return our element dot to uppercase method and
that's it we'll create a new array students what can we name this uh students upper I suppose we will take
our array of students use the map method pass in the function we would like to apply as a
callback then I will console.log students upper within my array all of the
students names are all uppercase let's create a function for lowercase function
lowercase to lowercase I will create a new array const students lower equals the name of the
array students map pass in our function as a call back then display the array of
students lower now all of the names are now lowercase all right third example this one is more practical we'll create
an array of dates const dates equals certain regions will order their dates differently for example you might
have the year followed by a month then a day we're going to rearrange the order of these dates using the map method so
come up with a few dates I picked 2024 January 10th 2025 February
20th 2026 March 30th feel free to rearrange these however you want I will create a
function to format dates we have one parameter a single
element within this function I will create a temporary array named Parts we're going to split each date into
parts and it within an array within this function const Parts equals element. split we are going to split
each element but where we are going to split at each dash for example with my first element we'll split this date into
2024 that will be the first element 1 and 10 then we'll reformat these parts I will return a template string so I'm
going to need some placeholders ERS so dollar sign curly braces let's take our array of parts at index of one
that will be the month I live in the United States we arrange our dates with month then day then year I will place my
month first forward slash let's include another placeholder Parts at index of two that
will be the day of the month slash Parts at index0 that will be the year we will
create a new array const
formatted dates equals take our original array dates use the map method then pass the function name as a
call back then after I will console.log our formatted dates and and here they are for me the
dates are now January 10th 2024 February 2nd 2025 March 30th 2026 feel free to arrange these however you like all right
everybody that is the map method it's very similar to the for each method the math method accepts a call back and
applies that function to each element of an array however it returns a new array when it's finished that's nice if you
need to preserve the original array that the elements came from and well everybody that is the map method in
Javas script hey again everybody it's me big surprise there today I'm going to
explain the filter method in JavaScript the filter method creates a new array by filtering out elements in this example
we'll create an array of numbers we will filter out any numbers that are odd let's add the numbers 1
through 7 now we need a function
function is even we have one parameter we have an element that's going to be provided to us by the filter method we
are going to return then write a condition we will take our element modulus 2 the modulus operator gives you
the remainder of any division you can use modulus 2 to check to see if a number is even if this condition is zero
strictly equal to zero then we will return true we will be returning a Boolean true or false the filter method
will take any values that return true and stick them within a new array which will effectively filter out any elements
we don't need that don't return true let's see if this works I will create a new array even nums equals take our
original array use the filter method pass in a call back is even we will display
console.log our new new array even numbers and there we are 2 4 6 let's do this with odd
numbers function is odd take our element modulus 2 is this strictly not equal to zero that means
the number is odd let's create a new array let odd nums equals our original array numbers
do use the filter method passing a call back is odd let's check out our new array odd
nums there we are we have the numbers 1 3 5 7 any numbers that are odd let's go over another
example I will create an array of Ages I'll use const this time instead of let const ages Pretend We're teaching a
college class we might have some students still in high school let's say a student is 16 another is 17 two or
18 19 20 and then we have somebody that's just a little bit older they're um 60 we'll use the filter method to
filter out anybody that is under 18 we will find all of the adults we will need a function function is adult we have one
element as a parameter that's going to be provided to us we will return a condition return
check our element is it greater than or equal to 18 so that's our function let's create a
new array of adults equals take our original array dot use the filter method pass in a call back is adult then
display our new array console.log adults we have five elements the age of
the students is 18 18 19 20 and 60 let's do this with is children to find anybody that's under
18 is child function return element less than 18 we'll create a new array const children
equals take our original array use the filter method passing a call back is child then display the new array we have
two students that are children one is 16 the other is 17 last example we'll create an array of words const
words add some words I think I'll add some fruit I'll add an apple
orange banana kiwi
pomegranate and a coconut I will filter out any words where the length of that word is above six so we
will create a function function get short words we have an element as a
parameter we will return a condition we will check if our element access the length property of that element they're
strings so they all have a length property how many characters are they long that's the length check to see if
the length of this element is less than or equal to six if it is return true if not return
false we will create a new array let's call this array short words equals take our array use the built-in filter method
pass in a call back get short words then we will console. log the new array short words in our array there are four
elements with the length of the characters of each string is six or under Apple orange banana kiwi then to
finish this off let's get any long words we'll create a new function get long words check the length
of the element to see if it's above six then we will create a new array const long words equals take our original
array use the filter method pass in a call back get long words then we will display our new array long
words within our original array there's two words that are considered long pomegranate and coconut these words each
have more than six characters coconut is seven pomegranate is 11 all right everybody that is the filter method it
creates a new array by filtering out elements your callback is likely going to checking condition does each element
pass this condition and well everybody that is the filter method in Javas script what's going on everybody so in
today's video I got to explain the reduced method in JavaScript the reduce method reduces the elements of an array
to a single value in this example we'll create an array of prices as if it was a shopping cart we'll sum all of the
prices within our shopping cart and return a total we'll need an array to work with const prices equals an array
think of some prices type in anything as as long as it's a number I'll keep this simple and use whole numbers I'll add
something that is $5 another that is 30 10 25 15 and 20 we will create a variable
for a total const total equals take our array of prices we will use the built-in reduce method of arrays but we do need
to pass in a call back to a function we need to create a function that will sum all of these
values let's create a function to sum our sum function will have two parameters the first will be an
accumulator the second will be the next element all we're going to do is return our
accumulator plus our element I'll explain how this works momentarily I just want to be sure that everything
runs fine first within the reduce method we'll pass in a call back to the sum function that will return a single value
a total in this case let's see what our total is console.log I'll use a template string
pick a unit of currency I'll pick American dollars add a placeholder let's display our total so my total is
$15 if you would like to add cents to the end of that you can follow this with the two fixed method then add two
decimal places for sense all right so how does this work exactly we have two parameters accumulator and element it
might be easier if I were to rename these parameters you can rename parameters let's say accumulator is the
previous element element is the next element we're returning the previous element
plus the next element during the first iteration we'll have 0 and five well 0 + 5 would give us 5 five is returned to
the accumulator whatever value is returned becomes the accumulator during the next iteration so now our
accumulator is five the next element is 30 then we are going to return the accumulator + 30 which is 35 we'll
return this to the accumulator during the next iteration the accumulator is now 35 the next El element is
10 35 + 10 would give us 45 return that to the accumulator and add the next element
25 so you just follow that pattern all right let's go over another example we'll create an array of grades
const grades equals these will be some number grades 75 50 90 80 65 and 95 we'll find the maximum value from this
array we'll create a constant to hold the maximum value what is the maximum score const maximum equals take our
grades array use the built-in reduce method then we need to pass in a call back to the reduce method we need a
function to get Max there's two parameters an accumulator
and the next element like I said feel free to rename them we will return the max method of math math. Max pass in
these two parameters accumulator and the next element within the reduce method we'll
pass in a call back to get Max the value returned will be the maximum grid from this array so let's
console.log whatever the maximum is the maximum score from this array is 95 let's do this with the
minimum let's copy this function change any instance of Max to Min get Min math.
Min let's create a new constant const minimum equals our array of grades use the reduce method to return a single
value then passing a call back to get min let's console.log the
minimum the minimum score from this array is 50 all right everybody that is the
reduce method it's a built-in method of arrays to reduce the elements of an array to a single value you can use it
to sum the elements of an array another possibility is to find the minimum or maximum value from an array and well
everybody that is the reduced method in JavaScript hey everyone so today I'm going to explain function expressions in
JavaScript a function expression is a way to define functions as a value or a variable not to be confused with
function declarations where you define a block of reusable code that performs a specific task we're already familiar
with function declarations such as this function then you create a function name such as hello in this example let's
console.log the word hello with the function expression we can assign a function to a variable
or pass it as a value to another function so this time we're going to write a function expression I will
create a constant named hello equals a function parentheses curly braces we'll do the same thing we
will console.log hello and if I were to run this the identifier hello has already been declared so for now I'm
just going to remove this function declaration all we're doing is assigning a function to a variable to use the
function that's stored within we have to take our variable name and add a set of parentheses to invoke it kind of like
it's a pair of telephones talking to each other hello using JavaScript we also have the capability of passing a
function as a value I will introduce the set timeout function there's going to be two
parameters a call back to a function and an amount of time we're going to wait then execute
this function this will be in Mills 3,000 milliseconds translates to 3 seconds let me put this function back
after 3,000 milliseconds I will execute the hello function 1 2 3 hello instead of using a
function declaration we are going to pass a function expression as an argument to the set timeout function
instead of a call back we will create a function we will pass an entire function as an argument what are we going to do
we will after 3 seconds console.log thee word hello and let's see if this works just to prove that I'm
not a liar 1 2 3 hello in JavaScript it is legal to pass an entire function as an
argument or treat it as a value we'll use previous examples of the map filter and reduce methods of arrays I
will create an array const numbers equals the numbers 1 through six 1 2 3 4 5
6 I would like to square each of these numbers what we've done in a previous lesson is declare a function function
Square we had one parameter in that example we had an element what we did is we
returned math.pow to raise a base to a given power we're raising our element to the
power of two the map method will return a new array const squares
equals numbers. map we're passing in a call back to
square then console.log squares this works we are using a function
declaration but this time we will now use a function expression we will treat this function
as a value let's cut this function replace the call back then paste it within the map method
then we just need to remove the name we don't need a name and this is still going to
work yeah it still does we don't necessarily need to think of a function name one of the benefits of doing this
is that we're not polluting the global Nam space with function names we're only going to be using this function once
there's no need to declare a function let's create a function expression to cube these numbers now as a beginner it
might be helpful to write out your functions as a declaration first then transform it into a function
expression function Cube we have our element as a parameter I'm going to copy this return
math.pow element to the power of three we will create a new array const cubes equals
numbers. map we don't need to pass in a call back we will cut this entire function paste it within the map method
then we don't need the name then console.log cubes there are all the original numbers cubed all right
I think we're starting to get the hang of this let's quickly use the filter method to filter out any even or odd
numbers I will create const even nums equals take our array numbers we will use the filter
method then we will pass a function expression as an argument there's one parameter an
element we are going to return element modulus 2 to see if it's divisible by zero is is the result
strictly equal to zero let's see if this works console.log even nums there they are we have 2
46 let's do this with odd numbers odd nums use the filter method again all we're going to change is
strictly not equal to zero return any odd numbers
135 then lastly reduce we will sum all of the elements of the array const total equals our
numbers do reduce pass in a function expression we have two parameters an
accumulator and an element we will return
accumulator plus our element return the total which is 21 we already do have some practice with
map filter and reduce instead of using function declarations than passing a call back we can pass an entire function
expression as an argument to these methods in the next topic I'll discuss Arrow functions which shortens the
syntax even further you'll like Arrow functions all right everybody so those are function Expressions they are a way
to define functions as a value or a variable we've both defined a function expression as a variable we stored that
within this hello variable we've also passed entire functions as an argument which you can do with JavaScript there's
a few benefits of function Expressions one of which is you don't need to keep on thinking of function names you can
perform a function once then just forget about it they're also used in callbacks and asynchronous operations higher order
functions closures and event listeners these are topics we still need to discuss but we will be using function
Expressions a lot don't worry we will have more practice and well everybody those are function expressions in
JavaScript hey hello there so today I'm going to explain Arrow functions in JavaScript an arrow function is a
concise way to write a function expression it's good for simple functions that you only use once here's
the formula you have your parameters Arrow then some code you would like to perform here's an example suppose I have
a function declaration I have the hello function I'll work going to do is console.log the word hello to use this
function I need to call it by its name add a set of parenthesis this will display the word hello a concise way to
write the same function is to use an arrow function we'll begin with a function expression then convert it to
an arrow function just so we understand the differences this time I will create a constant hello hello is going to be a
constant that stores our function expression if I were using a a function expression we would say function
parenthesis curly braces then the code we want to perform console.log the word hello this would do the same thing
hello a more concise way to write this function expression would be to use an arrow
function following this formula we list our parameters we don't have any we need a set of parenthesis Arrow then some
code we would like to perform I'm going to console.log the word hello and that
works we're sticking an arrow function within a variable or named constant to invoke the arrow function within we just
follow that constant or variable with the set of parentheses like we're calling it as if it's a pair of
telephones talking to each other you can send some arguments to an arrow function we'll need to set up the parameters I
will have a name parameter within our code let's console.log I'll use a template string hello add a
placeholder add my name parameter now I need to pass in an argument because right now it's hello
undefined pass in your first name as an argument hello bro within your code if you need to include more than one
statement you'll need to enclose all of that code within a set of cly braces let's add a new
line console log you are old hello bro you are
old okay let's set up another parameter this time we will accept an age argument let's transform our second
console.log to be you are at a placeholder our parameter age years
old now we'll pass in a second argument for age hello bro you are 25 years old so that's
the basics of an arrow function you have your parameters Arrow then some code you would like to perform there's no need to
create a function declaration let's go over another example we have the set timeout
function this function accepts a call back then a given amount of time we are then going to execute this code this
callback after 3 seconds 3,000 milliseconds I will execute whatever this call back is let's create a
function to say hello again function hello we will console.log the word hello I will pass
in a call back after 3 seconds we say hello in place of a callback I could use a function expression let's cut our
function remove this argument then paste our function expression remember we don't need the name for a function
expression this works as well hello or otherwise we can use a more concise Arrow function we will pass
that as an argument we have our parameters we don't have any Arrow then some code
console.log the word hello after 3 seconds we display the word hello
now we'll use Arrow functions with map filter and reduce we have an array of numbers const
numbers equals the numbers 1 through six let's start with using the map filter to square each of these numbers
but we will use Arrow functions const squares equals our original array number
numbers. map normally we would pass in a callback as an argument but we're not going to do that we'll use an arrow
function we have one parameter an element
arrow take each element use math.pow to raise our element to a given power then let's console.log our
squares console.log squares there they are here are all the original num squared 1 4 9 16 25
36 let's Cube each number const cubes raise our element to the power of
three console.log are cubes there are all the numbers cubed we'll use the filter method to
filter out any numbers that are odd const even nums equals rray numbers we will use the filter method we
can pass in a call back but we don't need to we will pass in an arrow function we have our element as a
parameter Arrow we don't necessarily need a return statement if we have only one line of
code take our element modulus 2 is it divisible by two and does the strictly equal Z if it does it's an even number
let's console.log our even numbers 2 46 let's do this with odd numbers odd
nums take our element modulus 2 is it strictly not equal to zero display our odd nums 1
35 and lastly let's do reduce we will get a total by summing all all the elements of this array const total
equals our original array reduce pass in a call back or an arrow function this time we have two arguments an
accumulator and an element we have an Arrow return our accumulator plus our
element then display the total our our total is 21 all right everybody so those are
Arrow functions they're a concise way to write a function expression they're good for simple functions that you only use
once you list your parameters within a set of parentheses an arrow then some code you would like to perform in this
example we've written a more concise way to use the map filter and reduce methods normally we can pass in a call back as
an argument a function expression or an arrow function and well everybody those are Arrow functions in
JavaScript hey what's going on everybody in today's video I'm going to discuss objects in JavaScript an object is a
collection of related properties and or methods properties are things that an object has such as a first name or an
age a method is a function that belongs to an object for example I have a person object our person can say hello and they
can say by methods are just functions that belong to an object what can this object do objects can represent Real
World objects such as people products or places in this example we'll be creating some people objects people from the show
SpongeBob we'll start from scratch though we'll create a person object I'll use a constant although it's not
necessary const person equals then add a set of curly braces we'll start with any property
properties you can add as many properties as you would like they're in key value pairs this person will have a
first name key colon then some value this person's first name will be SpongeBob separate each key value pair
with a comma let's include a last name property last name colon space will be Square Pants add a comma when you're
done with this key value pair We'll add an age property of 30 age has a different data type it's a number the
first two in my example were both strings SpongeBob and Square Pants let's add a Boolean is
employed col in space I will set that to be true he has a job at the Crusty Crab okay that's good enough for now I would
like to access these properties let's console.log if I need one of these properties take the object you're
referring to in this case person dot the name of the property let's do first name person. first name property that would
give me SpongeBob let's do this with last name take the object name dot the name of the property person. last name
is SquarePants let's do this with age person. AG is
30 person. is employed is set to true all right let's create another object we'll create an
object for Patrick const person now objects can't have the same name objects need
different names for example I can't have two person objects they can't have the same name syntax error identifier person
has already been declared I will rename our first person as person one our second person will be person two then
any place in which I'm referencing person will now need to be person one
let's reuse these same key value pairs person two's first name will be Patrick his last name will be star
Patrick will be I don't know how old he is according to the TV series let's say he's
42 is Patrick employed no he just watches TV all day now I would like to access person 2's
properties okay well console.log person 2's first name person 2's last name Person 2's age person two
is employed okay for person two we have Patrick Star 42
false so those are properties of an object they're key value pairs add as many as you would like in this example
these properties mimic real world attributes that a person might have like a first name last name age whatever you
can think of but not only that objects can have dedicated functions that we refer to as methods what sorts of
actions can these objects perform for example a person could eat they could drink they could sleep what sorts of
things do people do so just to keep this simple I am going to create a function to say hello we'll start with person
one say hello col in space this will be a function
expression what are we going to do when we invoke this function let's console.log
what would SpongeBob say if he's greeting somebody hi I'm SpongeBob be sure you're not including a
semicolon at the end that should work let's test it I'm going to have person one invoke
their say hello method hi I'm SpongeBob let's add a say hello method to Patrick person
two we'll change the output if say hello what would Patrick
say hey I'm Patrick dot dot dot now we'll have person two use their say hello
method hey I'm Patrick you can add as many methods as you would like so with these functions we're using a function
expression if you prefer you could even use an arrow function list your
arguments Arrow then the code you would like to perform this would work too let's add an eat method eat
function we'll use a function expression for SpongeBob let's console.
log what is SpongeBob eating I am eating a crabby patty we'll include an eat function for
Patrick as well what's Patrick going to eat Patrick is
eating I'm eating roast beef chicken and
pizza and if you would like you can use an arrow function for this example list your parameters Arrow then
the code you would like to perform it's not necessary but I do like Arrow functions person one SpongeBob
will use his eat method same thing goes with Patrick person two so SpongeBob is eating a crabby patty
Patrick is eating roast beef chicken and Pizza all right everybody so JavaScript objects are a collection of related
properties and or methods properties are what an object has methods are functions that an object can perform they can
represent Real World objects such as people products or places properties are key value pairs methods are functions
that belong to another object and well everybody that is an introduction to object-oriented programming in
JavaScript hey so we got to talk about this this is a keyword it's a reference to the object where this is used the
object depends on the immediate context if we had a person object and we're accessing their name property we could
replace person with this as long as we're within the context of that person object we'll create an object
const person one let's add a property for name the name will be
SpongeBob and a favorite food property fave food SpongeBob likes hamburgers more specifically Krabby
Patties I will give SpongeBob a say hello method this will be a function all we're going to do is
console.log I'll use a template string hi I am I'll use a placeholder let's attempt to use person one's name
let's see what happens let's take our object of person one I will invoke their say hello method
let's see what happens hello I am and there's nothing here for the name inside of this object of person one if I would
like to access one of these properties I'm going toe received the property with this this do the name of the property
and that should work hi I'm SpongeBob we're using this within the context of person one it would be like
us saying person one. name there would be no difference this is a reference to the object we're within if I said this
do favorite food well favorite food for short hi I am hamburgers it would be like like us saying person one. fave
food let's add another method I will add an eat method let's
console.log I'll use another template string add a placeholder
this.name is eating add another placeholder this. fave food let's have person one use their eat
method SpongeBob is eating hamburgers the cool thing about the this keyword is that if we create a new object with
these same methods we'll use the second object's properties let's copy person one paste change person one to person
two the name for person two will be Patrick favorite food will be Pizza let's have person two use their
eat method SpongeBob is eating hamburgers Patrick is eating pizza since we're in
the context of person two now imagine we're replacing this with person two person 2.n name Person 2. fave
food if you were to use this outside of any objects I'm going to console.log this what we're returned with is a
window object basically we're returning the window to see our website technically we're inside of an object
already our window object and we have all of these properties but since we're using the
this keyword inside the context of person one and person two we'll instead make a reference to those objects hey
one thing I forgot to mention the this keyword doesn't work with arrow functions for example with person two
let's convert this to an arrow function blank is eating undefined when you use
this within an arrow function it's making a reference to that window object still our window object does have a name
that's why it's appearing empty but fave food is undefined because our window object doesn't have a favorite food
property all right everybody so that is the this keyword we will be using this keyword a lot all it is is a reference a
reference to the object where this is used and that is the this keyword in JavaScript what's up people so today I
got to explain Constructors in JavaScript a Constructor is a special method for defining the properties and
methods of objects in Prior videos we've constructed objects like this we would declare an object assign it some
properties and some methods you know this works but what if we have to create a lot of objects here I'm manually
creating three different car objects that can be a lot lot of work what we could do instead is use a Constructor to
construct these objects automatically all we have to do to construct these objects is passing some unique data to
the Constructor to construct these objects here's an example we are going to create a function
car do pay attention to the capitalization we'll need to set up some parameters what sorts of properties will
we accept when we construct a car object how about a make model year and
color these are arguments we'll receive when we construct a car object to assign these properties we're going to use the
this keyword doake equals the make that we receive let's do this with model this
dood model equals the model we receive this doe equals year this do color equals color
that's good enough for now our car Constructor is a reusable method where we can define the properties and methods
of objects we create to use this Constructor I will create an instance of an
object I will use const car1 will be our first object equals we'll need to use the new keyword type the name of the
Constructor car car is a special method we'll need to pass in some arguments we'll need a make model year and color
in that order my first car feel free to send some different data to the Constructor but for me my first car will
be a Ford make sure each value is comma separated Mustang the year will be
2024 and the color will be red we should now have a car object with the name of car one and I'm going to
console. log car 1's properties car 1. make Ford let's do this with the other properties we have
model Mustang year
2024 and color red now this method is reusable we can reuse it to create other car
objects let's create const Car 2 equals new car we'll pass in different data this time the make will be Chevrolet
I will pick a Camaro the year 2025 and the color will be blue now I
can display car 2's properties let's select car 2make car 2. model car 2. year car 2.c color we have
a Chevy Camaro year 2025 the color is blue let's create one more car same process as before const car 3 equals new
car I'll go with a Dodge Charger the year
2026 and the color will be silver let's access K 3's properties car 3. make car 3. model car 3. year car
3.ol Dodge Charger 2026 the color is silver another thing with these parameters too you can name these
parameters anything when we assign these properties it can be kind of confusing like this. make equals make really we
write our Constructors this way just for readability technically this would work if we renamed our parameters for example
make will be parameter a model will be B year is C color is D then be sure to change these when we assign them A B C D
this would still work however this Constructor isn't as readable like what the heck is a b c and d it would be good
practice to clear clearly Define our parameters for readability purposes all right now let's add a
method we'll take this. Drive equals a function we
console.log I'll use a template string you drive the I'll add a placeholder this do
model With Cars 1 through three let's use the drive method car 1.
drive you drive the Mustang car 2. drive you drive the Camaro and car 3.
drive you drive the charger all right everybody so that's a Constructor it's a special method for defining the
properties and methods of objects it helps with code reusability we can reuse it to create many objects instead of
having to type them all out manually and well everybody those are Constructors in JavaScript all right let's do this thing
so I got to talk about classes and JavaScript classes are an es6 feature that provides a more structured and
cleaner way to work with objects compared to the traditional Constructor functions that we're normally used to
classes are going to be really helpful when we reach future topics such as the static keyword encapsulation and
inheritance in this example I have a Constructor for a product our product needs a name and a price for example we
have a shirt and the price is 1999 instead of using a Constructor method we're instead going to use a class our
class will include a Constructor so let's start from the beginning to create a class you type
class then the name of the object so our class is going to serve as a blueprint our objects will be products then add a
set of curly BRAC to use a Constructor we can use the Constructor keyword within our
class list any parameters we will have a name and a price for each product we will assign the properties of this.name
equals the name parameter that we receive this. price equals price I will also create a
function our function will be display product now in inside of a class you don't need to use the function
keyword when we would like to display this product we will console.log product colon space I'll
include a placeholder this.name let's also output the
price price pick a unit of currency I'll use American dollars this do price let's create some
product object objects const product one equals to create a new object we have to use that
new keyword the name of the class product The Constructor is going to be called automatically but we do need to
pass in a name and a price as arguments we will pass in a shirt the price will be
$19.99 just to be sure that everything works let's invoke the display product method product one do display product
method here are the details of our product object product shirt priced $19.99 let's create a few more so this
class is reusable product two will be
pants I'll pick 2250 for the price let's display product two product two and we will use use the display
product method of our class product pants the price is $22.50 uh looks like I only have one
decimal point I'm going to make one change after the price I will use the two fixed method and set this to be two
decimals there 2250 all right product three const product 3 equals new
product our third product is going to be underwear this underwear is really expensive it's
$100 it's really good underwear guys product 3. display product product underwear price
$100 here's a challenge round I'm going to add another method this method will have one parameter sales tax we'll
create a method to calculate a total including tax so let's create a new method inside of a class we don't need
the function keyword calculate total there will be one parameter sales tax all we're going to do is return
this. Price Plus to calculate the sales tax we'll take this. price times the sales tax assuming it's a
percentage okay let's display product one product one. display product I'm also going to create a constant for the
sales tax that's not going to change const sales tax let's say the sales tax is 5%
0.05 I will create a variable const total equals let's take product one use the calculate total method but we have
to pass in sales tax we can either pass in this number or this variable once we have our total let's
display it console.log I'll use a template string total price in parentheses with
tax I'll add a placeholder display the total pick a unit of currency I'll use American
dollars then I'll add two fixed two to set it to two decimal places all right our product is a shirt
price is $1 199.99 total price with tax is $20.99 9 let's do this with product two product two. display product product
two. calulate total pants 2250 total price 2363 let's check out our really
expensive underwear product 3. display product product 3. calculate total our underwear is $100 including sales tax
it's $115 all right everybody so those are classes they're an es6 feature that
provide a more structured and cleaner way to work with objects compared to the traditional Constructor functions that
we learned about in the last video classes are going to be really helpful with a few upcoming topics and well
everybody those are classes in JavaScript hey people let's do this thing so the static keyword static is a
keyword that defines Properties or methods that belong to a class itself rather than the objects created from
that class in summary a class own own anything static not the objects so what we're going to do is create a class for
math utilities class math util for short we'll create our own version of Pi
we'll use the static keyword the name will be Pi Pi will equal 3.14159 just the first few digits I'm
going to zoom in a little if I would like the static property I have to access it by its class so let's
console llog the name of the class math util dot the name of the property Pi our static
property is 3.14159 I don't need to create an object in order to use this property I don't
have to type const math UIL one equals new math youtil I would have to type math util
one that's the name of this object in order to access Pi all I have to do is type the name of the
class and that's pretty convenient anything declared as static belongs to the class itself and not any object
created from that class so now we're going to create a static method we'll use the static keyword
we'll get a diameter once we pass in a radius as an argument get diameter we have one parameter a radius
all we're going to do is return radius time 2 okay let's
console do log again we have to type the name of the class Matthew till dot the name of the method get
diameter we have to pass in a radius though let's pass in 10 our diameter is 20 let's create a new
static method for get circumference get circumference the formula is going to be
we will be returning 2 times this meaning Matthew till.
pi times the radius we receive let's console.log let me make the C Capital
the name of the class Matthew till dot get circumference pass in a
radius the circumference is 62.83 let's create one more for get area static get area we need a
radius we will return this Pi time
radius time radius so that's Rus squared console.log Matthew till the name of the
class get area pass in 10 and the area is 31415 in the next example we'll have a
mix of regular properties and methods and static properties and methods this will be example
two we'll create a class of users class user we'll create a static variable to keep
track of the amount of users we create user count I will set that equal to
zero I'll include a Constructor let me just space this out a little our Constructor is going to be
automatically called when we instantiate a new object we need one argument though when we create a new user we need a
username once we have our username we will assign this do username equals username not only that but when we
create a new user I'm going to increase our user count by one just so we can keep track of how many users we create
so inside of the Constructor you can write additional code it's not only for assigning
properties let's take user do user count Plus+ to increment
it let's create some user objects const user one equals new user pass in a username I'll pass in
SpongeBob then let's console.log user one's username which is
SpongeBob let's attempt to access user one's user count with user one's user count we get
undefined that's because our user doesn't have user count as a property it's static that means it belongs to the
class not any objects created from the class to access user count we have to type the name of the
class user in this case we have one user let's see what happens when I create a new user
object user 2 will equal Patrick our user count is now two
let's display user 2's name yep we have SpongeBob and Patrick the total user count is
two let's create a third user user three will be Sandy
console.log user 3. username our user count is now three we have a static property that's
keeping track of the amount of users we create let's create a method the first one will not be static say
hello all we're going to do is console.log I'll use a template string hello my
username is I'll add a placeholder this do username let's have user one use there
say hello method same thing with user two and user
three hello my username is SpongeBob Patrick and Sandy now we'll create a static method we'll get the
user count get user count
console.log I'll use a template string there are I'll add a
placeholder user. user count users
online now in order to access this method I have to type the name of the class user. getet user
count oops and I can't conso that log that user. getet user count there are three users online all
right everybody so that is the static keyword it defines properties and methods that belong to a class itself
rather than any objects created from that class in summary the class owns anything static not the objects and well
that is the static keyword in JavaScript hey what's up everybody so in today's video I got to explain
inheritance inheritance allows a new class to inherit properties and methods from an existing class these two classes
have a parent child relationship a child will inherit properties and methods from a parent it's kind of like a family tree
a child will inherit genes from a parent inheritance helps with code reusability because we don't need to keep on
repeating the same properties and methods if all the children share them here's an example we'll create an animal
class class animal will have a property of alive if you're an animal you start off being
alive all animals should be able to eat and sleep we'll create methods for those we'll have an eat method all we're
going to do is console.log I'll use a template string this now I'll add a
placeholder this do name is eating and a Sleep
Method sleep this this.net name is sleeping animal will be the parent class
we'll create children classes that inherit these properties and methods let's create a few children classes
class rabbit our rabbit class will inherit all the properties and methods of the animal class to declare a parent
child relationship the child will extends the parent animal for the rabbit I'm going to give
this class A Name name equals rabbit this will be a property if you're familiar with the
static keyword you can make the static now we'll create a fish class that also extends animal class fish
extends animal fish will have one property name equals
fish and a hawk class class Hawk extends animal will have one name
property Hawk all right let's see if this works if we create a rabbit fish and Hawk
object they should have access to these properties and methods let's create const rabbit equals
new rabbit const fish equals new
fish const Hawk equals New Hawk all right let's see if our rabbit
has an A Life Property console.log take the name of the object
rabbit do access a property or method alive that's our property the rabbit is alive but what if the hawk swoops in and
kills the rabbit let's change the alive property of the rabbit rabbit. alive equals false the rabbit is
no longer alive now let's see if our rabbit has access to a eat and Sleep
Method rabbit. eat this rabbit is eating and sleep rabbit.
sleep the rabbit is sleeping Let's test this with fish fish. alive fish. eat method fish.
SLE method the fish is alive the fish is eating the fish is
sleeping and Hawk hawk. alive hawk. eat method hawk. SLE method the hawk Is Alive the hawk is eating the hawk is
sleeping our children classes of rabbit fish and Hawk all inherited the properties and methods of the parent
animal class this helps with code reusability because I don't need to declare all of these properties and
methods within each of the children classes like this we're saving a lot of lines of code
it's not that apparent with just a few child classes but imagine if you had hundreds of different child classes well
by using inheritance you would be saving a lot of time but not only that the children can have their own unique
properties and methods too for example rabbits will be able to run but fish and Hawks can't run that's a method that
only belongs to rabbits within our rabbit class let's create a new method a run
method we'll console.log I'll use a template string
this add a placeholder this.name is
running within our fish class let's create a swim method
swim this this.n name is swimming and Hawks will be able to fly we'll create a fly method this this
do name is flying let's minimize these classes let's take our rabbit object
display the alive property the eat method the Sleep Method and the run method rabbit. run method the rabbit is
eating the rabbit is sleeping the rabbit is running now let's do this with fish fish. alive
fish. eat method fish. SLE method now does the fish have a run method it does not fish. run is not a function run is a
method that belongs to the rabbit class fish can't run because well they don't have legs we did not give our fish class
a run method they can swim though but they can't run fish. swim method the fish is swimming let's do
this with Hawk our Hawk cannot swim but it can fly we'll use the fly
method the hawk is eating the hawk is sleeping the hawk is flying and of course our rabbit can't fly or
Swim does our rabbit have a fly method it does not rabbit. fly is not a function all right everybody so that's
inheritance it allows a new class to inherit properties and methods from an existing Class A Child inherits
properties and methods from a parent it helps with code reusability I don't need to declare all of these properties and
methods for each of these classes I can simply reuse it that helps us follow the dry principle don't repeat
yourself and well everybody that is an introduction to inheritance in JavaScript yo what's going on everybody
so in today's video I'm going to explain the super keyword in JavaScript super is a keyword that's used in classes to call
the Constructor or access the properties and methods of a parent the parent is also known as the super class it's very
similar to the this keyword this refers to this object super refers to the parent of that object here's an example
we'll use inheritance to create a parent class of animal class animal our animal class will have three children also
known as sub classes class rabbit extends animal class fish extends animal class
Hawk extends animal we'll add an empty Constructor for now for the animal
class then we need a Constructor for the rabbit class so rabbits they'll have a name
property a and a run speed we'll assign these properties within the Constructor
this.name equals the name that we receive this. AG equals age this. runp speed equals run
speed let's copy this Constructor now with fish fish don't have a run speed but they'll have a swim
speed let's replace run speed with swim speed copy The Constructor again paste it Hawks in this example won't have a
swim speed they'll have a fly speed though replace swim speed with fly speed now let's attempt to create some of
these objects const rabbit equals new rabbit we need a name for this rabbit you could just say rabbit or if you want
to be creative you could say something like Bugs Bunny uh but let's just stick with
rabbit to keep it simple our rabbit will be Oney old and has a run speed of 25 mph if you use kilm feel free to use
kilom let's do this with fish const fish equals new fish the name of our fish will be fish
our fish is 2 years old and has a swim speed of 12 mil hour then with Hawk const Hawk equals
New Hawk our Hawk will have a name of Hawk our Hawk will be 3 years years old and has a fly speed of 50
mph so when I run this program we have an uncaught reference error must call Super Constructor in derived class
before accessing the this keyword so what JavaScript is telling us is that before we can use the this keyword we
have to call the Constructor of the parent the super class within each of these respective Constructors we will
invoke the Constructor of the parent the super class with the super keyword so let's do that for for each of these
Constructors now our program actually runs now so one of the benefits of using Constructors is that if there's any
properties that the children all share in common we can send them to the Constructor of the parent as you can see
we're repeating ourselves a lot each of these children classes has a name and age property that we're assigning to
each we would like to follow the dry principle don't repeat yourself so why don't we write this code once and reuse
it so within the Constructor of the parent will accept a name and age property we'll assign this.name equals
name and this. AG equals age now we can remove that within each of the child classes so we don't repeat
ourselves there's less code to right now but we do need to pass in these arguments to the parent Constructor name
and age for each and that's all there is to it in this
example when we construct an object either a rabbit a fish or a hawk we'll accept three arguments a name age and
either a run speed a swim speed or a fly speed depending on the animal that we're creating any properties they share in
common we can send to the parent Constructor it helps with code reusability and there's a lot less to
write it's not that evident with three children classes but imagine if you had hundreds of different classes like what
if this was Pokémon there's like what a, Pokémon now we would have to copy and paste those properties like a thousand
times for each if we're constructing individual Pokémon but since all of them share those same properties we can write
it in one place and make any changes only in one place so let's test this to see if it works let's
console.log our rabbit's name which is named rabbit let's console.log the rabbit's age the rabbit
is Oney old and let's see if the rabbit has a run speed 25 as in 25 mph let's do this with
fish fish. name fish. AG let's see if the fish has a run speed name is fish Age Two run speed is
undefined because fish can't run because they don't have legs but they do have a swim speed though swim speed 12
milph then Hawk hawk. name hawk. AG hawk. flyp speed name is Hawk age 3 the hawk has a fly speed of 50
mph so that's how you can use the super keyword in a class to call the Constructor of the parent it helps with
code reusability any properties that the children share in common in this case a name and Age The Constructor of the
parent can take care of that we don't have to repeat the set of code every single time for each child we write it
in one place and reuse it another thing you can do too with the super keyword is extend a method from the parent so what
we're going to do within the animal par class is create a move method within this method we will
console.log the following message the at a placeholder this.name moves at a speed of add a
placeholder speed mph for miles per hour or if you prefer you can use kilometers our move method will have one parameter
a speed that we need to pass in to use So within each of these children classes we'll write a method that also extends
the move method of the parent rabbits will have a run method we'll output the following
message console.log I'll use a template string this add a
placeholder this.name can run let's copy our run me method paste
it for fish but change swim to run because fish can't run this this.name can
swim then with Hawks they'll have a fly method fly this this. name can fly with our rabbit object let's invoke
the run method this rabbit can run let's do this with fish fish. swim this fish can swim
and hawkfly Method this Hawk can fly within each of these children classes we're going to extend the move method of
the parent animal within the run method of our rabbit class not only are we going to Output this
message we'll also extend the move method of the parent and display that message as well to refer to the parent
class we use the super keyword it's very similar to this but it means the parent use the parents move method but we do
have to send a speed argument let's send the Run speed of the rabbit this. runspeed let's do this with our fish
class we'll extend the move method super. move send in this. swim speed and Hawk super. move this. flype
speed now let's take our rabbit use the run method and we should extend the move method this rabbit can run the rabbit
moves at a speed of 25 mph let's do this with fish fish. swim the fish can swim the fish moves at a
speed of 12 mph and hawk hawk. fly method this Hawk can fly the hawk moves at a speed of 50
mph so that's how you can use the super keyword to extend a method of apparent all right everybody so that's the Super
Key word it's a reference to a parent it can be used to call the Constructor of a parent and or access the properties and
methods of a parent and well everybody that is the super keyword in JavaScript hey hello so uh today I'm
going to explain Getters and Setters in JavaScript Getters are special methods that make a property readable Setters
are special methods that make a property writable we can use use Getters and Setters to validate and modify a value
when reading or writing a property it helps with validation when creating an object or updating one of its properties
here's an example we will create a class of rectangle we need a
Constructor we will have two parameters a width and a height we will assign this. width equals
width this. height equals
height now let's create a rectangle object const rectangle equals a new rectangle for the width let's say -1
million something ridiculous and for the height I want the height to be Pizza the word
pizza then let's console.log our
rectangles width and the rectangle height we have created a rectangle object with the width of 1 million and a
height of pizza which doesn't make any sense we could use some validation when creating an object we don't want people
to enter in garbage values like negative a million or string when we're expecting a positive number for the width or
height that's where Getters and Setters come in we'll begin with set letters when setting one of these properties
either initially through a Constructor or updating one of them later such as setting the width or height equal to
some value we can go through a Setter first outside of our Constructor we will set a property we'll begin with
width this will be a special type of method the parameter will be new width what do we want to check before
assigning this property using an if statement let's check to see if the new width that the user sends us is greater
than zero if it is we will assign this doore width using an underscore prefix it
tells other developers that this is a private property you shouldn't touch it at all you could say that this private
property of width is different than our standard width property we will assign the private property of width equal to
the new width we receive else let's console. error not log we'll use error
this time width must be a positive number all right let's see what
happens width must be a positive number and our width is currently undefined which is good okay let's do this with
height let's copy our Setter for width paste it but change every instance of width to be height set height New
Height be sure to use that Camel case naming convention if new height is greater than
zero assign the private property of height equal to the new height else console.
error height must be a positive number and there we go that worked width must be a positive number and height
must be a positive number our width and height are currently undefined in order to set the width and
height we have to pass in a positive number for the width I will say three for the width four now when we access
width and height those numbers still aren't showing up that's because these properties are writable via Setters but
they're not readable that's where Getters come in we'll create two Getters one for
width we'll need to use the get keyword get width this will be another type of
method all we're going to do is return this private width and that appeared to work we have
three for the width let's do so with the height we will return this private
height we have three and four Now by using Setters we can even update those values later let's take our
rectangles width set that equal to be five take the height set it equal to be six and that
also appears to work but again if I try and update those values to some garbage values like negative a million and the
word Pizza we get those errors again and our our object retains its initial values
that we previously assigned it three and four with Getters we can even use the property accessor that dot to access a
property that doesn't necessarily exist for example we will get area we'll perform a
calculation we will return this private width times this private height
so now we can access area as if it was a property we have three for the width height four our width times our height
gives us an area of 12 our area isn't a property technically it's not found within our
Constructor but we can access it as if it was a property with a getter with Getters you can even add additional
logic I would like to preserve the initial values of our width and height when I return their value I will use the
two fixed method to give each of these a Precision of one let's do that with the width the
height and the area but that's going to be a little more complex we'll enclose width time height then add to fixed
one and why stop there I'll add centimeters to the end of each I'll use a template
string add a placeholder then add CM for M 3.0
cm and the area 12.0 CM let's make that centimet squared because it's area Technically
when you're assigning values even when you're initially creating an object you can go through the Setters for input
validation when you retrieve values and try and read them you can add additional logic too let's go over a second example
we will create a class of person we need a Constructor we will accept a first
name last name and an age this. first
name equals first name this. last name equals last name this. AG equals
age let's construct a person const person equals new person let's enter in some values that
don't make sense the person's first name will be the number 420 their last name is the number 69 their age is the word
Pizza let's console.log our person objects first name which is the number
420 their last name 69 and their age the word Pizza we need to validate this input before assigning the
properties that's why we need Setters we will set the first name property this is a special type of method the parameter
is going to be a new first name we need to be sure that this value passed in is a string and the length is
greater than zero we could write something like this we need an if statement let's check the type of our
new first name is it strictly equal to a string and is our new first nam's length property greater than
zero if all of that checks out we will assign this this private first name equal to the new first name we
receive else let's console. error first name must be a nonempty string let's see if this worked
I'm going to save first name must be a non-empty string and currently our first name is undefined okay that worked let's
copy our Setter for our first name paste it change every instance of first name to last
name new last name check if the type of our last name is equal to a string and if our new last
name the length of it is greater than zero if it is assign the private last name property equal to the new last name
else last name must be a non-empty string that also worked our first name and last name are undefined let's do
this with age set our age the parameter is going to be new
age using an if statement is the type of new age strictly equal to a data type of number and is our new age greater than
or equal to zero if it is take this private age equals our new age else we're going to console.
error age must be a non negative number we can no longer assign pizza for our age unfortunately
all right we have our setter set up now let's work on the Getters let's assign some legitimate values for the first
name SpongeBob last name SquarePants age 30 we don't have those errors anymore that means they're set
but those properties aren't readable that's why we need Getters let's get the first name get first
name return this private first name there's SpongeBob his first name get last
name return this private last name there's his last name let's create a getter for a full name
too let's console.log a full name even though we have no property for that that's
undefined we'll use a getter to mimic a full name property by just combining the first name and the last name properties
get full name return I'm going to use some string cination this private first name
plus a space character this private last name and there's his full name SpongeBob
SquarePants and the age get age return this private
age and SpongeBob is 30 all right everybody those are Getters and Setters Getters are special methods
that make a property readable Setters are special methods that make a property writable by using a combination of both
we can validate and modify a value when reading or writing a property and well everybody those are Getters and Setters
in JavaScript hey what's good everybody so in today's
video I'm going to give you a lesson in destructuring in JavaScript destructuring allows us to extract
values from arrays and objects then assign them to variables in a convenient way we can use straight brackets to
perform array destructuring or curly braces to perform object destructuring I'll give you five different examples
example one swap the value of two variables we'll have let a equal 1 let B equal to to use array D structuring we
need a set of straight brackets add the variables a comma B this will equal we're creating a new
array on the right hand side B comma a on the Le hand side of our equals we're using destructuring on the right hand
side we're creating an array let's see what's within variables A and B console.log variable a then variable B
so if these values are swapped we should have two then one not one and two that's example one we can use destructuring to
swap the value of two variables example two we can swap two elements in an array let's create an
array of colors const colors equals an array pick some colors I'll go with RGB so that
would be red green blue let's add black and
white suppose I would like to swap the position of the first element and the last element this first element has an
index of zero this particular last element has an index of four again we're going to use array to structuring we
need a set of straight brackets we'll take our array colors at index of zero comma rray at index of four we want
to swap red with white 0 1 2 3 4 that's the fourth index equals we're creating a new array by using Straight brackets
colors at index 4 comma colors at index zero then let's print our
array console.log R array of colors there we go we have white green
blue black red that's how we can use destructuring to swap two elements in an
array example three we can assign array elements to variables we'll declare a bunch of variables const we'll use
destructuring we're destructuring an array we need a set of straight brackets we'll create some variable names first
color Second Color third color I will assign this equal to our
array Colors Let's print these variables
console.log our first color we have red second color
green third color blue you could combine array D structuring with rest parameters we have two colors left let's assign
that to a new array we'll use rest parameters I will name this array extra colors then we will
console.log extra colors and that should be a new array that has the remaining colors black and white that's how to
assign array elements to variables using destructuring example for extract values from objects we'll create two people
objects const person one person one will have a few few properties first name will be
SpongeBob last name will be SquarePants age will be 30 and a job meaning
occupation not John job his job is that he is a fry cook all right let's copy person one
looks like that n should be capital in last name all right let's copy person one paste it change person one to person
two the first name of person two will be Patrick last name star age will be 34 person two is not going to have a job
property he's unemployed using destructuring I can extract values from these
objects we'll create a few variables const we'll use object destructuring we need a set of curly braces this time
we'll create these VAR variables first name last name age and job now this equals let's start with
person one let's display these variables console.log first name is
SpongeBob last name SquarePants age 30 job fry cook let's do this with person
two Patrick Star his age is 34 person two does not have a job property person one does though our job variable is
undefined as you can see here you can set default values when using destructuring if somebody doesn't have a
job property we'll set job to equal unemployed let's see if that works yep Patrick Star age 34 his job is he's
unemployed that's how you can extract values from objects values extracted can even have default
values all right last example we can destructure in function parameters we can pass an object to a function and
destructure it when it's passed in let's create a function we will create a function to display a person
with the parameters we'll use destructuring we're destructuring an object we need a set of curly braces
we'll receive an object such as this I'm going to invoke display person we'll pass in person one as an argument when
we receive person one as an argument we'll destructure that object right away we will create a first name parameter
last name age and job all we'll do is print a few lines using
console.log I'll use a template string let's say Name colon space I'll add a placeholder first
name and last name let's add a new line age call in space add a placeholder
age then lastly job job colon space add a placeholder job we're passing in person one and D
structuring it we should display name SpongeBob SquarePants age 30 job fry cook let's pass in person two as an
argument name Patrick Star age 34 job is undefined again we can set a default value when destructuring if an object
doesn't have a job property we will set that equal to be unemployed Patrick Star age 34 job
unemployed then if we pass in person one again his job should not be unemployed he's a fry cook there is a job property
so we do not use the default value all right everybody so those are a few examples of destructuring there's a lot
you can do with destructuring you use a set of straight brackets to perform array destructuring or curly braces for
object destructuring they allow you to extract values from aray and objects then assign them to variables in a
convenient way and well that is destructuring in JavaScript so uh yeah we're doing a
thing today today I got to explain nested objects in JavaScript nested objects are objects inside of other
objects they allow you to represent more complex data structures a child object is enclosed by a parent object by using
nested objects we have the cap capability of creating some very complex data structures for example a person
object could contain an address object as well as a contact info object or a shopping cart object each item in your
shopping cart is an individual object such as a keyboard a mouse or a monitor each of these child objects would have
their own properties and methods for example a price a name specifications on the item a shipping method nested
objects are just objects inside of other objects let me give you a basic example we'll create a person object const
person equals an object we need to set a curly BRAC a person might have a full name
property I will set that to be SpongeBob in this example SpongeBob SquarePants an age of
30 is SpongeBob a student is student he's in boting school so let's say that's true objects can also contain
array we'll create an array of hobbies to declare an array you need a
set of straight brackets what sorts of hobbies does SpongeBob have he knows karate he does
jellyfishing I need one more uh let's say that he enjoys cooking now we're going to create a
nested object this person object will have an address object so we need a set of curly braces
a few of the properties of the inner address object could be a street SpongeBob has an address of 124 con
Street his City will be bikini bottom and a country we won't do a full address but I think this is good enough
for this example so SpongeBob lives in the ocean let's say that his country is international waters I'll just
abbreviate International our person object has a nested address object inside of it to access some of these
properties of our person object we would type the name of the object use the property accessor which
is dot then the name of the property full name SpongeBob SquarePants let's print his
age 30 is SpongeBob a student that is true I'm going to display the array of hob
person. Hobbies this will give you an array but if you need individual elements you have to list an index
number so Hobbies at index zero would be karate one is jellyfishing index two is cooking let's
console.log our person object dot the address object this would return an entire
object if you need one of the properties within this object that's within the person object you would have to follow
the inner object with the property accessor again that dot person. address. Street which would give you 124 con
Street the city person. address. city Bikini Bottom person. address. country
international waters so when accessing a property within a nested object you have to use the property accessor t
that dot if you would like to Loop through the properties of a nested object you can write a for Loop like
this for const property in person. address
console.log take our person object access the nested object address then use the index of operator the straight
brackets give me the current property and there we are all right let's make something a little more
complicated we're going to create a class that utilizes nested objects so we will begin with
class address our class will have a Constructor for an address we need these
three things feel free to add more if you would like a street City and Country then we'll assign these
properties this. Street equals Street this. City equals City this. Country equals
country now we'll create a person class class person our person class will also have a
Constructor we'll need a name age and an address for the address I'm going to use rest
parameters we can pass in different parts of an address and store it within an array when we create a person object
we will assign this.name equals name this. AG equals age now for the address we're going to construct an address
object this. address equals a new address we're going to call the Constructor of our address class and
pass in our address I'm going to utilize the spread operator to spread our
address we'll send our address object a street City and Country all right let's construct some of these person
objects const person one equals a new person this will call the Constructor but we have to pass in arguments to
match the parameter a name we'll just do a first name to keep it short an age SpongeBob will be
30 we also need an address a street City and Country
124 con Street City will be Bikini Bottom his country will be international
waters and just for readability I'm going to put the address on a new line let's create person
two person two will be Patrick age 37 Patrick will live on 128 con Street
he'll have the same city and the same country then let's make person three person three will be
Squidward age 45 Squidward will live on 126 constr all right let's see if this all
worked console.log let's start with person one person one. name which is
SpongeBob age 30 let's get his address address and this returns an object which is good that's what we
wanted we have a nested object an address object for some of the properties within that address object we
have a street City and Country we use the property accessor again of dot give me the street 124 con Street the city
bikini bottom and the country international waters all right let's confirm this with person 3 just to
be sure it all works person 3 give me the name Squidward age
45 address gives me an object we'll use the property accessor again give me the street 126 con Street the city beini
bottom and the country international waters this will also all work for person two if it worked with person one
and three all right everybody so those are nested objects they're objects inside of other objects
they allow you to represent more complex data structures a child object is enclosed by a parent object in this
example our address is the child object of the person object we're creating a new object within our person object and
well everybody those are nested objects in JavaScript hey what's up everybody so in
today's video I'm going to show you how we can work with an array of objects in JavaScript what we'll do is create an
array of fruit objects we'll create five fruit objects to create an object you need a set of krly braces each object
will be comma separated just for my own readability I'm going to place each object on a new
line objects can have their own unique properties and methods our first fruit object will have a name of
Apple a color of red and calories meaning calories per
serving of 95 this is our first object let's copy these properties paste them for object
two change name to be orange color will also be orange calories
45 object three name will be banana color yellow calories 105 object
4 coconut color white calories 159 then our last object will be pineapple color yellow calories
37 all right and here is our array of objects there's a lot we can do with this if you ever need a property within
one of these objects of your array you would take the array in this cas fruits add an index number dot the name
of the property for example name I need the name property of the first object which would be Apple so let's test that
console.log what is the name property of our aray fruits at index zero that would be apple one is orange two is
banana three is coconut four pineapple let's select a different property let's go with the
calories 95 45 105 159 37 that's how to access a
property within an array of objects to add a new object you can use the push method let's take our array of fruits
use the push method we will push a new object into our array the name will be
grapes Color Purple
calories 62 then let's console.log R array console.log fruits so we have six
Apple orange banana coconut pineapple and grapes uh which I misspelled grap you can use the pop method to
remove an element fruits pop this should remove
pineapple Apple orange banana coconut no pineapple or splice splice will remove elements at certain indices fruits.
splice let's select indices 1 through two all we're left with is Apple coconut pineapple you can use the for each
method to Loop through the elements of your array let's display each object's name
fruits. for each we need a call back a function expression or an arrow function let's use an arrow function for every
fruit do this console.log each fruit this will return entire
objects for one of the properties we'll select dot the property name we have all the fruit
names let's go with the colors and the calories there we are there's also the map method the map
method will run each element through a function and return a new array let's create an array of fruit names const
fruit names equals take our array of fruits use the built-in map method we'll use an arrow function for every
fruit Arrow return the fruits name then we will
console.log our array of fruit names and here's our array of fruit names let's do this with
colors fruit colors return every color property of each
fruit then console.log our fruit colors red orange yellow white yellow let's do this with
calories fruit calories return each calories
property console. log our fruit calories array so the map method we'll return a new array let's cover filter filter will
return a new array after using each element and checking a condition let's return a new array where the color of
each fruit is yellow there's two const yellow fruits equals take our array of
fruits use the filter method we have one parameter a fruit Arrow then a condition we'll return this fruit if the fruit's
color property is strictly equal to Yellow then console.log our array of yellow fruits
and there's two bananas and pineapples they color are both yellow let's create a new array of any fruits that are low
in calories where the calories are below 100 const low cal fruits take AR array of fruits use the built-in filter method
for every fruit Arrow check the calories of each fruit is it less than 100 if it is put
it within this new array and here we are we have three fruits that are low in
calories Apple orange pineapple the calories are 95 45 37 they're all less than
100 let's find any high calorie fruits change our rate to be high Cal fruits where the calories of each fruit
is greater than or equal to 100 console.log AR array of high Cal fruits there are
two banana and coconuts the calories are 105 and 159 let's use the reduce method now I'll
admit this is going to be a little tricky but I'll try my best to walk you through it the reduce method will return
a single value in this case an object one of these objects let's return the object with the greatest amount of
calories we'll store that within a constant const Max fruit equals take array of fruits
use the reduce method there's going to be two parameters an
accumulator which keeps track of the greatest value during each iteration and the next element but I think we should
rename these let's rename our accumulator as Max it's going to be the current record holder of the object with
the greatest amount of calories element will be fruit meaning the next fruit here are the two parameters
Arrow what are we going to check is our fruit the next fruit in line are the calories
greater than our current record holders calories max. calories just for readability I'm going
to put this on a new line we're going to use the trary operator is this true does the next
fruit have more calories than our record holder if it does will return our fruit meaning the next fruit colon meaning
otherwise return the max again let's see if this works let's console.log our fruit with the maximum
amount of calories which is our coconut with 159 calories if you just need the calories you would type dot calories
that will just give you the calories but in this case we're returning an entire object object let's find the fruit with
the least amount of calories let's copy our code paste it and make a few
changes Min fruit change Max to be Min the condition will be is the
calories of the next fruit less than the calories of the minimum record holder then console.log our Min fruit
which is our pineapple with 37 calories all right everybody so those are a few ways in which you can work
with an array of objects there's a lot you can do with them you can map you can filter you can reduce you can splice you
can pop you can push all sorts of things and well that is an example of an array of objects in
JavaScript yo so uh what's up today I'm going to be talking about about the sort method in JavaScript the sort method is
used to sort elements of an array in place however with the sort method we sort elements as strings in
lexicographic order not alphabetical if I could summarize what lexicographic means it means alphabet Plus numbers
plus symbols as strings let me give you an example with just alphabetical characters I have an array of fruits to
sort this array I can take the array name fruits use the built-in sort method then
console.log my array of fruits let me expand this and here's my array all sorted when sorting we treat any
elements as strings what if my array were numbers I'll add the numbers 1 through 10 in a somewhat random
order let's change our array to be numbers numbers. sort con cons. log numbers here's the result we have one
then 10 then the rest seem to be in order we're not sorting this array numerically we're sorting this array
lexicographically we're treating each of these numbers as strings that's why we have one then 10 10 isn't at the end
where we expect it would be there's a couple extra steps we need to do involving sorting
numbers inside of the sort method we have to write a custom comparison function this is normally a call back
but you can write a function expression or even better yet an arrow function we'll write an arrow function in this
case let me zoom in with an arrow function we first need parameters we'll have parameters A and B
we'll examine two contiguous elements 1 then 10 10 then two 2 then 9 9 and three so on and so forth then we need an
arrow then we'll write a minus B our function a minus B will return either a negative zero or positive value
depending on what values we're examining the sort method will sort those values into place depending on what the value
returned is our array should be sorted you can see that 10 is at the end instead of right after one for reverse
order you could say B minus a now we're starting with 10 and ending with one
you can even sort objects by a given property let's go over that example we will create an array of
people const people equals this will be an array will include four objects all comma
separated the first will have a name property of SpongeBob age 30 and a GPA
GPA 3.0 I'm going to zoom out for the next object just going to put that on a new
line let's copy all these properties change name to be Patrick age will be 37 GPA
1.5 again for the next object we will have Squidward age
51 GPA 2.5 then lastly we'll have Sandy name
Sandy let's make Sandy 27 GPA of course it's going to be a 4.0 I would like to sort this array of
objects by each person's age we'll take our array of objects that's stored within
people use the built-in sort method use our Arrow function a comma B
Arrow we'll take parameter a that's person one do access their age property minus parameter B access their age
property and that's all you got to do now let's console.log R
people there we are we have Sandy who's the youngest then SpongeBob Patrick
Squidward for reverse order you'll just change a to be B and B to be a Squidward Patrick SpongeBob Sandy or
we can sort by a different property let's do GPA this time a. GPA b.
GPA we have Patrick with the lowest GPA followed by Squidward SpongeBob Sandy
then reverse order would be b. GPA minus a. GPA Sandy SpongeBob Squidward Patrick
let's try sorting by the name property and see what happens a.name minus b.n
name we have SpongeBob Patrick Squidward Sandy but that doesn't seem to make sense these aren't in alphabetical order
if you need to sort by a property that contains a string within an object there's a different
formula we will take a.name do use the buil-in local compare
method compare to b. name this method will examine two strings for lexicographic
order now these are all arranged lexicographically starting with Patrick then Sandy
SpongeBob Squidward for reverse lexicographic order we would take b.n name. local compare then examine
a.name I've just now realized that there's a lot of SpongeBob characters whose first name starts with an S like
we have three right here Squidward SpongeBob Sandy Patrick all right everybody so that is the sort method
it's used to sort elements of an array in place it sorts elements as strings in lexicographic order not alphabetical and
well everybody that is the sort method in JavaScript hey everybody in today's
video I'm going to show you how we can Shuffle the elements of an array using JavaScript this is an optional video you
might find this topic helpful if you're interested in making a game using JavaScript or any sort of application
where you need some Randomness in this example we'll create a deck of cards our deck of cards will be an array we have
an a for Ace the numbers 2 through 10 let me finish typing those in J for
Jack Q for Queen k for King I'm not going to include any suits for these cards such as Ace of Hearts Ace of clubs
that might be overkill for this example one method you might see floating around online to shuffle the elements of an
array is to use the sort method then pass in an arrow function where you take math. randomus 0.5 I would not recommend
using this method just because the results of this method aren't perfectly uniform let me console.log cards this
array appears shuffled but it's not that uniform but not only that the larger the array becomes this method becomes
increasingly more inefficient I would not recommend using the sort method to shuffle an array instead I would
recommend using the fer Yates algorithm we'll create a dedicated function for this so we will Define a function to
shuffle there will be one parameter and a array then to invoke this function we'll
type the function name pass in our array of cards so what do we want to do exactly
we're first going to Loop through the elements of this array we'll start at the end and work our way towards the
beginning we'll use a for Loop to decrement So within our Shuffle function we'll create a for Loop we will declare
index of I let I equal R array do length then minus one that's the first statement our array has 13 elements but
the last index is 12 because array start with zero if the array's length is 13 we need to subtract 1 to get 12 which would
give us the ending index of 12 we'll continue this loop as long as I is greater than
zero then iusus to decrement now we have to generate a random number between the end and the beginning somewhere within
this range we'll create const random random will store a random number take math. random
method times I our index + one we'll need to round this number we're now going to
enclose this equation with math. floor to round down math. floor and enclose this equation all right during the first
iteration of this Loop we should generate a random number between the end and the beginning we'll swap our king
with a random element within this array so to swap two elements of this array we can use destructuring in this context to
use destructuring we'll take our original position array at index of I during our first iteration that will be
the king we'll swap our King with our array at a random index the one that will be randomly
generated equals our array at index IND of random comma array at index of I then to finish using destructuring we
need to enclose both sides of this equation with an array there and that will swap two
elements of your array now if I run this program this will Shuffle the elements of my array I
would recommend using a dedicated Shuffle function because in a game it's likely you're going to shuffle something
more than once throughout that game like I said this isn't a necessary topic to continue on with the series but if
you're ever interested in making a game using JavaScript or need some element of Randomness well then this function would
work great and that is how to shuffle the elements of an array using JavaScript what's up everybody so in
today's video I'm going to explain date objects in JavaScript date objects are objects that contain values that
represent dates and times these date objects can be changed and formatted to suit our needs here's an example
we will create a date object that contains the current date and time to do so let's create a constant named date
date will be an object we will call the date Constructor with the new keyword date then pass in no arguments for the
current date and time so I'm going to console.log my date object which gives me my current date and time as of right
now I'm filming this video on a Thursday November 9th the year 2020 23 at about 7: in the morning so depending on when
you're watching this video the date and time is going to be different if you would like to create your own custom
date and time object you'll have to pass in some arguments you can follow this order for the date Constructor the first
argument corresponds to a year then month day hour minute second and milliseconds even so for the year let's
say 2024 the month zero corresponds to January one is February then that means
a month of 11 is December let's say January so that will be zero for the day one for the 1 for the hour uh 2 2 in the
morning this is in Military Time by the way for the minute 3 minutes after the hour for the seconds 4 seconds after the
minute we can even add milliseconds if we would like so for the milliseconds let's say five and here's my new date
object Monday January 1st 2024 about 2 in the morning passing in a string representation of time to the date
Constructor is also valid let's say the year is 2024 January 2nd for the time you're
going to type t for time 12 noon then add Z for UTC time and there's my new date again Tuesday
January 2nd 2024 6: in the morning another format you can use is within the date Constructor pass in a given amount
of time in milliseconds since epic if I could describe epic I would describe it as when the date your computer thinks
time began if you were to pass in zero to the date Constructor you'll be given a date and time around December 31st
1969 So within the date Constructor you can pass in a given amount of milliseconds since this date so if I was
to pass in 1.7 billion milliseconds what I'm telling the day Constructor is
give me the date and time that's 1.7 billion milliseconds since that epic date when I pass in 1.7 billion
milliseconds the date that I'm given is Tuesday November 14th 2023 about 400 p.m. passing in milliseconds would be
good for some sort of timer now let's use the current date and time I will pass in no arguments you can extract
individual values from a date object I would like the year const year equals take our date object I will use the get
full year method to get the year then I will console.log the year and this will be a
number 2023 let's get the month const month equals our date object
use the built-in get month method then I will console without log the month currently for me it's November not
October so remember January is zero December is 11 let's get the day const day equals date get date not day if you
get the day that will give you the day of the week like Sunday Monday Tuesday that sort of thing let's
console.log the day so for me it's the the 9th let's get the hour const hour equals date get
hours plural console.log the hour for me it's 7 in
the morning let's get minutes const minutes equals get
minutes console.log the minutes it is 7:45 in the morning get
seconds get seconds console.log the seconds so
745 21 seconds after the minute now if you need the day of the week here's what you can do const day of week equal
equals date get day that will give you the day of the week
console.log day of week for me that is for Sunday is zero Monday is one so that means it is Thursday now with the date
object you can even set the date with a method let's console.log the
date I'm GNA set the Year date set full year I will set the year to be 2024 yep Saturday November 9th
2024 let's set the month set month I will set the month to be January
so I will pass in zero Tuesday January 9th let's set the day that would be with set date not day
I will set it to be the first January jary 1st the hours with set
hours let's go with two for two in the morning set minutes 3 minutes past the
hour set seconds 4 seconds past the minute you can even compare dates as well let's
create two date objects const date one equals a new date I'll pass in a string representation of a date we won't
include the time though for the year let's say 2023 December that would be 12 31st New
Year's Eve basically and for date two let's say date two is New Year's Day
2024 January 1st using an if statement let's compare to see if
date 2 is greater than date 1 if it is then let's console.log happy New
Year so date two is greater than date one we'll print happy New Year let's change date two to be
2023 December 30th well nothing happens then but that's to be
expected all right everybody so those are date objects they're objects that contain values that represent dates and
times these date objects can be changed and formatted to suit our needs and well everybody those are date objects in
JavaScript hey what's going on everybody so in today's video I got to explain closures in JavaScript a closure is a
function defined inside of another function the inner function has access to the variables and scope of the outer
function by using closures they allow for private variables and state maintenance JS libraries and Frameworks
such as react View and angular use closures all of the time you'll see closures fairly often with
function-based components you have functions inside of other functions let me give you a very basic example we'll
have an outer function named outer within the outer function we'll have a function named inner
the inner function has access to everything within the outer function this scope if I was to create a variable
let message equal the word hello within my inner function I can use this message
variable console.log my message now if I invoke the outer function nothing appears to
happen when we call the outer function we're now within the scope but then what there's one of a few things we could do
if I would like to call the inner function from within the outer function I would need to call it somewhere here
let's call the inner function at the end there we go we have displayed the word hello everything within the outer
function is part of a closure we have a function defined inside of a function this inner function has access to
everything within that scope includ cluding this message variable one benefit of using closures is that any
variables are considered private outside of the outer function I will attempt to update our message message equals
goodbye now this doesn't work as you can see this message variable is in a different scope it's kind of like it's
in another dimension what we've done here is we have created a different message variable in a different scope
outside of the outer scope I have no way of accessing the message M variable so that's one of the benefits of closures
you can encapsulate variables and make them private let me give you another example a closure can maintain the state
of a variable we'll create a counter program so I'm going to create a function to
increment within the increment function I will set a count variable equal to 0o I will increment our count by one then
console.log I'll use a template string count increased to I'll add a
placeholder we'll display our count variable now anytime I attempt to call the increment function it'll increase
our count by one but if I was to execute this function again well we're redeclaring this variable of count we're
resetting it every time we call this function I can't get the count to go past one because we we keep on resetting
it but by using a closure we can have state maintenance we can maintain the state of this variable and remember
where this variable was previously I mean I could take this variable and declare it outside of the function but
then we don't have any security for that variable I will set the count equal to a million we're maintaining the state of
that variable but it's not private anybody and anything can access and change that variable a closure maintains
the state of a variable and makes it private what we'll do is enclose all of this code within another
function we'll create a function to create a counter how do we access the scope
within the create counter function here's another possibility we will return an object we
will need a set of curly braces our object will have a property of increment and its Associated value
will be a reference to increment there is a shorthand version of this you can just use the function name as a property
we're returning an object with the method of increment so now I'm going to create an
object named counter counter equals invoke the create counter function this will return an object that
has an increment method so I'm going to take our counter object use the increment
method count increase to one not only do we have an increment method we have a count variable as well you could say
that what we've done with this outer function it's very similar to creating a class we can use classes to instantiate
objects in this case we used a function to return an object so if I was to take my counter and increment it again our
closure should maintain the state of that variable count count increase to two it's not resetting every time we
call the method count increase to three let's attempt to access our count variable counter. count equals
z then I will console.log our count reference ER count is not
defined let's attempt to display our count variable
console.log take our counter object access the account variable it is undefined we don't know
what it is it's hidden your closure can have more than one function so what we'll do is create a
get count function we'll use the get count function to return our count if we need access to it
function get count we will return our count variable within the return statement
we're returning an object we will add another property of a reference to the get count
function so now within our counter we have a method to get the count variable let's
console.log I'll use a template string the Curve current count is I'll add a placeholder take our counter object use
the get count method the current count is three if I was to increment our counter again well that increased to
four all right last example we're going to create a closure for a game where we keep track of points
we have a score let score equal Z we'll Define the function function increase
score we'll have one parameter points in order to score some points we have to pass in some points as an
argument take our score plus equals R Points then let's console.log I'll use a template string
plus add a placeholder R Points then I'll add pts meaning points it's
shortened let's create a function for decrease score change increase to
decrease score minus equals points minus points and then let's get our
score function get score return the
score if I need to increase the score I will invoke The increased score function but I have to pass in points we scored
five points let's do this again we scored six points let's decrease the
score I will subtract three points minus three points let's get the current
score console. log I'll use a template string the final
score is add a placeholder get score the final score is eight I'm going
to add points after that eight points all right problem with this is that we can take our score and set it to
anything you scored like a kajillion points so for some security let's enclose all of this code within a
closure I'll create an outer function function create game this will return an
object let's cut all of this code paste it within the outer function of create
game and then at the end we will return an object that has references to these functions return an object we need curly
braces for that a reference to increase score decrease
score and get score so now I will use the create game function
to return an object const game game will be our object we will invoke the create game
function and return an object so now if I want to increase the score decrease it or get the score I
have to use the methods of this object game. increase score game. decrease score and game.get
score we have five points six points minus three points and then we have the final score of eight points well
everybody those are closures think of them as a function defined inside of another function the inner function has
access to the variables and scope of the outer function these are used frequently with JS libraries and Frameworks such as
react View and angular especially when you work with function based components and well everybody those are closures in
JavaScript hey what's going on people so in today's video I'm going to explain the set timeout function in JavaScript
the set timeout function allows you to schedule the execution of a function after an amount of time in milliseconds
the times are approximate they vary based on the workload of your JavaScript runtime environment I wouldn't recommend
using set timeout for anything precise like a stopwatch it's an approximation to use the set timeout function you pass
in a call back to a function and a delay in milliseconds here's an example I will create a function to say
hello all we're going to do is window. alert the word hello I will use the set timeout
function pass in a call back we'll pass in a call back to say hello then execute it after 3,000
milliseconds so 3 seconds let's see if this works 1 2 3 hello an anonymous function
works too so instead of a call back we'll use an anonymous function function parenthesis curly
braces window. alert the word
hello 1 1000 2 1000 3 1000 hello or even an arrow function we have parameters Arrow what are we going to do window.
alert the word hello 1 1,000 2 1,000 3 1,000 hello you can use the clear timeout function to
cancel a timeout before it triggers but we have to pass in a time out ID so what we'll do with this set timeout function
is assign it to an ID stored within a variable or constant const time out
ID equals our set timeout function that'll display the word hello I can clear this time out with the clear time
out function but I have to pass in that ID as an argument immediately after calling the
set timeout function we will cancel it let's try it 1 1000 2 1000 3 1000 yeah nothing's happening we
canceled it all right what we'll do this time is create a button using HTML when we click on the button we'll set a
timeout to display the word hello so let's clear all of this go to our
HTML file we'll create a button the button will have text of start and I'm going to zoom
in I will set the onclick attribute to equal a function we will start a timer then add a set of
parentheses when we click on the button do this function So within our Javascript file we will create a start
timer function function start timer we will set time
out I'll use an arrow function let's window. alert the word we will display
the word hello after 3,000 milliseconds all right so nothing's going to happen until I click the button
I'm going to click it now 1 1,000 2 1,000 3 1000 hello let's create a second button to
clear the timeout if we need to stop it let's copy our first button paste it change the text of the button to be
clear we will clear the timeout but we'll need another function clear
timer so there's our second button we'll need a timeout ID so outside of this function I will declare a variable
of let timeout ID when we start our timer we will
assign the set timeout function an ID of timeout ID then we can stop it using this
ID we will create a function to clear the timer we're going to use the clear
timeout function clear time out we need to pass out a timeout ID as an argument which we will do and then
just to be sure that everything works within both these functions let's console.log something let's say the word
started within our start timer and within our clear timer let's display the word cleared just so we know that these
functions were called so I'm going to save everything I'm going to start the timer but not
clear it let's start now 1 1,00 21000 3 1,000 hello let's go to our console and it says that we started well
starter I clearly can't spell today started we're going to start then cancel start 1 1,000 to 1,000
clear and nothing happened let's go to our console and expect console we started set timeout and then we cleared
it all right everybody that is the set timeout function it's a function in JavaScript that allows you to schedule
the execution of a function after an amount of time in milliseconds execution time may vary based on the workload of
the JavaScript runtime environment and well everybody that is the set timeout function in
JavaScript hey what's going on people so in today's video we're going to create a digital clock using JavaScript HTML and
CSS so let's get started the HTML for this project is going to be very minimal I will create a develop the ID of the
development will be clock Dash container within this development we'll have a nested development with an ID of clock
we have a clock within a clock container as a placeholder temporarily the text on the clock will be 0 0 colon 0 0 colon 0
0 000000000000 0 and I'm just going to zoom in
temporarily and that is all the HTML that we need let's head to our CSS stylesheet let's begin with the
body I will set all margin to be zero originally let's select our clock container ID clock container
I'll use flex box for the clock container display Flex I will justify content in the
center justify content Center if you would also like to vertically align you'll need to add the
following two lines of code I will align items Center this CSS property will vertically
align any elements but the clock container itself is kind of small for example I'll add a border of two pixel
solid the elements within the clock container are aligned both horizontally and vertically but the container itself
is kind of small to vertically align this element within the window itself we'll have to increase the height of the
clock container I will add height of 100 VH for the viewport height and we can remove the
Border yep the clock is now within the middle of the container both horizontally and vertically but if you
prefer it to be at the top you can eliminate these last two lines it's up to you let's style the clock itself we
are selecting the ID of clock I will change the font family to be
monospace this is the normal size when I'm zoomed in to 100% I will set the font size to be
6.5 RM then set the font weight to be bold and text align
Center if you would like a background image for the body of your document I just so happen to have one right here
it's a picture of Central Park in New York this is optional but if you would like to include a background image of
this project within your CSS stylesheet you'll add the following CSS properties I will set the background image property
to be a URL so what is the name of that image I'm going to copy the name of it and
paste it within this URL function I'll set the background position to be the center right now
we're seeing the top left of the image instead of the center
background Position will be Center if you're using a small image your image might be repeating itself to take up all
the available space to prevent that you can set the background repeat
property to be no repeat mine already wasn't repeating though but yours might be then we'll set
the background size to cover by adding this property this image will
cover the entire window and maintain its aspect ratio if you do have additional content besides this clock you can keep
the background in place when you scroll down by adding this property
background attachment to be fixed this property isn't going to be
apparent because we don't have a scroll bar but if you did have a scroll bar the background will stay in place at least
let's head back to our clock element I will change the color the font color to be
white if you would like a background blur effect you'll add this property we'll set the backdrop filter property
to be a blur function the greater the number the more blur effect you're going to have so this
is five pixels if I were to increase this to 50 well there's a lot of blur then I'll
set my blur to be five I would just like a little bit as if we're looking through glass I'll increase the width to be 100%
to take up 100% of the width of the web browser width 100% to give this glass look a foggy
appearance we can add a background color that's slightly gray background-
color let's select gray but I like using hsl values so for the lightness I'll set it to be
100% but I'm going to lower the alpha down to like 10% now the background has a foggy glass
appearance if you were to increase the amount of alpha that'll increase the
lightness I'll keep mine as 10% 0.1 for the alpha all right now we just need to get
this clock to run so let's save everything go to our JavaScript file we will create a function to update
our clock immediately when we begin this program we will update our clock once
immediately now we need to get the current time let's declare a constant of now what is the time right now this will
be a new date object to get the hour we will say const hours equals use the
builtin get hours method then let's do this with minutes con minutes equals now. get minutes
method and seconds const seconds equals now. get seconds I'm going to change the text
content of the clock to be a time string it will be a template string how do we want to arrange our
numbers const time string equals a template string first We'll add a placeholder for
our hours colon minutes
colon seconds then we will select the ID of clock document. getet element by ID the
ID that we're getting is our clock change the text content to equal our time string when we save the time on
the clock should update currently for me it's 8:00 for each of these placeholders for hours minutes and seconds I would
like each to take up two digits We'll add some zeros for padding for example this time will be
08006 there's a built-in string method for that so with hours minutes and seconds we will convert these to
Strings we'll use method chaining then add to string do this for hours minutes and
seconds with strings there's a pad start method for the first two characters pad them with a
zero let's copy this method and paste it for minutes and seconds now when I save an up the time we have zero padding 08
01 54 in this case to get this clock to update every second will follow update clock with the set interval function set
interval works like set timeout except it will call a function repeatedly not just once but we need a call back the
call back will be update clock call this function after every 1,000 milliseconds and now our our clock should
run currently this clock is in military time although I'm recording this at 8 in the morning if you would like this clock
to be a 12-hour clock then add am or p.m here's the following changes we're going to make we'll declare hours with let
instead of const so we can change it and reassign it we'll create a new constant of
meridium 400 a.m. or p.m. this will equal hours is ours greater than or equal to 12 we'll use
the erary operator to check this if ours is greater than or equal to 12 meridium will be PM otherwise it will be
am then after our meridium we'll reassign hours hours equals
hours modulus modulus gives you the remainder of any division ours modulus 12 if this is zero we'll use the or
logical operator or 12 after seconds We'll add a placeholder for our meridium currently we lost our padding
for the hours so we're going to cut this part of our code to convert ours to a string and Pad
it we'll take ours equals hours to reassign it follow hours with converting it to a string using the two string
method and Pad it before displaying it all right and that has appeared to work all right everybody so that is a
digital clock program you can make using HTML CSS and JavaScript hey what's going on everybody
in today's video I'm going to show you how we can create a stopwatch program using JavaScript HTML and CSS so sit
back relax and enjoy the show all right let's get started everybody we will create an H1 heading with textt of
stopwatch and I will give this H1 element a unique ID of my H1 then we'll create a container for our
stopwatch this will be a div element this div element will have an ID of container to contain everything our
container is going to have two sections two developments the First Development is
going to be for our display ID display I'll give this development some initial text as a placeholder we'll have
zeros for hours minutes seconds and milliseconds then our next development will have an ID of controls for all the
control buttons within this development of controls we'll create three buttons the first button will be start
the ID of this button will will be start button BTN short for button then I will set the onclick event handler equal to a
JavaScript function we will eventually create a start function we still need to Define it let's copy this button paste
it twice the second button will be for stop the ID will be stop button the onclick
attribute will be for a stop function the text on the button will be stop and then we have a reset
button the ID is reset button the onclick attribute will be for a reset function the text on the button
will be reset all right and that is all the HTML that we need let's go to our CSS
stylesheet I will first select the body of our document we'll use flexbox to display everything because I like
flexbox display Flex the flex Direction will be a column then I will align items
Center I'll set the background color of this application
background-color pick a color again I like using hsl values I'll set the lightness to
90% our container is going to be a lighter color we will select the ID of my H1 that's going to be the heading I
will set the font size to be 4 RM the font
family I will pick Ariel with a backup of s's serif for the font color I will set the
color property to be pick a color I'll pick black but set the lightness to
25% all right now we are going to select the container that contains everything besides the
heading this area we will select the ID of container I will use flex box within the
container display Flex the flex direction will be a column and aligned item
Center let's add a border a border around the container 5 pixel solid and I will round the corners
border radius let's do 50 pixels and I'll add a little bit of
padding padding 30 pixels and I will set the background color to be white background
color white we'll work on the time display next select the ID of
display I will set the font size to be 5 RM for the font
family I'm going to set it to be monospace and the font weight I will set to be
bold I'll change the color I'll set the lightness to 30% I'll give a text Shadow to the
display so it looks like it's somewhat 3D like it's popping out so text Shadow two pixels and two pixels for the
vertical and horizontal offset and a blur of two pixels now for the color I'm going to
lower the alpha to 75% or so that's not bad bad then I'll add a
little bit of margin to the bottom margin bottom 25 pixels now we have to style the buttons
we will select the ID of controls but I would like the button elements within the controls after selecting the ID of
controls select any buttons within that element we'll increase the font size of the buttons font size 1.5 RM I will set
the font weight of the buttons to be bold I'll add a little bit of padding 10 pixels by 20
pixels I'll add some margin around the buttons 5 pixels I'll set a minimum width of the
buttons to be 125 pixels let me scroll down I'll remove the border border
none set the Border radius of the buttons to be 10 pixels change our cursor to be a pointer
when we hover over the buttons let's see if that works yes it does then set the font color of the
buttons to be white now let's color the start button we will select the ID of start
button set the background color pick a color I'll start with something green
pick whichever color you would like I'll pick this shade of green here are the values when we hover over the
start button we will access the hover sudo class of our start button I'll decrease the lightness by
10% let's copy the markup that we have for the start button paste it twice we'll add color to the stop
button and the reset button I'll set the stop button to be red here are the hsl values that I
picked when I hover over this button I'll set the lightness to be 10% darker for the reset button I'll set
that to be blue when we hover our cursor over the reset button I will set the lightness to
be 10% darker not bad for all of the buttons I'm going to add a transition
effect transition select the background color we will create an ease
transition after 0.5 seconds we will ease so when you hover your cursor over the buttons there's going to be a slow
transition when we hover okay and that is all the CSS that we need we will now go to the Javascript
file to add some functionality let's declare all the variables we'll need we'll get the ID of the display and
store a reference to it const display equals document. getet element by ID the ID that I'm selecting is
display this ID we will create a timer let timer equals
null timer is going to hold the ID of set interval so we can keep track of it and stop it if we need to then we need a
start time let start time equal zero let elapsed time equal
zero let is running this will be a Boolean which I will set to be false if the stopwatch is currently
running we will flip this to be true and flip it to be false to stop it what are the functions that we need we have a
start stop and reset function function start function
stop function reset We'll add one more function of update to update the
display function update we'll begin with the start method we'll enclose everything within our
function within an if statement we need to check to see if our stopwatch isn't running if our stopwatch isn't currently
running if not running then start the stopwatch we need to set the start time the start time equals we will get the
current date date do now minus the elapse time which will be zero initially so just to demonstrate what
the start time is I'm going to console.log my start time so the start time is going to be in
milliseconds since epic epic basically speaking is when your computer thinks time
began we will set our timer equal to the set interval
function we will call the update function every 10 milliseconds so if I was to display my
timer console.log timer this is what it is our timer stores a unique ID to work
with this function if we ever need to stop it
we'll take the Boolean variable of is running set it to be true because our stopwatch is not running now we need to
go to the update function to actually get it working we need to get the current
time const current time equals access our date use the now method what is the date
right now we will calculate the elapse time equals the current time minus our start
time whatever that was when we initially pressed the start button so the current time minus our
original start time gives us the elapse time and this is going to be in milliseconds we need to convert the
elapse time into a readable format using hours minutes seconds and milliseconds we'll begin with
hours let hours equals take our lapse time divided by to convert milliseconds to hours we can
follow this formula elapse time divided by 1,000 milliseconds * 60 seconds times 60
minutes we don't want any decimal portions with our hours we will enclose all of this with the floor method of
math now we're going to do something similar with minutes let minutes equals take our lapse
time we need to convert milliseconds to minutes divided by 1,000 milliseconds in a
second times 60 seconds in a minute then modulus 60 modulus gives you the remainder of
any division we don't want our minutes display to hit 60 or go above 60 once we hit 60 it'll reset back to zero enclose
this formula with math. floor to round it math. floor okay then we have to take care of
seconds let seconds equals take our lapse time divided 1,000 to convert
milliseconds to seconds modulus 60 and close all of this with math.
floor to round it now for milliseconds let
milliseconds equals take the elapse time which is already in milliseconds modulus 1000 milliseconds
is normally four digits we're going to divide it by 10 we only want the first two
digits divided by 10 en close all of this with math. floor math.
floor then let's change the display we'll access our
display access the text content of the display set it equal to a template string if you would like to display the
hours it's optional we will add a placeholder for hours colon placeholder minutes colon placeholder seconds if you
would like to display the milliseconds we can add a placeholder for that colon placeholder
milliseconds let's see what we have so far I'm going to hit the start button and here's what we
got so the stopwatch is running but we should add some zeros for padding so I'm going to refresh to stop
it we'll convert hours minutes seconds and milliseconds into a string then add some padding of zeros to it if the
number is only one digit not two we will convert our hours minutes seconds and milliseconds into a string before
displaying it so let's take hours equals hours I will typ cast it as a string follow this with the pad start
method for the first two digits at a zero let's do this for minutes seconds and
milliseconds minutes seconds and
milliseconds we should have some zeros for padding to make each display two digits and that does appear to work
nice now we just need to get the stopwatch to actually stop right now there's no
functionality going to our stop function we need to check to see if our program is running is this variable is running
true if is running if that that's true then stop the stopwatch we will use the clear interval
function we need to pass in that unique ID for the timer this will stop the stopwatch from
running then we will calculate the elapse time elapsed time equals the date right now date. now method minus the
original start time then set is running equal to false because the stopwatch is
stopped it's not running anymore now we can start the stopwatch and we can stop it we can
start it and we can stop it the last thing we need to do is reset the stopwatch we can really just copy
everything that we have when we initially assign these variables we need to clear the timer
clear interval p pass in our variable timer that contains the ID of the set interval
function the start time will be zero the elapse time will be zero is running will be
false change the text content equal to all zeros this is for the hours minutes
seconds and milliseconds all right let's see if everything works just fine we can
start we can stop we can start we can stop we can reset we can start and we can stop all
right everybody so that is how you can create a stopwatch program using JavaScript HTML and
CSS hey what's going on everybody so today I'm going to explain es6 modules in JavaScript a module is an external
file that contains reusable code that can be imported into other JavaScript files let's say you write a really
difficult program well any part of that program you can import into a different application if you don't feel like
rewriting it modules can contain variables classes functions and more es6 modules were introduced as part of the
ecmascript 2015 update using modules we can create some reusable code that can be used in different programs different
JavaScript files so what we'll do in this example we will create a new
file I'll create a module for some math utility functions this file will be math u.j it's a separate Javascript
file from our index file we will import this module mathu till. JS but in order to do so within our HTML file we have to
set the type attribute equal to module we'll now treat our index file as
a module we can Import and Export other modules freely but we have to be sure to include this attribute and set it equal
to module So within our math util module we can write some reusable code for other
programs so let's define what Pi is Pi equal 3.14159 we'll create a function to get
circumference you have to pass in a radius though that's going to be the parameter function get
circumference we need a radius we will return 2 * pi time
radius then we'll create a function to get area get area we still need a
radius we will turn Pi * radius * radius then get volume to get the volume of a
sphere function get volume again we need a radius we will
return 4 * < * radius * radius I can reuse these variables and functions for any JavaScript program
that I have I can import them in order to do so though we need to be sure that we prefix each variable function or
class or anything else with the export keyword so that we can import it elsewhere so let's be sure we do
that all right be sure to save everything we can close out of this module then from our index CSS file I
will import then we're going to use object destructuring we need a set of curly
braces from the location of that module so these files are right next to each other
relatively speaking the right next to each other I would need slash the name of that file math util and this is a
Javascript file now anything I would like to import I'll place within the set of curly
braces we're going to be using object destructuring from this JavaScript module I would like Pi comma separate
each entity then I would like get circumference get area get volume I can now use these variables and
functions as if they were already part of my Javascript file for example I'm going to
console.log Pi and Pi does have a value because we imported it let's get the circumference but we do need to pass in
a radius this is a function that we have imported from that mathutils module I will store
the result within a variable const circumference equals we'll invoke the get circumference
function from that module I'll pass in 10 then we're going to display the circumference I'll use console.
log I'll use a template string include a placeholder display the circumference plus a unit of measurement like
cenm 62.83 one8 CM this isn't necessary but I'm going to round this number to two decimal places using the two fixed
method of numbers let's round to two decimal places let's create an area variable const area equals get area I'll
pass in 10 for the radius let's copy this line and paste it because I'm lazy let's display our area
variable with cm cubed 31416 cenm cubed then we'll create a
volume variable const volume equals get volume I will pass in 10 and then we will display the
volume volume cm cubed and our volume if we pass in a radius of 10 would be 1,256 64 cm cubed all right everybody so
those are modules they external files that contain reusable code that can be imported into other JavaScript files you
can write variables classes functions and more that can be reused in other programs you just have to be sure to
import them and well everybody those are es6 modules in JavaScript yo what's going on on people
so in today's video I got to explain what asynchronous code is in JavaScript synchronous is code that executes line
by line consecutively in a sequential manner synchronous code waits for an operation to complete for example if I
were to use console.log Let's Pretend We're performing some task it doesn't matter
what the task is we will pretend that task one is complete then we'll move on to task two then task three all this
code is synchronous we're executing this code line by line we can't move on to task two until we
complete task one there is an order of events that we need to follow it's code that waits for an operation to complete
now on the other hand asynchronous code allows multiple operations to be performed concurrently without waiting
asynchronous code doesn't block the execution flow and allows the program to continue imagine that asynchronous code
is kind of like a time traveler a time traveler can move out of the flow of time but the rest of the world continues
time resumes normally asynchronous code doesn't block the execution flow time moves on with or without it asynchronous
code is typically found with input output operations Network requests and fetching data anything that could take
an indeterminate amount of time so for example I will use the set timeout function after after 3 seconds I will
execute a function let's console.log let's say task one we'll
change these three lines to be task 2 task three task 4 I will finish Task 1 after 3,000 milliseconds now check this
out we've already completed task 2 3 and four but task one finished last that's because set timeout is one of many
asynchronous functions s the rest of the program isn't going to wait around for it to complete it runs concurrently with
the rest of my code that's why task one was completed at the end and not at the beginning there's different ways to
handle a synchronous code we're already familiar with callbacks but there's also promises as well as a sync and a wait we
still need to discuss these topics in the future but we're already familiar with callbacks if it's crucial that task
2 through 4 finishes after task one we can use a callback we don't necessarily know how long this
asynchronous function is going to take what we could do in this example is create a function function Funk one
meaning function one I will execute this code within function
one then we will accept a callback as an argument then we'll have function Funk 2 to do some synchronous code
function two will have tasks 2 through 4 after task one is complete I will invoke my call back to function two so
with an arrow function I have more than one line of code I need to add a set of curly
braces after task one I will invoke that call back so then if I call function
one I have to pass a call back to function two so Now function one is
asynchronous but I need this synchronous code to execute after task one is complete and now that should
work one 2 3 there it is we have task one which is asynchronous followed by task two task three and task four so by
using callbacks that's one way in which we can handle asynchronous code but we still need to discuss promises a
sync and a wait which are future topics all right everybody so that is what a synchronous code is synchronous code
executes line by line consecutively in a sequential manner asynchronous code allows multiple operations to be
performed concurrently without waiting asynchronous code doesn't block the execution flow and allows the rest of
the program to continue asynchronous code is commonly found with input output operations Network requests and fetching
data usually anything that takes an indeterminate amount of time and well everybody that's what asynchronous code
is in JavaScript hey people so in today's video I'm going to explain error objects
in JavaScript and how to handle them an error is an object that is created to represent a problem that occurs errors
occur often usually when we accept user input or establish a connection it's an object that's created to represent a
problem so for example I am going to console.log the word hello and then afterwards I'm going to display a
message to indicate that we have reached the end of the program you have reached the end this runs as it should right
let's say I misspell log as leg well we encounter an uncaught type error there's many different types of Errors console.
leg is not a function type errors tend to happen when we try and access something within an object that doesn't
exist one big issue that we run into is that we prematurely exit the program it never finishes executing we have not
reached the end errors when they're uncaught interrupt the normal flow of our program another example of an error
would be a reference error I will console.log X but X isn't defined we have an uncaught reference error X is
not defined and again it interrupts our program we never reach the end errors can be generated for all sorts of issues
such as network issues promise rejection which we still need to talk about and security errors when we encounter a
problem when doing one of these things an error object will be generated and it interrupts our program there's a
solution though and that is to handle these errors when they occur we can do that with try catch and find blocks with
the tri block we can enclose any code that might potentially cause an error such as if we're trying to establish a
connection to something if that connection fails an error can occur if we don't handle it it's going to
interrupt our program so all of this code I will place within a tri block we will try all of this
code but we need a catch block too the catch block has one parameter it will catch an error
object then let's console.log the error object to see what it is so let's run this we have a
reference error a is not defined see now we are reaching the end of the program the program is not being interrupted we
have gracefully handled this error before it was uncaught but now it's caught for catching errors I wouldn't
recommend using console.log rather I would use console . error this will highlight any errors
that occur and still handle them it's good for debugging we can clearly see the error reference error X is not
defined and again it doesn't interrupt our program we still reach the end now optionally you can add a finally block
the finally block always executes regardless if an error comes up the finally block is usually used for
closing files closing connections or releasing resources usually when you open something or establish a connection
you need to close it afterwards you don't want to leave it open that's where the finally block comes in do any
cleanup at the end whether or not an error occurs so just to test this I'm going to
console.log this always executes I'm going to console.log X we have a reference error it is caught so
it doesn't interrupt anything we're still executing the finally block and we reach the end of our program if we don't
run into any errors I'm going to console.log hello there are no errors that occur we
don't end up catching anything this always executes the finally block and we reach the end of our program so any code
that is considered dangerous where it could cause an error you'll want to surround with a tri block and then catch
them in the future if you ever open any files or establish a connection you'll want to finally block two close those
connections but we haven't discussed that yet errors can also occur when accepting user input because we don't
know what the user is going to type in in a worst case scenario a user could type in a malicious script in this next
example I'm going to create a constant for a dividend and a advisor const dividend equals window.
prompt enter a dividend with division a dividend is the number that is being divided and we need
a diviser a divisor is the number we're dividing by enter a
divisor then I'm going to create a constant result result equals our dividend divided by our
diviser console.log the result
what is 1 / 2 0.5 now mathematically speaking we can't divide a number by 0 if you attempt to
do this in JavaScript I will divide 1 by zero you end up with infinity we can intentionally cause errors then handle
them with try catch and optionally finally blocks so this code is considered dangerous I'll place it
within a tri block we need to catch any
errors catch an error object if it occurs then console. error the error
object so just to test this instead of console. log I'll misspell log as leg I should probably add a message just
to confirm that we have reached the end you have reached the end 1 / 0
type error console. leg is not a function but we still reach the end our program isn't interrupted within a tri
Block in certain situations we can intentionally cause an error I'm going to use an if
statement if our divisor is equal to zero then I will throw a new error
object we're calling the error Constructor to constru conu a new error object within the Constructor we have
one argument we can pass in a message what is the error going to say you can't divide by
zero okay let's try this enter a dividend one enter divisor I'll type in zero then press
okay we have a caught error you can't divide by zero our program isn't interrupted we still reach the end let's
change console. Le back to log cuz I forgot to do that what if somebody attempts to type in something that's not
a number enter a dividend one enter a divisor I'll type in the word Pizza not a number you have reached the
end I would like to throw a new error when somebody doesn't type in a number what I can do is that with our prompt I
will typ cast it as a number if somebody enters in some non-numeric characters for either the
dividend or the diviser we will store within there not a number so let's check that with an if statement if is not a
number if our dividend is not a number or our divisor is not a number let's throw a new error throw new
error values must be a number I will divide one by the word Pizza error values must be a number we
still reach the end of our program with error objects you can even create your own in certain situations and then you
can handle them however you want all right everybody so those are error objects and how to handle them an error
is an object that is created to represent a problem that occurs they occur often with user input or
establishing some sort of connection to handle them you can use try catch and optionally finally blocks which are
mostly used for cleanup if there's any code that can cause an error place it within a tri block and catch any errors
that happen and well everybody that is how to handle errors in JavaScript hey what's going on everybody
in today's video we're going to create a calculator program using HTML CSS and JavaScript so let's get started all
right let's do this thing everybody we have a lot of buttons to create but we'll need a container I will create a
div element the div element will have an ID of calculator within the div element we'll
create an input element the input element will have an ID of
display to display the numbers that we type in I don't want somebody to enter in some text for the
display I would like this display to be readon I will add the read only property so we can't type in anything even though
I'm trying I will create a nested div element that has an ID of keys for all of the keys we need to add a lot of
buttons we'll begin with the first I will create a button element the text on the button will be plus I will set the
on click attribute of this button to be a JavaScript function we still need to Define this fun function eventually
we'll create a append to display function we have one argument to pass into this JavaScript function a
character of plus that's our first button let's copy this button and paste it 13 additional
times if I counted right okay the second button will be seven the character we're passing in is
seven followed by 8 9
minus 4 5
six asterisk for multiplication 1
2 3 forward slash for
division then zero and here are the new buttons I miscounted we need to add one
more a DOT for a decimal now we need an equals button we're going to arrange that a little
different let's create a button with the text of equals the onclick attribute of this
specific button is going to be calculate then we need a button to clear our
screen the text on this button will be capital c for clear the onclick attribute of this button is going to be
clear display and that is all the buttons we'll
need so let's save everything and let's go to our CSS stylesheet I'm going to zoom back to 100
% first let's style all these buttons I will select all buttons for each button I will set the
width to be 100 pixels the height to be 100 pixels so they're
even I would like rounded buttons I will set the Border radius property to be 50 pixels so they're
circles let's remove the border border none I'll change the background color of
the buttons background- color I'll use hsl values I'll set the lightness to be 30% so they're darker
for the text of the button I will set the color to be white for the font
size I will set that to be 3 RM set the font weight to be bold then when I hover my cursor over
one of the buttons I would like my cursor to be a pointer
cursor pointer now we have to arrange these buttons
properly let's select the ID of keys keys is a development that's containing all of the
buttons this element all of the buttons are within
to arrange these buttons in a grid we can set the display property to be a
grid for this calculator I would like four columns to do that I will set the grid template columns property to be
we'll use the repeat function of CSS I would like four columns then to arrange these buttons evenly you can use
one f r f FR stands for fractional unit one F FR indicates that each column should take up an even amount of space
so now we have Columns of four if I were to set this to three we would have Columns of three but I'm going to use
Columns of four because I would like all of the operators on the left hand side I'll set the Gap to be 10
pixels that is the gap between each of the rows then I'll add some padding of 25
pixels that's padding around the keys let's select the ID of calculator I'll add that to the top to
keep everything organized with our calculator I will select a font family of aiel with a
backup of s serif let's pick a background color for the
calculator I will select something darker I'll set the lightness to be 15% I'll round the corners of the
calculator border radius 15 pixels the corners of the calculator are smooth
now then I will set a Max width of the calculator to be 500 pixels if any elements overflow I will
set that to be hidden this is mostly for our display if we have a very long equation all right
next let's select the display right now it's kind of small we are selecting our ID of
display let's set the width to be 100% I'll add some padding of 20 pixels for the text of the display I
will set the font size to be 5 RM let's text a line
left I'll remove the border border none and I'll change the background color I'll just copy this property
because I'm lazy let's increase the lightness to 20% then we'll select the body of our
document I will remove all margin margin zero I would like the calculator to be
in the middle of my window right now it's in the top left corner if you would prefer it up here you can leave it as
is I will set the display to be Flex for Flex box
justify content in the center for a horizontal alignment M for vertical alignment we
can set align items to be Center but we do need to increase the height of the body of
the document so it's 100% I will set the height to be 100 VH for 100% of the viewport height that
should place the calculator in the middle of the body of our document both horizontally and vertically for the
background color I'm going to decrease the lightness slightly for the background color I will set the
lightness to be like 95% okay let's go to the bottom of our CSS
stylesheet when I hover over one of these buttons I would like to increase the lightness so with all
buttons with the hover sudo class change the background color so the lightness is 40% instead of
30 now these buttons light up when we hover our cursor over one of the buttons now when I click on one of the
buttons I'll increase the lightness further so it flashes we are selecting the active
pseudo class now let's take our background color property increase the lightness to
50% when we hover over a button it lights up when we click on it it flashes momentarily so with all of these
operators I would like all of these op buttons to be a different color I'll pick orange we're going to give each of
these buttons a new class let's head back to our HTML file beginning with the plus button I will set the class equal
to operator Das BTN for button so let's copy this class paste it for our minus
button multiply button divide button and the clear button now we will select the class of
operator BTN for button let's change the background color I'm going to set the background
color to be orange I've already pre-picked a color when I hover my cursor over one of
the operator buttons I would like the color to be a lighter orangee instead of gray let's take our operator button
access the hover sudo class I'll increase the lightness to 65% then when I click on one of these
buttons I would like the lightness to increase further with the operator button
class with the active pseudo class increase the lightness to 75% so when I click on one of the
operator but buttons it's going to flash momentarily all right and that is all the HTML and CSS that we need now we
just need to add functionality let's go to our Javascript file for our Javascript file there's not
a lot we have to write first we need to get the display element so what was that ID
display const display equals document. getet element by ID get the ID of display we have three functions to
create a function for append to display calculate and clear display these three functions function append
to display there is one parameter input because we were passing in a
character when we call this function then we have a function to clear
display then a function to calculate we'll begin with a pen to display all we're going to do is take
our display this element access its value append it with plus equals our input and let's see if this works seven
I forgot to change the font color of the display so let's do that within our display element let's set the color to
be white okay that's much better 7.13 + 5 equals okay we know that that
works when I click on the clear button I would like to clear this display let's access our display element
at access the value property set it equal to an empty string 3.14159 when I hit clear it should clear
the display lastly we have calculate let's take our display
elements value property set it equal to now we're going to use the eval function the eval function takes an
expression such as 1 + 2 + 3 and evaluates it and gives a result it's kind of like it's its own built-in
calculator so to say evaluate the value within our display display.
value so if I add 3.14 plus 1.01 I'm given a result of
4.15 now for some reason if we get an error for example 7 + equal well we have a problem let's go to our
console we've encountered an uncaught syntax error because we never finished our equation in the last lesson we
learned about error handling this is dangerous code it can cause an error let's surround this code with a try
block we will try this code and catch any errors that happen so we need a catch block now
catch any errors we will change the value of the display to equal some text of
error all right and that should work 3.14 times equals that results in an error we can clear it and then start
over what's 1 + 2 + 3 + 4 that would be 10 all right everybody so that is is a calculator program you can make using
JavaScript HTML and CSS impress your friends all right what's going on people so today I got to explain what the Dom
is in JavaScript the Dom is the document object model it's a JavaScript object that represents the page you see in the
web browser and it provides you with an API to interact with it the web browser constructs the Dom when it loads an HTML
document and structures all of the elements in a tree like representation within my HTML document we have our HTML
element as the root element the HTML element contains a head element and a body element and many various elements
can be found within each of these they're arranged in a tree likee data structure but we access this tree like
data structure from the document object in past lessons in order to select an element by its ID we would type document
dot then follow it with a method like get l element by ID and then we would select an element by its ID our document
is an object it contains properties and methods and other nested objects if I was to
console.log the document well then it's going to display my HTML
document now you can also use dur meaning directory this will list all of the properties of this
object so here's my document object and all of the different properties it contains it's one gigantic object for
example we have a title the title of the web page that would be found right here near
the bottom document but you can change it I will access our document as if it was an object because it is access the
title property change it to something else like my website now if I display the title
that property has changed it's now my website dynamically after the page loads I would like to change the background
color of my document later on in the series we're going to create a toggle button to toggle between light and dark
mode just to give you an example if I need to change my theme to be dark mode I could access the document object
access the body access the style then change the background color property to some
color let's stick with black for now I'll use hsl the Hue will be zero saturation will
be 0% and the lightness will be 15% even though we have no CSS we're still able to dynamically change the
background color let me give you another example we'll create an H1 element this H1 element will say welcome
I will give this element an ID ID welcome- MSG meaning
message and I'm just going to zoom in a little I will create a constant of username type in your username or your
full name I'm going to conditionally change the content of this HTML document I will
get this element by its ID our welcome message const welcome message I'm using camel case naming convention for this so
I will access my document use the get element by ID method that ID was welcome- message MSG for short I would
like to update the text content of this element I'll take my welcome message access the text content of it
then appen some text using stringy catnation I'll use the tary operator to see if my username is strictly equal to
an empty string is our username empty did somebody not type it in question mark If username is empty I
will append our welcome message with guest otherwise our username my username has a name it's not
empty it will display my name welcome Thro code if it was empty if somebody didn't type it in it will display
welcome guest so that's an introduction to the document object model the document object model is a JavaScript
object that represents the page you see in the web browser and it provides you with an API to interact with it the web
browser constructs the Dom when it loads an HTML document and structures all of the elements in a tree likee
representation by using JavaScript we can access the Dom dynamically after the page loads and change the content
structure and style of a web page and well everybody that is an introduction to the document object model in
JavaScript hey it's me again so today I got to explain element selectors in JavaScript element selectors are methods
used to Target and manipulate HTML Elements by using these methods they allow you to select one or more multiple
HTML elements from the Dom the document object model these methods are built-in methods of document the Dom we can
select Elements by an ID a Class A tag name and then there's query selector and query selector all these methods return
something different either an element an HTML collection or a node list one method you're probably already familiar
with is get element by ID so in this example within our HTML document we will create an H1 element I will create a
heading for my sample web page I'm hungry so I'm going to talk about food my heading is going to be food are us
it's like Toys R Us but it's with food I'm going to give this H1 element an ID of my Dash
heading so going back to our Javascript file I can select this element by its ID I'll store a reference to it const my
heading equals we're accessing the Dom with document. get element by ID that ID was
my heading I can access this element this H1 element using this reference so let's take my
heading access its style access its background color so with CSS properties in
JavaScript if you're accessing them through the Dom they have a camel case nameing convention if you're selecting
these properties with CSS they have a hyphenated naming convention so do pay attention to that
so with the background color I will set it to be yellow as if we're highlighting it you could also apply different CSS
properties let's take my heading access its style access the text align property and set it to be
Center and it's now centered now if I was to console.log this element of my heading
this is what we would see it displays my HTML element including its style if it has style for
some reason if this ID doesn't exist for example I'll misspell heading as heading with an extra G well this returns null
if I were to eliminate these two lines of code you can see that null get element by ID returns a single element
if it finds it or null if it doesn't the next method is get Elements by class name this returns an HTML collection
it's similar to an array but it's limited in the built-in methods that it has So within our HTML document I will
create three separate div sections this first development will have a class of
fruits my first fruit will be apple so let's copy this development paste it two times I'll change the second to be
orange then banana all right going back to our Javascript file I will use this method
of get Elements by class name this will return an HTML collection it's similar to an array but it's not technically the
same so const fruits this will be the name of my HTML collection equals docu doent we're accessing the Dom get
Elements by class name what is the class name that we're getting
fruits let's console. log fruits just to see what it is what are we working with so fruits is an HTML collection my
collection contains these three elements we have three objects within this HTML collection if I was to take a look at
some of these properties we should have text content so for the first element we have text content of Apple for the next
div element which has an index of one the text content is orange we can assume that the next element has text content
of banana to change something about one of these elements let's begin with the first element we have an HTML collection
of fruits to select one of these elements you'll use an index so let's take our HTML collection of fruits at
index zero that's going to return the first element our div element of Apple I will access its style access its
background color set it equal to be yellow as if we're highlighting
it there we are Apple it's highlighted for the next element I will increase the index to one that will select our orange
and then two would be banana if I would like to iterate over all of these elements I can use an enhanced for
Loop we'll say let fruit of fruits HTML collections are iterable we can iterate them with an enhanced for
Loop let's take each fruit access its style access its background color then set it to be
yellow and that should highlight all of them now HTML collections don't have a built-in for each method HTML
collections do allow for live updates but unfortunately they have a limited amount of utility
methods if I attempt to use our HTML collection of fruits then attempt to use a for each
method here's what happens we have a type error fruits. 4 each is not a function HTML collections
don't have a for each method we're not able to use that what we could do is typ cast our HTML collection as an array
let's access the class of array then use the from method this will return a new array of
fruits we'll typ cast our HTML collection as an array then you could follow this with the for each method if
you so choose for each element within our array after type casting it let's take each fruit I'll use an arrow
function what would we like to do let's take each fruit access its style access its background
color then set it to be yellow as if we're highlighting it and that does work get Elements by
class name will return an HTML collection of all matching elements that share this class if you would like to
use array method me with this HTML collection you would want to typ cast it to an array all right now we have get
Elements by tag name within our HTML document we'll create two unordered lists I will create an H4 heading of
root vegetables let me scroll down I will create an unordered
list with a few list items three should be good for my first list item that will be beets beets are a root
vegetable carrots and potatoes let's copy our unordered list
and our H4 heading paste it change the second H4 heading to be nonroot vegetables my first list item within
this other list will be broccoli celer and onions I just picked three
vegetables kind of at random with our next method of get Elements by tag name I can select one of
these elements by their tag name H4 unordered list list items take all matches within our HTML document stick
them all within an HTML collection I will create const const H4 elements equal alss we're accessing the Dom use
the get Elements by tag name method let's select all H4 elements then I will
console.log my HTML collection of H4 elements let's see what it is so it looks like this HTML collection
has two elements two H4 elements the text content of the first element is root
vegetables then we can assume that the other element is non-root vegetables yes it is non-root
vegetables we can access individual elements of this HTML collection by an index let's take this reference of H4
elements access the first index access the style access the background
color set it to be yellow as if we're highlighting it and that should highlight root vegetables the next index
of one would be non-root vegetables to apply CSS properties to all of the elements I can use an enhanced for
Loop for let H4 element singular of H4 elements plural take each H4 element access its style access its background
color set it to be yellow and that will highlight all of the H4
elements let's create another HTML collection of all the list item elements we'll create another reference to all
list item elements so that'll be beets carrots potatoes broccoli celery and onions const Li elements equals
document. getet Elements by tag name the tag that we're selecting is all list item elements
so using a for Loop let's iterate through them let Li element singular of Li
elements plural for each list item element access the style access the background color then set it to be a
different color let's say light green and now all list item elements will be a light green color and again
since the these are HTML collections not arrays they don't have any array methods but we can typ cast them so that they do
if I wanted to change the background color of these with the for each method of
arrays I'm going to typ cast our HTML collection of H4 elements as an array I will access the class of array
use the from method pass our HTML collection of H4 elements as an argument if I wanted to
use the for each loop I can method change follow this with for each what do we
want to do for each of these elements take each H4 element use an arrow function do this take each H4 element
access its style access its background color set it to be yellow and that does work so let's do
this with our list item elements I'll just copy this because I'm lazy we'll type cast our list item elements HTML
collection for each list item element take each list item element access its style access its background color set it
to be light green and that does work to that is the get Elements by tag name selector it will select all elements
with a matching tag name throughout your document it returns an HTML collection now we're going to talk about
query selector query selector will return the first matching element or null if it doesn't find any matches I
will create a const of element equals document. query selector query selector will return the
first match to select an element by a class name we'll use dot the name of the class these three elements have a class
of fruits let's select that dot fruits if I was to take this element access its style access its background color set it
to be yellow which element do you think is going to be selected the first Apple it's the first matching element Cory
selector only returns a single element the first match if I selected a tag name of H4 that would select root vegetables
even though we have two H4 elements the first matches selected if I selected the first list item element that would
select beats that is the first list item element on my web page if I changed this to UL meaning unordered list it would
select the first unordered list if I attempt to select something that doesn't exist like any ordered
lists well they don't exist there's no matches if I was to console.log my element
it would return n there's no matches so query selector selects the first matching element or null you can select
a class or a tag name then the last method we'll discuss is query selector all this returns a
node list a node list is similar to an HTML collection except it has built-in methods similar to arrays however no
lists are static HTML collections are live since node lists are static they do not update automatically in the Dom HTML
collections are live they will I'm going to select all elements that have a class of fruits I'll create a reference to
this const fruits equals document. query selector all we are getting a class of fruits
I can access this node list by an index number let's select the first element access the style access the background
color set it to be yellow and that will select Apple let's select the next element that's orange
the next would be banana let's select all list item elements I'm going to rename this though
let's rename fruits as Foods let's select the first element that would be
beets the next element would be carrots then potatoes broccoli
celery onions so if I was to console.log
Foods this would give me a node list with six elements node lists do have a built-in
for each method let's use that we don't need to typ cast it as an array take our node list of foods use
the built-in for each method what do we want to do take each food use an arrow function do this take each food access
its style access its background color set it to be yellow this will take all list item
elements change the background color to Yellow as if we're highlighting them all right everybody so those are different
element selectors get element by ID get Elements by class name get Elements by tag name query selector and query
selector all there is a lot of overlap where you could select any number of these to select something but they each
return something different personally I like using a combination of get element by ID and query select all but that's
just my personal preference in conclusion element selectors are methods used to Target and manipulate HTML
elements they allow you to select one or more multiple HTML elements from the Dom once you select your element or elements
you can make any sort of changes that you would like and well everybody those are element selectors in
JavaScript yo what's going on people so today I got to explain Dom navigation in JavaScript Dom navigation is the process
of navigating through the structure of an H HTML document using JavaScript HTML elements include but are not limited to
the following properties for D navigation we can get the first child the last child the next sibling the
previous sibling a parent or all the children of an element so for this exercise within our HTML document we're
going to create a few unordered lists of course these unordered lists are going to be for food because I like food the
first unorder list will have an ID of fruits let's create a few list item elements an
apple an orange and a banana we'll need a few unordered lists
to work with let's copy this unordered list and paste it twice the second list will be for
vegetables pick some vegetables I'll pick carrots
onions potatoes the third unordered list will be for desserts I'll pick
cake pie ice cream that is good enough for now
heading back to our Javascript file I will now discuss the property of first element child our unordered lists are
elements they each have their own children a child element is any element found within this element our unordered
list of fruits has three children Apple orange banana vegetables has three children carrots onions potatoes
desserts has three children as well cake pie and ice cream let's say that our unordered list of fruits is a parent
well Apple would be the firstborn orange would be the middle child and banana would be the last born if these were
actual children so think of it that way so so I'm going to create a constant of element I'll be using this as a
reference document. getet element by ID I will get that unordered list of fruits I'm storing this unordered list
within this element I will create a reference for the first child equals take our element
access the first element child if I was to take this element change its style access its background
color set it to be yellow which element is going to be highlighted Apple if I selected a
different element like my Ida vegetables the first child would be carrots then desserts the first element child of
desserts is cake they are the firstborn children they're at the top Within These un ordered lists if you used query
selector all I'll give you a demonstration I will select all unordered lists const UL
elements equals document dot query selector all select all unordered
lists this will return a node list node lists do have their own built-in for each method take all UL elements use the
built-in for each method what do we want to do iterate over every unordered list element do this let's create a reference
to the first child equals take our unordered list
element access its first element child then store it as a reference let's take our first
child access its style access its background color property set it to be
yellow that will highlight all of the first element children of all the unordered lists so that's how you can
use Query selector all to select all of the first children of all matching elements now we're going to access last
element child with our unordered lists if we're select ing our elements of fruits vegetables and desserts this
would return the last child banana potatoes or ice cream depending on what we're selecting if these were actual
children these three elements are the last born they're the youngest I'm going to create a reference to an element
equals access the Dom get element by ID I will get my ID of fruits I will create a reference refence
to the last child equals take our element get the last element
child take our last child element access its style access its background color set it to be
yellow so that will highlight banano if I change the selected element to vegetables that would select potato es
if I selected desserts that would select ice cream they are the last element children found within each of these
elements if I were to use Query selector all to select all unordered lists let's create const UL
elements equals document. query selector all select all unordered
elements this returns a node list they have their own built-in for each method take our node list of unordered
elements use the built-in for each method take each unordered list element use an arrow function to do this
I will create a reference to the last child equals take each unordered list
element access the last element child take the last child during each iteration access its style access its
background color set it to be yellow and that will select banana potatoes and ice cream select all unordered lists take
each of their last children change the background color to be yellow so that is the last element child property in this
next example I'll demonstrate next element sibling but we're going to make a few changes going back to our h HTML
file we will give each of these list items a unique ID so let's start with the first the ID will be Apple for the
first list item element I'll copy this ID for each of these elements and then change them in a
moment so we have apple followed by orange banana carrots onions potatoes cake pie then ice cream
if I'm selecting my unordered list of fruits Apple orange banana or the children they are all siblings to each
other if I were to select Apple then get the next sibling that would be orange if I select carrots the next sibling would
be onions if I selected cake the next sibling would be pie so let's create a constant of element equals document.
getet element by ID the ID that I'm going to select is Apple I will create a reference to the
next sibling equals take our element access its next element sibling take our next
sibling access its style access its background color set it to be
yellow if I'm selecting Apple the next sibling to that would be orange if I were to select orange the next
sibling would be banana if I were to select banana well banana doesn't have a next sibling it's the last in line we
wouldn't be selecting anything there is no next sibling for banana if I were to select carrots the next sibling is
onions if I selected onions the next sibling is potatoes if I selected cake the next sibling is pie if I selected
pie the next sibling is ice cream what if I SEL selected fruits vegetables or desserts what would be highlighted I
will select the ID of fruits that would highlight my unordered list of fruits these three unordered lists of
fruits vegetables and desserts they're all children of the body they're all siblings to one
another it's kind of like if the list item elements of Apple through ice cream are all children the unordered lists of
fruits vegetables and desserts are the parents and the body is the grandparent if I
select the unordered list of fruits the next sibling would be vegetables by accessing the next element
sibling of my unordered list of fruits that selects my unordered list of vegetables if I selected vegetables then
get its next sibling that would give me this unordered list of desserts all right then we have previous
element sibling if I select an element we'll get the the previous element sibling so if I were to select orange
that would give me Apple if I selected banana that would give me orange if I selected onions that would give me
carrots I will create a constant for element equals document. getet element by ID I will select
orange const prev meaning previous sibling equals take our element access the the previous element sibling if I
were to take my previous sibling access it style access its background color set it to be
yellow the previous sibling of orange is Apple the previous sibling of banana is
orange if I selected onions the previous sibling is carrots the previous sibling of
potatoes is onions the previous sibling of pie is
cake the previous sibling of ice cream is pi if I selected the first sibling then attempt to get the previous
sibling well we don't select anything the previous sibling of a first child doesn't exist if I selected the previous
sibling of my unordered list of vegetables that would select my unordered list of fruits if I selected
the unordered list of desserts that would give me vegetables now we have the parent
element property whichever element I select will get the parent the parent is the element that contains
it const element equals document. getet element by ID I will select Apple const
parent equals access our element access the parent element let's take our parent access its style access
its background color set it to be yellow that will highlight my unordered list of fruits if I selected orange well that
wouldn't change the parent is still fruits same thing goes with banana if I selected carrots well the parent is
vegetables that unordered list if I selected ice cream while the parent is desserts so that's how to get the parent
of an element you can access the parent element property the last property we'll discuss
is children we can return all of the children of a selected element I will create a const element equals
document. getet El element by ID I will select my ID of fruits I would like all children of this
element I'll create a reference to Children equals take our element access the children property if I was to
console.log Children this is what we're working with by accessing the children of an
element that returns an HTML collection this HTML collection has three list item
elements HTML collections don't have a built-in for each method I would need to typ cast it as an array using the from
method of arrays let's take all of our children convert it to an array then method chain the for each
method let's take each child from children then do this take each child during each iteration access its Style
access its background color set it to be yellow so this will highlight all children of a selected element Apple
orange then banana if I selected vegetables that would highlight carrots onions
potatoes if I selected desserts that would highlight cake pie then ice cream you can even access these children by an
index number let's say you would like to highlight a
middle sibling orange onions or pie let's take our children it's an HTML collection access it by an index number
so let's access children at index one of desserts that would highlight pie let's select vegetables that would
highlight onions then fruits would highlight orange all right everybody so that is an
introduction to Dom navigation it's the process of navigating through the structure of an HTML document using
JavaScript there are several different properties that you can use to navigate through HTML elements and well everybody
that is an introduction to Dom navigation in JavaScript hey everybody in today's
video I'm going to show you how we can add and change HTML elements using JavaScript so sit back relax and enjoy
the show I'll break down creating an appending element El to the Dom in three simple steps we'll create the element
add any necessary attributes or properties and then append the element to the Dom will be the final step but
before we do begin within our HTML file we'll create a few boxes for this exercise these will be
developments with an inner paragraph the first will have text of box one with this development I will give it an ID of
box one and a class of box let's copy the div element paste it
three times for a total of four boxes we'll create box two box
three and box four I'll apply the following CSS properties we're selecting the Box class
add a border 3 pixel solid set a width to be 100% and a height of 125 pixels and we are ready to begin step
one we need to create the element in order to work with it right I will create a constant of new H1 H1 equals we
will select our document use the create element method then as a string pass in the type of the element we would like to
create we'll create an H1 element we now have an H1 element to work with which we're referencing as new H1 let's add
some attributes and CSS properties let's do one for now now I will take my new H1 element access its text content set it
equal to I like pizza and then we just have to append this element to the
Dom to do that we will access our Dom with document what element would we like to
select let's select the body element of our document and then we will use the append
method pass in our HTML element as an argument and there we go there's our H1 element when you append an element to a
parent this new element is the last child you could prepend if you would like it to be the first child so let's
use the prepend method change aend to prepend and it's now at the beginning let's add an additional
attribute we will take our new H1 element set the ID attribute equal to my H1 and let's see if that worked I will
rightclick on this element inspect it here's our H1 element it's the first child because we're prepending it this
H1 element has an ID attribute set to my H1 let's change the CSS properties of this element I will access new H1 access
its style access its color the f color let's set it to be red but better yet let's set the color
to be tomato because I like tomatoes I think that's a better looking shade of red let's also Center the text new H1
access its style access the text align property set it to be Center and the text is now centered when
I append this element I would like to append it to within box one I will select box one as the parent rather than
the body we will access our document we need to select an element we will select box
one we could use document. getet element by ID the ID that I'm going to select is box
one I will then follow this with append append our new H1 element so our H1 element is now within
box one and not outside of it like it was previously I could append this H1 element to box two but I would have to
select it we will get element by ID select box two to put it within box two box 3 and box
four when I'm appending this element to box one it is the last child of box one if there are any child elements within
this box which there is we have a paragraph element that H1 element will come after and not
before so if you would like this H1 element to be the first child we can prepend it I'm going to copy this
because I don't want to rewrite it we will prepend prepend my new H1 element take
box one prepend the new H1 element so my H1 element is now at the top it's the first child the paragraph element comes
after let's do this with box two box 3 and box four what if we would like to take our H1 element and sandwich it
between box one and box two I could select box two and insert that new H1 element before it here's how I will
create a reference to box 2 equals
document. get element by ID we will select the ID of box two access our document access the body
because box two is a child element of the body use the insert before method there's two arguments the new
element and the current element the new element is going to be new H1 that's what we're trying to add
the current element is the target we're selecting box two in insert the new H1 element before box two and this is what
that looks like this H1 element is now between box one and box two take the new H1 element insert it before box two if
we were to do this with box one well then it's going to be before box one let's try this with box
three our H1 element is before box three and box four what if these elements don't have
IDs how do we select them then here's how we will use Query selector all to select everything that has the Box class
I will create a constant of boxes this will be a node list access our document use Query selector all select everything
that has a box class we will use the the insert before method access our document access the
body insert before we have the new element to add and the current element the new element
is new H1 the current element is our node list of boxes we can access a specific element from this node list
with an index if I accessed boxes at index zero that would give me box one boxes at index one that's referring to
box two box three and box four so you could use Query selector to select many
elements store it within a node list then select those specific elements with an index
number this is optional but at any time if you need to remove an HTML element here's how let's append our new H1
element we need to select the location in which we can find that element it's within the body of our
document document.body use the remove child method we will remove our new H1 element
and it's gone what if this H1 element was within box one all right I will append our new H1 element to box one and
we need to add the IDS back to these boxes because I forgot to do that we're pending our new h one element to box one
when I try and remove it it doesn't work it's still there we need to select box one and not the body of our document
because box one is the direct parent of our H1 element not the body the body in this case could be like the
grandparent instead of selecting our body we will get the ID of box one or some other element selector to get box
one I'll use get element by ID because it's easy get element by ID the ID that I'm
selecting is box one remove the new H1 element that's found within it and it's gone if at any time you need to remove
an element select the parent of that element then follow it with the remove child method pass in the element you're
trying to remove as an argument in this last example we're going to work with ordered lists so
going to our HTML file we will create an ordered list with a pair of of O tags I will give this ordered list an ID of
fruits we'll add a few list items the first list item will be for an apple the ID will be
apple we'll create a list item element for an orange ID will be orange and a
banana ID banana I'll add a little bit of CSS styling going to the CSS stylesheet I
will select the ID of fruits I'll add a border of three pixel solid for this demonstration and increase the font
size to 2 RM all right and that's what we need to work
with we'll now be creating a list item element I will create a constant of new list item equals
document. create element what is the type of element we're trying to create a list item
element let's set any attributes or properties that's step two let's take our new list item set the text content
to equal coconut we'll append this element if I were to append this new list item to the
body of my document it's the last child of the body we're not adding it to this ordered list now
that we can see it I'm going to add a few more attributes and properties let's take our new list item access its ID
attribute set it to be coconut let's change the font weight new list item access the
style access the font weight set it to be bold
and the background color access the style access the background color I'll set the background color to
be light green we have our list item element if I append it to the body it's now the last
child of the body of my document not this ordered list found within the body if I were to prepend it this is what
would happen prepend the new list item it's now the first child now we'll select our ordered list
of fruits get element by ID fruits append the new list item and it's now at the
end at number four let's prepend to the ordered list get element by ID fruits prepend
our new list item our coconut is now at number one how can we insert our coconut between
Apple and Orange here's how since these list item elements have an ID I could use
that let's get the ID of orange const orange get element by ID orange instead of selecting the body
we're going to select the ordered list that has an ID of fruits document. getet element by ID the ID that I'm selecting
is fruits select the ordered list of fruits insert the new list item before the orange our coconut is now at number
two let's insert the coconut before the banana the ID was banana const banana insert the new list
item before the banana our coconut is now at number three you could insert before Apple too
I will get the ID of apple const apple insert the new list item before the
apple and it's back at the beginning what if these list items don't have IDs let's eliminate
those we would need to use Query selector to select all list items from the ordered list of
fruits so I'm going to use Query selector all select the ID of fruits then select any
list item descendants within this ID this will return a node list that stores all of the current list items within
this ordered list we need to select our ordered list of fruits not the body document. getet element by
ID I will select our order ordered list of fruits insert the new list item before
list items at index zero now will'll insert the coconut before the Apple let's increment our
index to one our coconut is now before the orange now it's before the banana and
now it's after the banana if I need to remove this list item I would need to select it first so let's append the new
list item to fruit I will get the ID of the ordered list of fruits remove the child of new list item
and it's now gone all right everybody so that is how we can add change and remove HTML
elements using JavaScript hey everybody in today's video I got to explain Mouse events in
JavaScript so sit back relax and enjoy the show the first thing I need to discuss is event listeners an event
listener listens for specific events to create interactive web pages a few types of events we'll discuss are click events
when we click on something Mouse over is when we hover over something and mouse out is when we're hovering over
something and then leave that element to add an event listener you'll use the add event listener method pass in an event
type including but not limited to this could be clicking on something hovering over something or leaving the confines
of an element and then a call back to a function what do you want to do when you interact with something for example I
could use the click event and then change the color of something when I click on it going to our HTML file I
will create a development for a box the ID of this development will be my box the text on the box will be click me
then for fun I'll add an emoji because I like emojis let's apply some CSS styling because it's kind of small
let's select the ID of my box change the background color to light green or some other color
of you're choosing set a width of 300 pixels a height of 300 pixels I'll increase the font size to
something large like 4.5 RM I'll set the font weight to be bold I'll use flex box
display Flex align items in the center and text align
center that is good enough for now be sure to save everything we're going to select the ID of my box we'll store that
as a constant const my box equals we'll need to select it by accessing the Dom document. getet element by ID I will
select select the ID of my box and then we can work with it easily we'll take my box add an event listener that's a
built-in method my box. addevent listener we need to pass in an event
type and a call back to a function I want to do something when I click on this box the event type is going to be
click and now we need to call back to a function we'll Define a function to change the background
color function change color there's going to be one parameter an event then we will pass in a call back to change
color now the event parameter event is an object it's provided to us automatically by the web browser when
something happens when an event occurs like when I click on something event is an object that contains information
about something that happens that event for this demonstration temporarily I'm going to to console.log my event so
let's click on the box then go to inspect console and here's my event when we clicked on that box the web browser
provided us with an event object it's a pointer event this object contains details about what happened
exactly for example we have the target what did we click on WE clicked on the div element with an ID of my box and
here are all the properties and methods of that box that's the target we have a time stamp of when the click occurred
the type of the event click which matches up with the event type and coordinates of where we clicked on the
screen event is an object that's going to be provided to us through the web browser automatically we don't need to
explicitly pass in an event object with this call back it's provided to us behind the
scenes I'm going to change the background color of our box when we click on it we will access our event op
object that's provided to us access the target the target is what we clicked on there's information about our Target
within the event object then I will take the style of the target set the background color property to be a
different color I will set it to be red but I prefer the shade of tomato because I like that color now when I click on
the box the background color changes but why stop there let's also change the text content I'll add one
more statement to the change color function again we will access our event access its Target access the text
content of the target to be ouch and then I'll add an emoji that's a good
one when I click on this box not only does the color change but the text too now you don't necessarily need to pass
in a call back you can also pass in an anonymous function or even an arrow function so let's copy these two lines
of code we'll reuse it later we no longer need to define a function within the event listener
instead of passing in a call back we'll pass in an anonymous function we have one parameter and event
that's going to be provided to us when we click on my box do this change the background color and the text now we
could even use an eror function I have a preference for Arrow functions because they're concise with their syntax with
an arrow function we have one parameter an event if you have a single parameter you don't need to enclose it within a
set of parentheses we have one parameter of event then do this do all this code and
that should still work when I click on the box the color changes as well as the text so when you add an event listener
you can pass in a call back or an anonymous function or an arrow function it depends on what
your preferences are personally I like Arrow functions we have a few other Mouse events to discuss Mouse over and
mouse out Mouse over is when you hover your cursor over something so let's take my
box add a new event listener an element can have more than one event listener add event
listener we have an event and a call back as arguments the event is going to be Mouse over for the call back I'll use
an arrow function we have one parameter of event Arrow do this let's copy these two lines
of code I'll change the background color to be yellow like it's a warning and the text content to be don't do
it that's a good face when I hover my cursor over this element the background color and the text is going to change
the event that occurred is mouse over it's when you hover your cursor over something Mouse out is when you leave a
specified element so when I leave the box I would like to change back the background color and the text content
We'll add an additional event listener my box add event listener the event type is going to be
Mouse out then I'll write an arrow function we're provided with an event Arrow do this
let's change the background color and the text content I will revert the background color to be light
green and the text to be click me whatever the text content originally was when I hover my cursor over this
element we get that Mouse over event but when I leave we get the mouse out event when I click on the this box we
get the click event when I leave the Box we get the mouse out event again to reset it essentially for the last part
of this demonstration we're going to create a button when we click or interact with the button then we'll
change a separate element this box so within our HTML file let's create a button with text of Click
me I will give this button a unique ID of my button and I'll increase the font size
with CSS we will select my button I will increase the font size to be 3
RM just so it's not so small let's select the ID of my button const my button equals document.
getet element by ID my button I'll add the event listener to my button not my box
if I was to interact with this button with the way it is now when I hover over the button we've created a mouseover
event and the button changes when I click on the button we're changing the HTML and CSS of the button because the
button is what has the event listener we're selecting the target of the event to change which is the button that is
what we interacted with when we interact with our box it doesn't do anything it doesn't have any event listeners the
button does though we're going to replace the event Target with my box when we interact with the button change
the background color and the text content of my box so then when I hover over the button
the Box changes when I leave it reverts back to normal when I click on the button then we've created a click event
all right everybody so that is an introduction to Mouse related events you'll need to add an event listener an
event listener listens for specific events to create interactive web pages a few events we've covered include click
Mouse over and mouse out to add an event listener take an element use the built-in add event listener method pass
in an event type and a call back Anonymous function or an arrow function to do something and well everybody those
are Mouse related events in JavaScript hey what's going on everybody in today's video I'm going to give you
an introduction to key events in JavaScript so sit back relax and enjoy the show so what we've discussed in the
previous topic is event listeners an event listener can be added to an HTML element they will listen for specific
events to create interactive web pages we'll be discussing key down and key up there is a third type of key event
called key press however according to the official documentation this event isn't compatible with all web browsers
so you should avoid using key press a key down event occurs when you press down on a key a key event occurs when
you release a key by adding an event listener to the Dom document we can detect when we press down or release a
key here's how we will access our Dom then add an event listener add event listener we have two arguments the event
type and a call back when we press down on a key let's do something doesn't matter what key it is any key for this
next argument I can either pass in a call back an anonymous function or an arrow function I like Arrow functions so
I'm going to use an arrow function we're provided with an event parameter when something happens within our web browser
an event object is created we can access it so I'm going to console.log this event object and we'll
see the details of it be sure to select your web browser I'm going to press the q
key then let's go to inspect console and here's that event
the web browser provided us with a keyboard event the key pressed was Q there's a
relevant key code of 81 and there's other properties too like was the ALT key being held down at the time it
wasn't same thing with the shift key and the target which is the body of our document I'm going to Output the key
property of the event we'll press a different key I'm going to hold down the F
key I'm not releasing it I'm holding it down we're going to consistently fire key down
events I would like to detect when I release a key I will use the key up event so let's copy this paste it the
event is going to be key up I'll display something else I'm going to use a template
string I will display key down equals then I will display this events key let's do this with key key up too I'll
just copy this key up equals event. key let's go back to our
console I'm going to hold down the S key then when I release it we'll have a key up event key up equals
s oh one more important thing the arrow keys we have Arrow up arrow down arrow left and arrow right if you ever would
like to make some sort of game the arrow keys are also accessible now what we'll do on key down and key up is change an
HTML element so to make this simple within our HTML document I'm going to create a div element this div element
will have an ID of my box I'll add some text an emoji all right let's add a little bit
of CSS we will select my box I will set the background
color to be light blue we haven't picked light blue yet I will set a width of 200
pixels a height of 200 pixels a font size of 7.5
RM I'll use flex box display Flex justify content Center
aine item Center this part is important for the next exercise we are going to set the
position to relative for relative positioning I'll set the body of my document to have no
margin margin zero all right we are ready we are going to select the ID of my
box const my box equals document . getet element by ID the ID that I'm going to select is my
box when I press a key down I'm going to change the text content of my box mybox do textcontent
equals I'll pick a different Emoji let's do that one and I'll change the
CSS mybox dostyle do background color equals tomato or some other color of you're
choosing so when I press down on any key the HTML and CSS is going to change I'm going to release that key but we don't
revert back to normal our HTML element stays that way what we'll do is that when we release a key we'll revert these
changes by going back to the original so let's take my box change the text content to equal an emoji because I like
emojis we'll use the original one then I will set the background color to be light
blue now if I were to hold down a button the HTML and CSS is going to change until I release that button which I am
about to now in 3 2 1 go I'm going to try and press the space bar as fast as I can seizure
warning let's go okay it's about time we move on what we're going to do now is using the arrow
keys move this element we're going to create a const of move amount when pressing an arrow key how far do we want
to move this element let's say 10 for 10 pixels I will create a variable for X think of these as coordinates I will set
that to be zero and y y will also be zero X for any horizontal movement and Y for any vertical movement
document. addevent listener when we have a key down event I
would like to do something I'll write an arrow function we're provided with an event do all this code I only want to do
something if a user uses an arrow key so if I was to console.log my event then access the key property let's
go to inspect console select your document I would like to do something only if the key pressed is Arrow up
arrow down arrow left or Arrow right I don't want any of the other keys I can write the if
statement if access our event access its key follow this with the starts with method does this key start with arrow
will only enter the SI statement if the key of the event is Arrow up Arrow down arrow left or Arrow right then we'll
write a switch we haven't written any switches for a while we will examine the key of our event with switches we
examine a value against matching cases if we have a case of Arrow up if the key of our event matches the
case of Arrow up then do this we'll take our y-coordinate subtract our movement
amount which is 10 Yus equals the movement amount and then be sure to break to break out of
the switch then we need a case for arrow down arrow down y+ equals our movement amount Arrow
left Arrow left X for the horizontal axis minus equals the movement
amount and then Arrow right arrow right X plus equals the movement
amount then outside of the switch but within our if statement we're going to access my
box access the style access the top property set it equal to a template
string we're going to take our variable of Y for the y-coordinate then add pixels take the top property of my box
set it equal to the y coordinate we're going to copy this and do this with the left
property set it equal to X in pixels be sure to select the body of your document we can move right with the right arrow
key down left and
up or diagonal if I hit two keys at once the arrow keys have a default Behavior to scroll you can see that if
we go down too far we have a scroll bar on the right hand side we can prevent the default behavior
of a key we just have to add this line of code take our event then follow it with the prevent default
method so when my element Scrolls off screen it'll disappear we're not going to scroll with it
to increase the distance in which this element moves we can increase the move amount let's set it to be 100 now we're
moving a lot further with each key press hey this is bro from the future there's one more thing I would like to
add to this project when pressing down on a key let's change the text content and the background color much like what
we did with the first exercise then when we release a key we'll revert the HTML and the CSS back to normal we're
combining the first exercise and the second one and this is the result when I move the arrow keys this guy's going to
freak out until I Let Go pretty exciting all right everybody so that is an introduction to key events
in JavaScript you're going to add an event listener to the document when you select your document and press a key
when the key is pressed down that will create a key down event when you release a key that creates key up event and well
everybody that is an introduction to key events in JavaScript hey everybody in today's
video I'm going to show you how we can show and hide an HTML element using JavaScript in this video you'll need an
image to work with once you find your image add it to your website folder then we are ready to begin we're going to
create a button and an image element let's start with the button the text on the button will be initially hide to
hide an element I will give this button a unique ID of my
button I'll add a break then we'll create an image element this is a self-closing tag with
this image I will set the source equal to either the relative file path or the file
name so my file is car.jpg it's a little too big I'll set the width attribute to be like 400 pixels that's a
decent size I will give this image a unique ID of my image my IMG and just so we can see this button I'm going to
apply a little bit of CSS to the button let's select the ID of my button take the font size I will set it to be 2
RM that's decent enough all right let's go to our J Javascript file I'm going to create a reference to my button and my
image let's start with the button const my button equals document. getet element by ID the ID that I'm selecting is my
button let's create a reference to my image as well my IMG the ID was my IMG when I click on this button I would
like to do something we will take my button and add an event listener add event
listener there are two arguments an event type and a call back to a function the event type is going to be
click when we click on the button we're going to do something for the call back we'll write an arrow function we are
provided with an event parameter by the web browser Arrow do this when when we click on the button what code do we want
to perform we're going to take my image access its style access its display property set it to be a string of none
so when you click on the button it's going to hide the image the display property is set to none not only that
let's change the text on the button after we hide the element let's take my button change the text content equal to
be show because now I want to show the element so hide become show when we click on the button a
second time nothing happens we would like to toggle between hiding and displaying this element we'll
write an if statement let's check to see if the display of my image is strictly equal to
none is the display of my image currently none if so we're going to set the display to Black block because it's
a block level element take my image access its style access its display property set it to be
block then within an lse statement place these two lines of code and we will change the text content
of my button to be hide now when clicking the button we can toggle between hiding and showing this
element the image now let me demonstrate something if we were to take my button then add it
after the image here's what would happen let me add a break
too so by setting the display To None we don't Reserve any space for that image my button moves up near the top of the
window until I show it again another option if we would like to reserve some space for the image is to toggle the
visibility not the display property replace display with visibility we're going to check if the
visibility is hidden set the visibility equal to be hidden if we would like to show the
image the visibility is going to be set to visible when we toggle the VIS ility of
this image we at least reserve the space for it the elements that come after aren't going to shift near the top of
the window you can use visibility or display depending on the project you're creating all right everybody so that is
how to show and hide HTML elements using JavaScript so uh yeah I should probably talk about nod lists today a no list in
JavaScript is a static collection of HTML elements they can be created by using query selector all we can select
Elements by an ID a class or an element type nod lists are similar to an array but they don't have a built-in map
filter or reduce method they do have a for each method at least though an important thing to note with node lists
is that they won't update automatically to reflect changes to the Dom for example if you were to remove an element
from the Dom and it's within a node list you would also have to separately remove that element from the node list so what
we'll do in this example is create four buttons they'll all have the same class we'll have button
one with a class of I don't know what's a good name my buttons the class all right let's copy this button paste it
three additional times we'll have button two button three button four and I'm going to add a little bit of CSS to
these buttons let's select the class of my buttons I'll increase the font size so you can see it font size for
RM add a little bit of margin 10 pixels remove the border border none smooth the corners with border
radius 5 pixels add some padding 10 pixels by 15 pixels I'll change the background color
to something blue background color blue but I'll select hsl
values I'll turn the lightness to like 60 okay that's decent and the font color will be
white okay that's good enough for now one way in which we can create a node list is by using query selector all
we've talked about this in a previous video but I'll show you a few more advanced things we can do with node
lists we can select Elements by an ID a class or an element type we will create a node list of let
buttons equals document. query selector all let's select all elements by a class
we need to use dot then the class name my buttons we could select Elements by an
element type if I would like to select all buttons I would just type in button the element type but I would like to
select only elements by this class now that we have our node list I am going to console.log my node list of buttons and
we'll take a look at it here's my node list it contains four elements button one button two button
three button four we do have a length property a few methods entries for each item Keys these are all different
methods for each is what we're going to be using a lot here's how we can change the HTML and CSS properties of all
elements within a node list we can use the for each method of a node list and iterate through all of the elements so
we will take our node list of buttons use the built-in for each method then write an arrow function we are provided
with an element Arrow do something but I'm going to rename element as button just so it's more easily understandable
during each iteration we're provided with a current button what would we like to do to that button well let's change
the background color button. style do background color I'll set it to be
green that should update the color of all the buttons not just one of them we're iterating through all of the
buttons within this no list change all of their background colors to be green let's change the text content too take
each button access the text content I will set it equal to be I don't know an emoji or
something let's do that the text content and all the buttons is is going to change maybe let's append an emoji not
replace the text content that's better that is how you can add and change HTML and CSS
properties with a node list use the for each method then write an arrow function to do something in a similar way we're
going to add an event listener to each button that will listen for a click so again we're going to take our node list
of buttons use the buil-in for each method for each button Arrow do this we need to add an event listener to
each button we will take the parameter of button add an event listener within our event listener we
have an event type and a call back to do something the event type is going to be
click instead of a call back we'll write an arrow function we are provided with an event Arrow do this event is proved
provided to us through the web browser when something happens we will access the event objects Target meaning the
button that we click on that's going to be our Target access the
style access the background color property let's set it to be red or better yet tomato because I like
tomatoes each button has an event listener it will listen for click events when we click on a button the background
color is going to change we're going to add an event listener for Mouse over and mouse out let's begin
with mouse over again take our node list of buttons use the for each method for each button Arrow do this
take that button add an event listener with event listeners we have an event type and a call back the event
type Tye is going to be Mouse over when we hover our cursor over something what would we like to do we
will write an arrow function event Arrow do this let's access the events Target that should equal our button that we
click on access the style access the background color so with the current color I'm
going to go back to my CSS I will copy this color paste it but make the lightness 10% darker now when we hover
over one of the buttons the background color is going to change I'll set the lightness to like
40% to make it much more apparent there that's better now when I leave one of these buttons I need to revert that
color back to the original really we can just copy all this code replace Mouse over with mouse
out and set the background color back to the original
each button now has a mouse over and mouse out event listener here's how you can add an
element to a node list I will create a new button const new button equals document. create element what element
are we creating a button so with creating an appending HTML elements there's three steps this
is step one we need to create that element first step two is to add any necessary
attributes or css properties so let's take our new button change the text content of the button equal to be button
5 I would like to give my new button a class of my buttons we're going to access the class list
property new button. class list when working with an element's class we work with class list not
class so the class list equals the class of my buttons then we have step three now we
have to append this element to the Dom what is the parent element of this new button going to be well in this case
it's going to be the body of my document we're going to be adding a new button right here the parent the
enclosing element is the body in this case access our document select the body append Child new
button and there's button five since we added our class of my buttons that's why it has all these CSS properties if I
were to remove this line of code we get the default appearance for a button I'll talk more about class lists
in the next video there's a lot you can do with them now if I was to console.log my node list of buttons
here's what we have we have five buttons within our Dom but within our node list we have four
buttons button one 2 3 four button five isn't within this no list no lists are a static collection
they won't update automatically to reflect changes to the Dom even though button five is within the Dom we would
need to manually add it to our no list if we want to work with it so to do that we can just use Query selector again and
select all elements by the class so let's reassign buttons since we're reassigning buttons that's why I
declared buttons with let instead of const so we're able to reassign it because if this was a constant we
couldn't change the elements within it so buttons equals document. query selector all select All
Elements by a class class my buttons and then again let's console.log my node list of
buttons inspect console and there we go our node list has five elements button 1 2 3 4
5 even if you were to add an element to the Dom that same element isn't going to be automatically added to your node list
I would recommend using query selector all again just to update it here's how to remove an element from a node list
when you click on it we'll have to give all of these buttons an event listener they will listen for a click event when
we click on one of these elements remove it from the Dom and the node list here's how again we will take our node list of
buttons use the built-in for each method for each button within our node list do this take each button add an event
listener we are provided with an event type and a call back to a
function the event type that we're listening for is click the call back is going to be an
arrow function we're provided with an event Arrow do this to remove an element from the Dom when you click on it we
will access our event object access the target use the built-in remove method to remove it so let's see if this works
currently let's remove button 2 1 4 3 so those buttons are gone but let me show you something I'm going to
console.log my node list of buttons after each click even if I were to remove these
buttons from the Dom they're still within the node list even after all the buttons are gone our
node list still has four buttons so we do have to update that manually here's an easy way how to do
that we're going to use Query selector all again we'll reassign buttons equals
document. query selector all select all elements from the Dom that have a class of my
buttons then just to see if this works let's console.log my node list of
buttons now when we click on a button it should be removed from the Dom and the node
list when I remove all the buttons our no list is then empty all right everybody so that is an
introduction to node lists they're a static collection of HTML elements they can be created by using query selector
all we can select Elements by an ID a class or an element type they're similar to an array but there's no map filter or
reduce method and do remember that nod list won't update automatically to reflect changes
to the Dom and well everybody that is an introduction to node lists in JavaScript hey everybody so in today's
video I got to explain class lists in JavaScript class list is an element property it's used to interact with an
elements list of classes meaning CSS classes by accessing the class list property of an element we can make
reusable classes for many elements across your web page if I have a CSS class I can dynamically add remove
toggle replace or check to see if an element contains a certain class so what we'll do in this example in our HTML
document is create a button the button will have text of my button the ID of this button will be my button we'll
apply a little bit of CSS initially let's select the ID of my button
we'll be applying just a few properties let's increase the font size to for
RM oh not 43 four go back go back go back I'll add a little bit of margin of 10 pixels remove the border with border
none border radius to smooth the corners 5 pixels and add a little bit of
padding 10 pixels by 15 pixels that's good enough for now we're going to create a CSS class of
enabled we won't apply it right away though we'll apply this class to this button using JavaScript if an element is
enabled let's change the background color to be something blue I'm going to use hsl values
though and I will set the font color to be white so this button doesn't doesn't
have this class yet we'll add that in dynamically using JavaScript we'll create a reference to this button const
my button will be the name then we need to select it document. getet element by ID the ID that I'm selecting is my
button to add a class to an element take that element my button access the class list property follow this with the add
method we will add the name name of the class enabled and now my button is enabled we have appended the CSS
properties dynamically so if I were to inspect this element I'll rightclick
inspect we have added that class of enabled to the element so my button has an ID and a class of enabled to remove a
class again take that element of my button access the class list we will use the remove method method we will remove
the class of enabled and it's gone let's right click on the element
inspect so our class list is empty we have added and then removed that class of enabled we're going to create a new
class now of hover when we hover over an element apply these CSS properties it's kind of like we're using the hover sudo
class but we're using it a little bit different we can add or remove this class dynamically at will if we apply
this class let's set a box Shadow to give the element a 3D pop effect for a horizontal and vertical offset let's set
those to be zero each let's add 10 pixels for the blur effect and I will set the color to be I don't know let's
set it to be black but set the alpha down to like 20% and then when I hover I would also
like to set the font weight of that element to be bold
let's add the hover class so the appearance of this button changed I would like to apply this class
of hover only when I hover my cursor over the element We'll add a mouse over event
listener we will take my button add event listener we have an event type and a
call back to a function the event type will be Mouse over when we Mouse over this element
we are provided with an element object event Arrow do this we will access our event objects Target meaning the button
take our class list and add the class of hover and let's see if this works if I
hover my cursor over the button we apply the hover class now when I leave the button I would like to remove it really
we can just copy the code for the event listener paste it replace Mouse over with mouse out then we will remove that
class so now we can apply that class and then remove it with mouse over and mouse out there's also toggle if we toggle a
class we'll remove it if that class is present add that class if it's not so let's replace add with
toggle do this for both Mouse over and mouse out and that should work the same when we hover our cursor over the button
we will toggle the class of hover if we have a mouse out event we will toggle it again to remove
it now we're going to use the replace method to replace one class with another we'll create a new class of
disabled we'll be replacing the enabled class with the disabled class when we click on the button so with the
background color of the disabled class let's set the background color to be Gray
again I like using hsl for the colors I'll set the lightness to be like 60% I'm trying to get a faded appearance
and for the color let's pick a light shade of gray using hsl
values I'll set the lightness to be 80% going back to our Javascript file let's add the class of
enabled my button access the class list use the add method we will add the class of
enabled then we'll add an event listener to the button we will take my button add an event
listener we have an event and a call back the event is going to be click I would like to do something when we click
on the button we will receive an event Arrow do this take our events Target access the class list we will
will use the replace method replace the old class with the new class replace the enabled class with the disabled class
there's two arguments the old class and the new class replace the old class with the new
class then when we click on this button we'll replace the enabled class with the disabled class then we have the contains
method if an element contains a class this will return true and if it doesn't it returns false So within our event
listener let's add an if statement and an else statement we'll check to see if our
events Target access the class list we will use the contains method if we click on the button and the
class contains disabled what do we want to do does the class list contain disabled
let's change the text content take our vents Target access the text content I'll append an
emoji what's a good one that one else replace enabled with disabled let's click on the button we'll
replace the enabled class with the disabled class our button is now disabled if I were to inspect this
element the class is now disabled if I were to click on this button again well our class contains
disabled that was true so we end up doing this code where we append to the text content of the button now the nice
thing about using class lists HTML elements have a class list property we can reuse CSS classes amongst many HTML
elements we'll create an H1 element now the text of this element will be hello I will give this element a unique
ID of my H1 I'll increase the font size so we can see it select the ID of my H1 I'll increase
the font size let's try five RM let's create a reference to my H1 const myh1 equals document. getet
element by ID the ID that I'm selecting is my H1 we'll add the enabled class to myh1 myh1
do classlist do add not ass add
enabled and there we go we have added these CSS properties to this element and because I'm lazy I'm going
to copy all this code where we add an event listener to my H1 so let's replace my button with my
H1 now when we click on this H1 element we can disable it we'll replace the enabled
class with the disabled class and if you don't believe me let's take a look the class of my H1 is now
disabled if I were to click on this element again while the class list contains disabled so we execute this if
statement where we change the text content of that Target now here's a challenge round
we're going to create four buttons and store all of those buttons with then a node list so let's create a button with
the text of the first button being button one I will give this button a class of my
buttons let's copy this button paste it three times button one button two button three
button four let's remove the CSS from my H1 select the class of my
buttons keep these three classes of enable hover and disabled okay let's eliminate all this
code we'll create a node list to contain all these buttons we can use const if we don't plan on adding or removing buttons
or let if we do let buttons equals document. query selector all select all elements that have a
class of my buttons we'll apply our enabled class to all the buttons so we will take our node list of
buttons use the for each method for each button within our node list do this take each button access each
button's class list property I will add a class of
enabled and we have applied that class to all the buttons If you need to remove a class you can do the same but replace
add with remove move now when we hover a cursor over one of these buttons we will toggle the
hover class we need to iterate through our node list of buttons take buttons use the built-in for each
method for each button within our node list do this take each button add an event
listener the event listener has an event type and a call back to a function the event type will be Mouse over when
we hover a cursor over it we will be provided with an event argument Arrow do this access the event
object access the target meaning the button that we hover over access the class list property we will
toggle the hover class so when we hover our cursor over one of these elements we will apply the hover class
now when our cursor leaves one of these elements we would like to toggle that class again let's copy everything we
have here paste it replace Mouse over with mouse out when we leave one of these elements
toggle the hover class again to remove that class now when we click on one of the
buttons we're going to replace the enabled class with the disabled class
take our node list of buttons use the for each method with each button Arrow do this
take each button add an event listener we need to select the event type and a call back to a function the
event type is going to be click the parameter is event Arrow do this when we click on one of these
buttons we'll replace the enabled class with the disabled class take our event object
access its Target access the class list property we will replace replace the old class with the
new class replace the enabled class with the disabled class and let's see if this works when I
click on a button we'll replace the enabled class with the disabled class the last thing we'll do is that when we
click on a button that's disabled we'll change the text content we'll have to use the contains method So within our
event listener I'll add an if statement if access our event access its Target access the class list property
use the contains method does the class list contain the class of disabled if it does we'll
access our event access the target of that event change the text content of that element I'll append an
emoji that one I like that emoji if the class list of that element isn't disabled it doesn't contain the class of
disabled we'll execute an L statement where we disable it by replacing the enabled class with the disabled class we
have three event listeners Mouse over Mouse out and click we're utilizing all three of these custom classes enabled
hover and disabled we can hover over these elements then we'll have Mouse over and
mouse out events then when I click on one of these buttons we can apply that disabled class within our click event
listener we have an if statement if we click on an element that's already disabled append the text
content all right everybody so that is the class list property it's used to interact with an elements list of
classes their CSS classes they allow you to make reusable classes for many elements
across your web page and well everybody that is the class list property in JavaScript hey what's going on everybody
in today's video we're going to create a game of rock paper scissors using JavaScript so sit back relax and enjoy
the show all right let's do this thing we're going to create an H1 heading with text of rock paper
scissors for a title we'll create three buttons the first one will be for rock you can add
some text of rock but you know what I like using emojis I'm going to use an emoji instead I would like an emoji of a
fist and I'm going to zoom in until we add some CSS let's create a button for paper that'll
work and scissors maybe a p sign with each of these buttons I will
set the onclick event handler equal to a JavaScript function we'll name the function play game now with these
functions we're going to pass in an argument the first will be a string of rock now if you use double quotes HTML
is going to be confused where this event handler ends our argument is going to be a string but it's going to be within
single quotes because we're already using double quotes let's copy this attribute cuz I don't
feel like typing it again the second argument will be for a string of paper and then
scissors let's enclose our buttons within a div element this div element will have an ID
of choices let's cut our buttons and paste them within the div element outside of
the div element we'll create create another div element we will display the Player's
Choice player colon space the ID of this development will be player display this will display the
word rock paper or scissors depending on which button we pick let's do this for
computer text will be computer ID computer display we should display a result who
won the ID will be result display just for some temporary text I'm
going to add it's a tie when we style this with CSS I would like to be able to see the updates we'll get rid of this
pretty soon eventually we'll add in a score tracker but we'll do that after our game is at least working okay let's
head to our CSS stylesheet I'm going to zoom back to 100%
let's select the body of our document I will set the font family to be aial with the backup of s
serif let's set the font weight to be bold throughout this application I will set any margin to be
zero around the body use flex box to display the elements display
Flex the flex direction will be a column and align items
Center let's select our H1 element I need to increase the font size font size 3.5
RM for a color pick a color for me I'll set the lightness to 20%
now we're going to select our development of choices actually let's make this a class class
choices select the class of choices add margin
bottom of 30 pixels within this development we need to select all the
buttons we will select the class of choices select all buttons within this class we increase the font
size to 7.5 RM these buttons need to be big I will set a minimum width of 160
pixels at a little bit of margin between each button zero pixels on the top and bottom
10 pixels on the sides for the buttons I would like rounded Corners I would like these buttons to be a
circle I can set the Border radius to something massive like 250 pixels that will give us some rounded buttons and
pick a background color background color I want something blue I've already pre-picked a color so
I'm going to use this now when I hover my cursor over one of the buttons I would like my cursor to
change into a pointer and that does work let's also add a transition effect let's change the background color
to e after half a second let's access the hover sudo class of all the buttons of
choices take the background color I'll set the lightness to be 20% lighter each button is going to light up
when you hover your cursor over the button then we'll work on the display displays next we're going to select the
player display and the computer display these are ideas player
display and computer display let's set the font size to be a 2.5
RM and for the result display where it says it's a tie that's the ID of result
display set the font size to be 5 R and I'll add some margin to the top
and bottom 30 pixels to the top and bottom zero on the sides okay that is good enough for
now so we no longer need this placeholder for the result display let's add some
functionality we have a lot of constants to declare const choices choices will be an array of strings we'll have
Rock paper and scissors we need to get the player
display and the computer display so we can update them const player display equals document. getet
element by ID the ID that I'm selecting is player display then we have computer
display computer display and a result display this one it's empty currently const result display equals
document. getet element by ID result display we'll factor in scoring later we need a function of play game that
accepts one argument the Player's Choice function play game we have one
parameter player choice when we play a new game we have to pick a choice for the computer
between rock paper or scissors what we could do is generate a random number between zero and two rock is index zero
paper is index one scissors is index 2 we'll create a constant within play game of computer Choice I'm declaring it
within the function so we can update it every time we play a new game equals take our array of
choices at index for the index we'll generate that random number using the random method of math math. random
method * 3 then we need to round it because it's not going to be a whole number math. floor to round it
down so the computer's choice will be a random index between 0 through two which will give us randomly either rock paper
or scissors hey this is bro from the future one thing that would be good for us to do is along the way use
console.log just to be sure that what we've been writing has been working so within our computer's Choice let's
console.log whatever that is so if this does work after clicking one of these buttons the computer is
either going to pick rock paper or scissors the computer picked scissors just now scissors scissors it really
like scissors apparently so yeah the Player's Choice is being populated with the string of rock paper or scissors I
just wanted to confirm that and we need a result what are we going to display to the
screen result will be an empty string for now first let's check to see if the Player's Choice is equal to the
computer's choice that means it's a tie if Player's Choice is strictly equal to the
computer's Choice maybe we both pick rock well well then we'll take our result to be displayed and set it equal
to be it's a tie else somebody is going to
win let's add an else statement we can use a switch we can examine a value against
matching cases we'll examine the Player's Choice does the Player's Choice match
the case of rock do these two Val use match if so we'll use the tary
operator we'll check the condition of if our computer's choice is strictly equal to
scissors if so question mark That's the tary operator if we pick Rock and the computer picks scissors we will return U
win otherwise if this condition is false well that means the computer picked paper if our choices already don't match
and we picked rock that means they either picked scissors or paper if they didn't pick scissors that means they
picked paper so they win that means we lose you lose whatever string is returned we're
going to assign it to result result equals whatever is returned either you win or you lose then we should add a
break after this case all right let's copy this case and everything within
it let's paste it if the Player's Choice matches the case of paper and the computer's choice is strictly equal to
rock that means if that's true you win else you lose let's copy this case and everything within
it case scissors if the computer's Choice equals paper then you win otherwise you lose
after we move beyond the IFL statements we need to update the text on the screen so we will take the players
display set the text content to equal a template string of player col in space add a placeholder
the Player's Choice did we pick rock paper or scissors then let's do this with the computer's
Choice select the text content of the computer display the text will be
computer we will display the variable of computer Choice the one that was picked randomly and take our result
display which has no text content currently set it equal to be
result okay let's see what we have currently let's pick Rock it's a tie paper you win scissors you lose what
we'll work on next depending on the result that's displayed if we win I would like the text to be green if we
lose I want the text to be red going to our CSS stylesheet we're going to add three
classes green text red text pick a font
color pick something green and for the red text pick a red font
color if we win or lose we're going to add one of these classes to the class list of our result display so going back
to to our Javascript file after we display the result now we're going to add a
switch we're going to examine our result we will add a case of you win if our value matches this case let's
take our result display access the class list use the add method add the class of green text
then break let's copy this case paste
it we will add a case for you lose add the class of red text if we lose let's see what we have
currently if we win you get green text if you lose you get red text but now if it's a tie we have red text with each
new game we should reset the color back to the original so before updating the color
and displaying it let's take our result display access the class list use the remove method remove any class of green
text and red text let's see if this works you lose it's a tie that's black you lose you win
the colors seem to be working all right now let's add scoring mechanism we'll have to head back to our HTML
file after our result display we're going to create a div element the first div El will have a
class of score display the text for the score display will be player
score colon space then we'll add a span element within with text of zero row I will give
the span element a unique ID of player score display the reason I'm putting this
number within a span element I'm going to style this number different from the rest of the div element the player
score okay let's copy this div element and paste it we need another for computer computer
score the ID of the span element will be computer score display going back to our c a stylesheet
we'll add the following after our result display we will select the class of score
display increase the font size font size will be 2 R for the actual numbers I'm going to
change the color with the CSS property where the font color is green I'll add an additional selector let's select the
ID of player score display I would also like that to be that shade of green and for the red text let's select the ID of
computer score display so the computer score that number will be red okay now we just need
to add functionality to the scoring mechanism so back to the top we're going to select the ID of
player score display const player score display equals doc min. getet element by
ID player score display and we need the same thing for the
computer computer score display and we need a score value a number so we can work with it let player
score equals zero let computer score equals z going to the bottom of this function
within our switch within our case of you win we're going to increment our player score player score
Plus+ then take our player score display and update it access the text
content set it equal to whatever the player score is then let's do this with our computer
computer score Plus+ that's if we lose and computer score
display equals the computer score and that should be everything let's see if this program
works you lose you win you win it's a tie you win you win you lose the player score is four the computer score is two
all right everybody so that is a game of rock paper scissors you can make using JavaScript hey what's going on everybody
so in today's video I'm going to show you how we can create an image slider program using JavaScript you will need
some images to work with I would recommend finding three or more somewhat related images to whatever you would
like to create an image slider for once you find your images put them within your website folder and we are ready to
begin okay let's do this thing everybody so we will create a development to contain everything this development will
have a class of slider within this development we will create another
development this development will have a class of slides to contain our images within this inner div element we will
create three image elements the first image will have a class of slide with this image element I will set
the source attribute to be a relative or absolute file path let's begin with image one whatever you currently have
I'll copy the name of this image including the extension so my image has a name of
image 1.jpg and for some reason if this image can't display I'll add some alternative text with the alt attribute
let's say image number one and there is my image I will copy this image element paste it twice or
once for every image that you have then I have image two and image three let me change those we have image two and image
three so you should have three or more images depending on what pictures you're using and how many then we're going to
add some Arrow buttons for the time being that will be down at the bottom so we will create a button
element now you could use a left angle bracket let me zoom in but I think there's a better option
there's a unic code character for a left pointing angle bracket which looks like this we will use the Unicode character
of Ampersand # 100094 I think that looks better but you do you all right then let's create a
right angle bracket with another button the number is 1 95 so that will create a button with an
arrow that points to the right for the previous button the left one I will assign a class
of prev meaning previous and the next button will have a class of
next when we click on these buttons we'll call a JavaScript function we need to set the onclick vent Handler equal to
a JavaScript function for the previous button we'll call a function of prev slide meaning
previous and for the next button we will call a function of next slide to go to the next slide
okay and that is all the HTML that we need for now let's go to our CSS stylesheet we will select our class of
slider that contains everything class slider we're going to use relative positioning these elements will move
relative to their normal position using relative so we have position relative I will set a width of
100% as well as margin Auto to to Center everything horizontally now just in case if our
images are really big I will set the Overflow property to be hidden so take our class of slider select all the
images with these images I will set their width to be 100% and for now I will set the display
property to be none we don't want to display all the images right away so they should
disappear let's add a little bit of functionality before continuing let's go to our Javascript file
I'm going to create a node list of all the images within our class of slides so I will create a constant of slides which
will be a node list equals document. query selector all we will select all elements within the class of
slides that are images image elements we will also declare an index of the current slide let slide index so this
will be zero initially to start at the first slide we'll be using the set interval function set interval will
return an ID that we can work with so we will declare a variable to hold to that let
interval ID for now I'll set it to be null meaning no value okay let's declare our functions
we will have a function to initialize our slider this will populate our web
browser with the first image when we call this function then we need a function for show Slide there will be
one parameter an index an index of the next slide we would like to go
to a function for the previous slide prev slide and a function for next slide function next
slide within our function of initialized slider we will take our node list of slides at index of our current slide
index which will be zero initially I will access the class list and add a class of display slide which we still
need to work with and then we will call this function right away okay we need to build this class
still display slide we will select all image elements that have a class within their class
list of display slide if an image has this class we will set their display property to display as
a block we should get our first image if you would like although it's not necessary we could display this
image after all of the Dom content loads by using an event listener here's how if you would prefer to wait for all the Dom
content to load we can take our document add an event listener we will wait for the event of
Dom content loaded once all of the Dom content loads pass in a call back to initialize slider
so this would work too and I would say it's the preferred way rather than just calling this function initially wait for
all the Dom content to load then display our first image by calling this function within the initialized slider function
we will use the set interval function we will call the next slide function after a given amount of seconds
let's say after 5 seconds I would like to go to the next slide and display the next image whatever is next within our
node list in order for us to work with this interval this function is going to return an interval ID so we can clear it
later if we need to we will take our interval ID set it equal to the set interval
function so I am going to console.log my interval ID just to see what it is so let's save and run
everything go to console so this interval has an ID of one if I need to clear this set interval function I can
access it by its ID which is currently one and we can get rid of this line to avoid displaying an image if we
don't have one we can wrap these two lines of code within an if statement we will check if our node list
of slides its length property is greater than zero if we do have slides then display it and use the set interval
function if there's no slides no images then don't do this okay then we're going to go to the
next slide function we're going to increment slide index by one slide index
Plus+ and then we will will call the show slide function pass in our slide index after incrementing it and that is
all we need for next slide then we have the show slide function within our show slide function we will access our node
list of slides use the for each method to iterate through all of them I would like
to take each slide Arrow do this take each slide access its class list then remove a class from the class
list we will remove the class of display slide if it's time to move to the next slide we don't want to display the
current slide anymore we'll remove display slide so that it's no longer displaying as a block remove these
properties then outside of this for each method we will add display slide to the next slide then we will take our slides
at index of slide index access the class list of the next slide then we will add a new class add
the class of display slide so that it displays as a block and let's see if this works after
5 Seconds we should move to the next slide and that does in fact work let's wait again for the next
slide and that has worked too we need to reset our slide index because right now we're going out of
bounds we only have three slides in this example within our show slide function We'll add an if
statement and an lse if statement if we reach the end of our slides we need to reset the slide index
and set it back to be zero if our index that's passed in is greater than or equal to our node
list of slides length property if we reach the end we need to take our slide index and reset it to be
zero now if we go backwards with the previous button if our index is less than
zero we will take the slide index set it equal to our slides length property minus one to set it to the end
if we're on the first slide and we hit the previous button that will bring us to the last slide these images should
Loop let's see see if that does work so we're on our green car and we should go to our blue car next and that
does work our initialized slider function is done if we click on the next button we should be able to go to the
next slide right away now we have to work on the previous button and add some functionality to
that within the previous slide function we will take our slide index and decrement it with minus minus then call
the show slide function pass in the current index now we should be able to move forward and
back now if we hit the previous button CU we want to look at an image the timer is still going we'll still go to the
next slide if we would like to take some time to admire one of these images we can clear the set interval function by
using its interval ID so if somebody were to hit the previous button let's clear the timer we will use the clear
interval function we will pass in that interval ID our set interval function is still
going to move the slides forward but if I were to hit the previous button that interval is going to
stop we are done with all of our JavaScript functionality we're going to apply some CSS styling to the buttons
and even add a transition animation to the next image we will style our buttons next
within our class of slider select all buttons I will set the position property to be
absolute positions an element relative to its parent meaning the slider element with absolute positioning I will
set the top property to be 50% these buttons will then be positioned on the Y AIS at 50% meaning
the middle then I will use the transform property I will translate them on the Y AIS by minus
%. Translate Y is a function we're moving these buttons up by 50% of the element's height that will put this
button right in the middle take 50% of the height of the button Move It Up by that amount I'll increase the font size
font size 25 pixels or better yet let's do like 2 RM okay now for the background
color I'll set it to be black but I'm going to lower the alpha on it so it's transparent I'll set the alpha to be
50% and for the font color color I'll set that to be white okay you can see our two buttons
are overlapping currently I'm going to remove the border around the buttons order
none and change our cursor to be a a pointer if we hover over one of the buttons so these buttons each have a
class previous and next let's select the previous class I will set the left property to be
zero to left align it and with the next class that's the next button I will set the right property to be zero to align
it to the right I'm also going to add a little bit of padding too around the buttons let's
add some padding here padding 10 pixels by 15
pixels that looks pretty good we are going to add an animation at Key frames we need an animation name we will name
this animation fade for a fade effect from this property of opacity I can't spell today 0.5 meaning
50% two this property opacity one for 100% when a new image is displayed the opacity is going to be 50%
so it's transparent then after the animation is complete set it to be one for 100% now we just have to utilize
this animation of fade all images that have the display slide class we will set their animation name when that image is
displayed to be fade how long do we want this animation to take we will set the animation duration to be
about 1.5 seconds okay let's see if this works we should get a fade animation when each
new slide appears we can move forward and we can move
back all right everybody so that is an image slider that you can create using JavaScript HTML and
CSS hey everybody in today's video I got to introduce to you the wonderful world of callback hell callback hell is a
situation in JavaScript where callbacks are nested within other callbacks to the degree where the code is difficult to
read if you Nest too many callbacks within other callbacks your code starts to form a pyramid and it's really
difficult to work with callback hell is an old pattern to handle asynchronous functions in Java Script nowadays we
have promises as well as a sync and a wait to avoid callback hell which we'll discuss pretty soon to help us avoid
callback hell we should be familiar with what it is I'm going to create four tasks these will be functions function
task one these will be synchronous functions we don't need to use callbacks for
synchronous functions then we'll change these to be asyrus functions within task one we will
console.log task one complete okay let's copy task one paste it three times for a total of four
tasks we'll have task two task three and task
four in order from the top down we will execute task one followed by task two task
three and task four when all four tasks are complete we will console.log all tasks
complete these functions work synchronously they're all in order task one is complete then two 3 then four
then we get the final message of all tasks complete but what if these were asynchronous functions they're not going
to follow this order from the top down so to make these functions asynchronous one thing we could do we can enclose
this code within the set timeout function set timeout set timeout takes two arguments
a call back and a time in milliseconds in which to complete this code for the call back this could be a call back an
anonymous function or an arrow function I'll write an arrow function parameters Arrow do
this say the task is complete after 2,000 milliseconds let's do this with the other tasks
too so task two will be complete after 1 second 1,000 milliseconds task three will be complete
after 3,000 milliseconds now task 4 task 4 will be complete after
1,500 milliseconds okay let's try this again I need these tasks to be completed in order starting from one all the way
to four it says that the tasks are already complete then the tasks are completed in
this order task 2 task 4 Task 1 and task three so that's the problem with asynchronous code asynchronous functions
can complete at any time the rest of our program doesn't wait around for them to finish if I absolutely need these tasks
to complete an order starting with 1 then 2 3 4 each of these functions can accept a call back so we need to set up
that parameter after we say that that task is complete we will execute the call back
to the next function so let's do this with the rest of the tasks
if we need these tasks to complete an order starting with one we would take one and there's one parameter a call
back we'll pass in a call back to task two we can pass in a call back and Anonymous function or an arrow function
I like Arrow functions though parameters Arrow do this what are we going to do when task one is complete we'll call
task two task two also accepts a call back again this can be a call back an anonymous function or an arrow function
this will be an arrow function parameters Arrow do this what do we want to do when task two is complete call
task three task three also accepts a call back we'll use an arrow function parameters Arrow do this now when task
three is complete guess what we're going to do call task four task four task 4 accepts a call
back we'll do this parameters Arrow then would like to console.log all tasks complete all tasks
complete this should work now task one complete task two complete task three complete task 4
complete all tasks complete so what we've done is use callback hell it's where you're nesting callbacks inside of
other callbacks if you have a lot of tasks to complete an order it can become very unman manageable hey this is bro
from the future one thing that I wanted to mention is that four levels of callbacks isn't too unreasonable but
when you add additional levels on top of that that's when you're starting to approach the levels of callback hell
where the code can become unmanageable and really difficult to read what I've written in this video isn't too
unreasonable but hopefully you can see how we've come to start that pyramid pattern that is all all right everybody
so that is callback hell it's a situation in JavaScript where callbacks are nested with other callback where the
code is difficult to read it's an old pattern to handle asynchronous functions in some upcoming videos we'll be
discussing promises as well as a sync and a wait to avoid callback hell and well everybody that is callback hell and
why you should avoid it in JavaScript what's going on everybody so in today's video I got to talk about
promises in JavaScript A promise is an object an object that manages asynchronous operations such as querying
a database space fetching a file Gathering resources those you could consider asynchronous operations they
can take an indeterminate amount of time you can wrap a promise object around some asynchronous code the promise
object promises to return a value that promise object will be pending then either that promise will be resolved if
the task completed successfully or rejected if it failed for some reason maybe the promise couldn't fetch that
file resolved if it did A promise is an object will create a new promise object with new prom
then pass into a function usually you see this is an arrow function there's two parameters resolve and reject Arrow
then do some asynchronous code so in this demonstration we're going to be doing some chores if you live with your
parents maybe your mom asked you to do these chores or with the roommate these are the tasks you need to do or your
significant other wants you to do these tasks anyways we have some chores to do we have to walk the dog clean the
kitchen and take out the trash I'll create functions for each of these chores first we'll start by using
callbacks then I'll demonstrate the use of promises and how they're helpful so let's create a function to walk dog to
make this asynchronous I'm going to add a set timeout function this takes a call back and an
amount of time in milliseconds to complete this code let's say walking the dog takes 1,500 milliseconds what code
would we'd like to perform let's write an arrow function to keep it simple parameters Arrow do this let's
console.log after completing this chore you walk the dog okay that'll be the first function
let's create a function to clean the kitchen function clean kitchen this will take a long time 2,500 milliseconds
let's say when we complete this task we will print you clean the kitchen and a third
function take out trash you take out the trash taking out the trash it's really
quick it takes half a second 500 milliseconds if I need to do these chores in order I would need to use some
callbacks after walking the dog we will call a call back to clean kitchen after we clean the kitchen we will take out
the trash we need to modify these functions so that they accept some call backs after our code is complete we will
invoke the call back call the Callback so let's add that parameter to each of these
functions now if we want to call all these functions in order we would have to start using call back hell which we
learned about out in the last video so first I would like to walk the dog I will call that function pass and a call
back but we'll use an arrow function then we will clean the kitchen pass in a call back I'll use an arrow
function take out trash and we'll pass in a call back to do this when we complete all the
chores console.log you finished all the chores okay let's see if this
works you walk the dog you clean the kitchen you take out the trash you finished all the
chores if we have a lot of callbacks to work with we'll end up going to call back hell you don't want to go to call
back hell so what we'll use instead are promises with all of this asynchronous code we'll wrap it within a promise by
using a promise we don't need callbacks instead of using callbacks we'll use method chaining we'll method chain our
Pro promises here's how how we'll modify these functions is that at the end of each function we will return an object
return a new promise return a new promise object and follow this formula we have two parameters resolve and
reject resolve reject Arrow do this asynchronous code within an arrow function take all of the
asynchronous code cut it place it within the promise our promise promises to return a value it's either going to be
resolved or rejected we're going to modify this function we don't need to work with call backs anymore we can get
rid of those get rid of the parameter and the portion of the code where we call the call back if we would like to
display a message when the promise resolves when it finishes successfully we will instead call the resolve
parameter it's a function this message is the value the argument that we're passing in after you finish walking the
dog here's your completion message when the promise resolves let's modify the rest of the functions so that they use
promises we will return a new promise two parameters resolve
reject Arrow do this asynchronous code let's cut our current asynchronous code paste it remove the call back
parameter we don't need it anymore and we don't need to call the call back when this promise
resolves pass along this message you clean the kitchen let's do this with take out
trash we will return a new promise two parameters resolve reject Arrow do this cut the asynchronous code
paste it within the promise remove the call back and where we call the call back when we resolve this promise pass
along this message we no longer need to use callback hell instead we're going to use method chaining first we're going to
walk the dog clean the kitchen and then take out the trash in that order we will call the walk dog
function and then we're going to Method chain follow this with the then method walk the dog then what is what
we're saying the walk dog function does provide a value parameter this message we can use that message for something
that's going to be stored within value that's going to be the parameter that's provided to us take the value let's
print it console.log my value so when I run this program we should only be walking the
dog you walk the dog and nothing else looks like I misspelled resolve as resolves there after walking the dog I
would like to clean the kitchen so I need to call that function next within our Arrow function we'll write more than
one statement we need to enclose this within a set of curly braces print our value and then do this function
return clean kitchen and then call it we'll add another then method then take the value provided by
clean kitchen that will be this one take that value
arrow console.log that value you walk the
dog you clean the kitchen then we'll take out the trash at the end we'll add another statement to this
then method we will return take out trash invoke this
method then we will take the value provided to us when it resolves this value
do this code console.log that
value you walk the dog you clean the kitchen you take out the trash so after taking out the trash
that's our last chore let's add another line of code after displaying you take out the
trash let's console.log you finish all the
chores you walk the dog you clean the kitchen you take out the trash you finished all the
chores by Method chaining then methods it's a lot easier to write than nesting call backs now sometimes with
asynchronous functions depending on the task the task May Fail let's say we're trying to locate a resource a file if we
can't locate that file and we're using promises we don't want to resolve that promise
because we couldn't locate that file instead we want to reject that's what happens when an asynchronous function
fails to do something when inside a promise so let's change our functions around within set timeout let's create a
variable const dog walked did we accomplish this this will be true or false we'll use an if statement if dog
walked then we will resolve it if we walked the dog else we will
reject we'll pass in a different value you didn't walk the dog okay let's do this with the other
functions let's create a constant of kitchen cleaned equals true if our kitchen is cleaned if that
is true we will resolve this promise you clean the kitchen else let's reject pass along
this message you didn't clean the
kitchen and lastly take out trash const trash taken out let's set that to be
true if the trash is taken out resolve the promise else we will
reject you didn't take out the trash if a promise might reject there's
one more method we need to add to the end of this chain we need to add a catch method to catch any
errors this will catch any Rejects this is similar to error handling we'll be provided with one value an error Arrow
do this let's console.log or even console. error the message provided to us with
reject that's what the error is going to be we'll successfully walk the dog that will be true and cleaning the kitchen
will be true but taking the trash out will be false we weren't able to complete this chore these are the
results you walk the dog you clean the kitchen you didn't
take out the trash how dare you we'll keep on completing these tasks until we fail at one of
them so if walking the dog was false that was our first task this first promise was rejected we
don't even attempt to resolve these other promises all right everybody so those are promises they're an object
that manages asynchronous operations you can wrap a promise object around some asynchronous code these promise objects
promise to return a value they will be pending until they complete then they'll either be resolved if that task
completed successfully or rejected if it failed for some reason and well everybody those are promises in
JavaScript hey everybody so today I got to talk about a sync and a weight in JavaScript a sync and a waight are two
keywords by using these two keywords together they allow you to write asynchronous code in a synchronous
manner a sync makes a function return a promise a wait makes an async function wait for a promise we'll discuss async
first in this sample program from the last topic we have some chores to do we have to walk the dog clean the kitchen
and take out the trash each of these functions returns a promise a promise that can either resolve or reject based
on the code that's written if the dog is walked if if that's true resolve if it's false reject a function can be declared
with a sync a function declared with a sync will return a promise however that promise that's returned doesn't resolve
or reject in a way you could say it's an empty promise if I were to run this code this is what
happens uncaught reference error resolve is not defined if an asynchronous function returns a promise that either
needs to resolve or reject adding a sync to it really doesn't benefit us a sync works together with a weight by using
these two keywords together when calling all of these asynchronous functions in order we don't need to Method chain then
statements there's a more synchronous manner in which we can write the same code but we'll need to contain it all
within an async function async function we'll create a function to do chores then we will need to call this
function somewhere let's do so right here first we need to walk the dog walk the
dog returns a promise that's where the await keyword comes in a wait makes an async function
wait for a promise before continuing we're going to create a constant of walk dog result equals use the await
keyword await walk dog then we will console.log the walk dog
result you walk the dog now let's do this with clean kitchen we're going to be writing this code in a synchronous
manner line by line linearly we will create a constant for clean kitchen result equals await the
next promise await clean kitchen then console.log clean kitchen result let me
close this you walk the dog you clean the
kitchen and last we have take out trash const takeout trash result equals a wait take out the
trash then console.log the result you walk the
dog you clean the kitchen you take out the trash let's add one more line when we finish everything one more line of
code you you finished all the chores you walk the dog you clean the kitchen you take out the trash you finished all the
chores let me show you what happens if we attempt to use a weight within a function not declared with a
sync uncaught syntax error a weight is only valid in async functions that's why a weight depends on async a weight makes
an async function wait for a promise before continuing now if your promises can reject let's say that dog walked is
false uncaught in promise you didn't walk the dog we'll surround all of this code within a tri block then catch any
errors catch one parameter of error we can console.log or console .
error the error you didn't walk the dog all right everybody so that is a
sync and a wait a sync makes a function return a promise a wait makes an async function wait for a promise by using
these two keywords together we can write asynchronous code in a synchronous Manner and well everybody that is a sync
and a wait in JavaScript what's up everybody so today I got to talk about Json files using
JavaScript Json means JavaScript object notation it's a data interchange format most of the time it's used for
exchanging data between a server and a web application they can have a few different formats usually you'll see a
Json file as an object an object made up of key value pairs or you may see them as an array an array of values or some
combination of both you can have an object where one of the values is an array and or you could have an array of
objects like this just to understand the format we'll create a new Json file let's go to our website folder create a
new file we'll create an array of names the file extension is Json we'll Begin by writing an array
with a set of straight brackets let's add a few names just some first names SpongeBob
Patrick Squidward Sandy this is a valid Json format let's create a new Json file just for a single
person this will be an object new file person. Json this time we will create a single
object this object will have key value pairs we will have a name key and a value of
SpongeBob each key value pair is going to be comma separated SpongeBob will have an age
key of 30 and a Boolean of is employed is SpongeBob currently employed that will
be true this is also a valid format our Json file contains one object an object
made up of key value pairs objects can even have arrays as one of their values we will create an array of
hobbies what what does SpongeBob like to do this will be an array
jellyfishing karate and cooking let's create one more Json
file we will create a Json file for people this will be an array of objects people.
Json we're going to create an array of objects within this array we'll create one
object what key value pairs should this object have we'll just reuse what we have for SpongeBob excluding the array
to keep it simple okay that will be the first object let's create another object we
need another set of curly braces the second object will have a name property of Patrick age 34 is
employed will be false the next object this will be for Squidward age
50 is a employed true he works at the Crusty Crab one last object name Sandy age
27 is employed false Sandy is self-employed all right we have an array of objects each object can have its own
unique key value pairs so let's close out of these Json files but we'll hold on to
them so Json formats they're one long string to represent that object or array using the stringify method of Json we
can convert a JavaScript object or an array into a Json string so let's copy what we have for
names I will create a constant of names equals that array we'll convert it to a Json
string const Json string equals access Json Json is a built-in object that's provided to us to work with Json files
we will use the stringify method then pass in our array or our object currently if I were to
console.log my names before stringifying it here's the result we have an array of strings to
work with after using the stringify method on names we'll be given one long string to represent this array if I was
to use this on an object let's copy what we have for person I will create a const of person this
will be an object I'll just paste what I have for SpongeBob first let's console.log person here's my person
object then let's stringify it and display the Json string Json files work with one long
string that represents an object or an array let's stringify our people it's an array of objects
const people equals paste what we have let me show you what happens when I console.log people before stringifying
it we have an array of objects each object has its own key value
pairs then if I was to stringify it here's the result one extremely long
string now we'll use parse parse converts a Json string to a JavaScript object so let me reformat
these to convert these objects or arrays into a string we can surround them with a pair of back
ticks so let's rename these let's say Json names Json
person then Json people these objects and arrays are all in a Json format to convert them to
their original form we can use the parse method of Json I will create a constant of par data equals Json
parse pass in our data of Json names and then let's console.log let me show you Json names
first before parsing it we have a string representation of an array but after parsing it it becomes a JavaScript array
let's do this with our string representation of an object Json person normally it looks like this and then
after parsing it we have a JavaScript object and then Json people it's an array of
objects then we'll parse it and here's the result an array of objects now I'm going to show you how we
can fetch a Json file we'll talk about fetch more in the next topic fetch is a function as an argument we can pass in a
relative or absolute file path or a URL we'll discuss that in the next topic I would like to get my Json file
of let's go with person so I will list the relative file path these files are right next to each
other I just need to type person. Json fetch returns a promise we will follow this with the then method then do this
we'll be provided with a response object take our response Arrow do this we will take our response object convert
it to a Json format using the Json method then let's display what we have currently then take the value arrow
console.log that value let's see what we have yep there's SpongeBob we have successfully fetched a
Json file let's do this with our array of names we have an array of strings of
first names and people people. Json we have an array of objects one object for each
person if you would like to iterate through all the objects let's rename value as values we'll use the built-in
for each method of arrays values. for each take each value Arrow do this console.log each
value now we're iterating through and printing each object if you would like some of the specific properties like
make name follow the value with name SpongeBob Patrick Squidward Sandy or age or is
employed oh and another thing that I'm forgetting be sure to add a catch method to catch any errors just in case we
can't fetch this Json file for some reason console.log or console. error the error
message we'll talk about fetch more in the next topic all right everybody so those are Json files Json means
JavaScript object notation it's a data interchange format it's mostly used for exchanging data between a server and a
web application Json files are usually objects or an array or some combination of both to convert a Json object to a
string you can use the stringify method to convert a Json string to an object you can use the parse method to fetch a
Json file you can use the fetch function which we'll talk about next and get more in depth with and well everybody those
are Json files using JavaScript well it's going on everybody so in today's video I'm going to show
you how we can fetch data from an API using JavaScript and at the end of this video we're going to create a project
where we can fetch some images of Pokémon depending on what Pokemon you type in so sit back relax and enjoy the
show all right people so we got to talk about fetch fetch in JavaScript is a function it's used for making HTTP
requests to fetch resources including but not limited to Json styled data images files resources of that nature
the fetch function simplifies asynchronous data fetching it's used for interacting with apis to retrieve and
send data asynchronously over the web fetch has two arguments a URL of the resource and an object an object of
options I won't be talking about options in this video that's more advanced JavaScript one of what you may see is a
method property the default is get to get a resource you can use post to send some data put to replace some data and
delete to delete some data so the default is get but we don't need to explicitly state that we'll just be
focusing on getting data with only a URL to fetch something we have to use the fetch function and pass in a URL what I
thought we could do for this video is fetch some Pokemon data from the Pokémon API if you want to follow along you can
go to this URL I would like to fetch some data on Pikachu because everybody knows about
Pikachu and here's some of the data on Pikachu this resource is one gigantic object Pikachu has a name an ID number a
type Pikachu's an electric type there's stats such as his attack power HP there's even image Sprite which we'll
work with later we will copy this URL and paste it within the fetch function we will pass in a string
representation of this URL the fetch function is promise-based it's either going to resolve or reject so we should
add a then and a catch method to catch any errors error Arrow do this let's console
the error if there's an error once the promise resolves will be provided with an object a response object take our
response object Arrow do this for the time being let's console.log our response just to see
what it is exactly so here's our response object the body contains the data we're
looking for for Pikachu this response object has a status code of 200 that means it's okay here's where you may see
that status code of 404 if you can't locate a resource it has an okay property if fetching this resource was
okay this is going to be true if not it's false there's also a URL here too now our next step is to convert it to a
readable format there's a few different methods there's array buffer blob text and Json these are all methods we're
interested in the Json method in this example so our next step is to take our response object convert it to Json using
the Json method this is also promise based once this promise resolves let's follow this
with a then method then take the data our Json data that's going to be returned to
us Arrow do this let's console.log my data just to see what it is so after fetching data on Pikachu convert the
response object to a Json format and here's my data for Pikachu we have a name an ID Pikachu stats such as
his HP and attack and wait and many more things with this Json data you can access one of the properties I would
like just Pikachu's name data. name Pikachu data dot weight how much does Pikachu way 60 60 units of something
whatever unit of measurement they use in Anto what is Pikachu's ID 25 near the end of this video we're going to fetch
the Sprites of the Pokémon now for some reason if we try and access a Pokemon that doesn't exist as of the filming of
this video SpongeBob is still not a Pokemon we get a status code of 404 meaning we could not find this resource
SpongeBob is not a Pokemon unfortunately so even if we can't locate a resource our promise is still going to resolve
it's not going to reject we need to check to see if our response is not okay let me demonstrate I will console.log my
response object here's my response object it is not okay your response will be okay if
the status is within the 200 range since we have a status of 404 we couldn't locate this resource okay is false we're
going to throw an error if our property of okay is false within our first then method we'll write a few statements we
need a set of angle brackets before continuing let's check to see if our response access the okay property then
use the not logical operator if our response is not okay if it's false we're going to throw a new
error and then catch it using the catch method we can write a custom message let's say something like could not fetch
resource if our resource is okay we won't execute this code otherwise we will return our response object in a
Json format let's try and retrieve Pokemon data on
SpongeBob okay we have an error but we have caught this error using the catch method error could not fetch resource
then let's get data on Pikachu again and there Pikachu and his ID number if you would prefer to use a sync
and a weight here's how let's delete all this we will create an async function so that we can use a weight within it I
will declare a function to fetch data no parameters do all this we will create a try and catch
block try and catch catch has one parameter an error if we receive an error let's console. error
the error within our Tri block we will create a constant of
response the fetch function is going to return an object a response object we will
await our promise that's returned by fetch then we need to get that URL again let's get data on a different
Pokémon another Pokemon that I like is tyion honestly I think tyion is my favorite
Pokemon all right here's the stats for tyion I'm going to copy this URL pass it to the fetch function as a
string once the promise for fetch resolves we have to see if the response is okay we'll use an if
statement if our response object is the okay property not okay if our response is not okay if we can't
locate this resource then we will throw a new error let's say could not fetch
resource if our response is okay we will create a constant for our data equals await take our response and
convert it to Json this also returns a promise that's why we're using a wait then we will
console.log our data and then we have to call the fetch data function because I forgot to do
that call fetch data and here's the stats for tyion Name tyion ID 157 tyion is a fire
type that's how to use a sync and a weight to fetch a resource now that we know what we're
doing we're going to create a text box and a button to search a Pokemon and pull up a Sprite of that Pokemon and
display it so going to our HTML file we will create an input element with the type attribute of text
because it's a text box I will set the ID of this input element to be Pokemon name
it's a little small right now we haven't applied any CSS I will add a
placeholder of enter Pokemon name then we need a button I will create a button
element with text of fetch Pokemon I will set the onclick event
handler equal to a JavaScript function let's call that function a fetch data then I will add a
break after fetching some Pokemon data we have an image to work with I will set the source currently to be an empty
string I will display some alternative text if we can't display the image of Pokemon
Sprite and I will give this element an ID of Pokemon Sprite to not display the image
currently we can access the style access the display property and set it to be none then if we do want to display it we
can set display to be a block let's go to our Javascript file within our Tri block we will create
a constant of Pokemon name equals document. getet element by ID the ID
that I'm selecting is Pokemon name access the value of this input
element now if somebody types an uppercase characters I'll take the value make all
the letters lowercase I will method chain the two lowercase method two lowercase
method with our fetch function we're going to use a template string with a pair of back ticks for the Pokémon's
name we will use a placeholder and pass in our Pokemon name variable so now when I type in a
Pokemon's name like Bulbasaur we should get data on that Pokemon if it exists so let's go to
inspect console and here's data on Bulbasaur Bulbasaur's ID is one Bulbasaur is a grass type
and I think he's a poison type too if I'm not mistaken this Json data also has Sprites
images of each Pokemon we're going to fetch the front default so we don't need console.log
anymore we'll create a constant of Pokemon Sprite to get that image equals take our
data access the Sprites property get the front default Sprite then we will get our image
element this one that has an ID of Pokemon Sprite const image
element equals document. getet element by ID the ID that I'm getting is Pokemon Sprite we will change the CSS of this
element take our image element access its source attribute right now it's currently empty our source is an
empty string set the source equal to our Pokemon Sprite this is a
constant then we will take our image element access the style attribute access the display
property and set it equal to be a block because right now it's none now when I type in a Pokémon's name
like Charizard and fetch that Pokémon we get the image of that Pokémon it is a little small however it is a
Sprite Sprites tend to be very small or we can get meww or whatever other Pokemon you can
think of I think there's like over a thousand Now where's tyion there's tyion all right everybody
so that is how to fetch data from an API you got to use the fetch function it's is used for making HTTP requests to
fetch resources you can fetch Json style data images files the fetch function simplifies asynchronous data fetching
it's used for interacting with apis to retrieve and send data asynchronously over the web and well everybody that is
how to fetch data from an API using JavaScript hey everybody so in today's video we're going to create a weather
app that fetches data from an API you can look up any didn't get the weather if that sounds good to you then sit back
relax and enjoy the show if you would like to follow along you will need your own API key the API that we'll be using
is openweathermap.org you do need to sign up for an account though it is free to sign up for an account you can go to
sign in if you're currently not registered you can create an account for free once you're signed in you'll need
an API key go to my API Keys it may take you some time to get an API key generated for you mine took about 15
minutes and once you get it make sure it's active we will need that API key about 20 minutes into this topic
hopefully for you by then it'll be generated okay let's do this everybody we will Begin by creating a form element
the form element will have a class of weather form our form element is going to have an input element and a
button within this input element we'll type in the name of the city we would like to retrieve the weather data
4 so the type of this input element is going to be text for some text the class will be City input so a
user can type in the city and we'll add a placeholder let me zoom in a little so you can see
it the placeholder will equal enter City then we'll need a button let's
create a button element with text of get weather the type of this button will be submit it's the submit button for our
form after retrieving the weather data we'll display the weather data in a card format like a Pokemon or Yu-Gi-Oh card
so we will create a div elopement with a class of card but before applying some CSS we
should at least add some placeholder elements so we can style them and see the changes for the time being let's
create an H1 element we will be deleting these elements later so don't get too attached I will set the class of this
element to be City display We'll add a sample City let's say Miami or pick a city if you're
choosing then I will create a paragraph element the class will be temp display meaning temperature let's say the
temperature is 90° fah or pick something in celsius if you're on Windows to add a degree symbol you can hold alt then type
0176 Miami is going to be 90° F then we'll create a paragraph element for the
humidity class equals humidity
display for the text let's say humidity colon space then a percentage 75%
then we need a description of the weather this will be another paragraph element the class will equal description
display desk meaning description for the description let's say clear skies I'll also display an emoji
depending on what the weather is the class will be weather Emoji I'll use a
sun for some reason if we can't display the weather data such as if we can't locate
a city let's add the following paragraph the class of this element will be error
display We'll add the text of please enter a city that is all the HTML that we need
for now we're going to apply some CSS styling next so now let's head to our CSS stylesheet we are going to select
the body of document select a font family I will pick Ariel with a backup of s
serif I'll change the background color of the body background color pick a color I'm going to use hsl
values I will set the lightness to be 95% so it's a light gray color I will set all margin around the body to be
zero then I'll use flexbox to display the element elements display Flex the flex direction will be a column
to arrange all the elements in a column then align item Center to horizontally align all the elements
align item center now we'll select the class of weather form that'll be this form that has an input element and a
button all we'll do is add a little bit of margin around the entire form 20 pixels
then we'll select our city input that's going to be the text box class of City
input I will add some padding of 10 pixels let me zoom out to
100% increase the font size to 2 RM set the font weight to be
bold I'll add a border two pixel solid and pick a
color but all lower the alpha so it's transparent to 30% there's our border
currently border radius around the corners let's do 10 pixels add some margin of 10 pixels
that'll separate this element from the button and set a width of 300 pixels okay let's style the button next
okay we are going to select all buttons that have an attribute where the type equals
submit so that's going to be for our submit button that says get weather let me scroll down okay I'm going to add
some padding around the button 10 pixels by 20 pixels I'll set the font weight to be
bold I'll increase the font size to be to R pick a background color for the button
I'll pick something green but I'll use hsl values I've already pre-picked a color
let's go with 122 the 39% and
50% that's a good shade of green I will set the color to be white for the font
color remove the border border none and Border radius 5 pixels to round the
corners then when we hover our cursor over the button I would like it to be a pointer and that does work when we hover
a cursor over the button we'll use the hover Pudo class to change the background color so let's take our
button for the type attribute is submit access the hover sudo class take our background color make it a little
bit darker I'll bring down the lightness by 10% so it's at 40% so that does in fact
work okay then we're going to select our card class that contains all the weather data so we will select the class of
card for the background we're going to do something a little bit different we're going to use a linear gradient
instead of selecting the background color we will select the background I will use the linear
gradient function there's three arguments think of a linear gradient as a slow
transition between two colors we need an angle in degrees we'll say 180° for now then a color let's pick something
blue and orange I'm going to pick some colors that look a little bit
better so for blue let's set the Hue to be 210 100% for the saturation and the
lightness will be 75% that's a good shade of blue and for orange we'll use another hsl
value for the Hue I'll say 40% the saturation will be 100% And The lightness will be
75% so I'm hoping with this linear gradient the background color looks kind of like a sunrise or a sunset once we
have our background I will add some padding of 50 pixels I'll add a box Shadow to this
card we'll add a vertical and horizontal offset of two pixels each and a blur effect where the radius is 5
pixels then we'll pick a color I'm just going to lower the alpha to 50% not
bad this gives our card a 3D pop effect I will set a minimum width of this card to be 300
pixels then we have to align everything within it I'll use flex box because I like Flex box display
Flex Flex direction will be a column and align items Center to horizontally
align the items there we go then we'll select all H1 elements that's going to be our city
name select all H1 elements increase the font size to be 3.5
RM I'll remove any margin from the top margin top will be zero and add margin to the
bottom of 25 pixels then we'll select all paragraphs that's going to be everything
underneath our city select all paragraphs increase the font size to 1.5
RM there's a lot of natural margin between the paragraphs let's set all margin to be
zero to see what it looks like okay let's add a little bit of margin five pixels on the top and bottom zero margin
on the sides that's a lot better we'll select the city display and the temperature display we're going to be
selecting two classes City display comma our temp display take these two classes apply the
following properties you know what for our font size let's set that to be 3.5 RM we can honestly remove that from
H1 for the font weight I will set that to be bold for the color I'll make the color a little
transparent I'll set the alpha down to 75% so that our city and our temperature they're both going to be
transparent then I'll add some margin to the bottom margin bottom 25
pixels okay let's select our humidity display class humidity display set the font weight to
be bold and add some margin to the bottom of 25 pixels then we'll select our description
display which we shortened to desk display for the font style I will set it to be
italic and the font weight will be bold I'll increase the font size to 2
RM then we'll select our weather Emoji so class weather Emoji remove all margin around the Emoji margin zero then we'll
increase the font size of the Emoji the size will be 7.5 RM so it's kind of
big then if for some reason we display an error we'll display this text so this class is error
display I'll set the font size to be 2.5 RM the font weight will be bold I'll set the color to be something
transparent I'll lower the alpha to 75% okay that is all the CSS that we need let's go back to our HTML file we
can delete everything within the card class we just wanted to see what it would look
like with the elements populated with our card element I will set the style attribute to be take the display
property set it to be none we don't want to display the card at all until we get the weather data until it's returned to
us our HTML is done our CSS is done then we're ready to add some JavaScript functionality we'll declare our
constants that we need const weather form equals document dot now since we're not working
with IDs we can't get element by ID we're working with classes we can use Query selector or query selector all so
I'm going to use Query selector this will return the first element in this class we only have one element with this
class class weather form we'll store a reference to it const City in
input equals document. query selector we are selecting the class of
City input that's going to be this text box const card our card is what contains all the weather
data document. query selector select the class of card and
give me the first element now we'll need that API key const API key
equals now here's my API key please don't try and use this one specifically I will be deactivating it at the end of
this video hopefully by now you should have that API key given to you first we'll take our weather
form We'll add an event listener this is our form the text element and the submit button
when we click on this button the event type is going to be submit after we attempt to submit this form we'll do the
following code we'll have one parameter an event that's going to be provided to us Arrow do this we'll fill this in
later we'll declare our functions that we need we will need an async
function to get weather data there will be one parameter a city that's going to be passed
in then we'll need a function to display weather info there will be one parameter data the data will be in a
Json like format we'll create a function to get weather
Emoji based on what the weather is there will be one parameter a a weather ID then we'll create a function to
display to the screen any errors if there are any function display error there will be one parameter a
message a message to be displayed to the window within our event listener once we have a submit event
once we click the button forms do have a default Behavior where they'll refresh the page we would like to prevent that
so let's take our event use the prevent default method to prevent the default behavior for a form we don't want to
refresh the page then we'll have to get the city the value within this text box const City equals take the city input
access the value store it within this variable it should be a string we'll use an if statement if
City if there's a value within here this this will be true we can use it within an if
statement if there is a city do this else we'll call the display error function else we will display an
error we will pass along the message to please enter a city let's fill in the display error
function we want to be sure that it works before continuing the display error function is at the bottom
will be provided with a message to display we will create a constant of error
display equals document now we'll create an element create element we will create a
paragraph then we'll need to change the text content of this element error display access the text
content set it equal to be our message then we're going to add the class of error display we would like
these CSS properties take our error display element access the class list then we
will add a class we will add the CSS class of error display then we will take our card
element which normally displays the weather data take our card reset the text content if there is something there
we'll set it to be an empty string so normally with our card the display is set to none we'll set the display to be
a block or even Flex access our card access the style access the display and I will set the
display to be Flex to display it we will take our card we will append a child element append child we will
append this par paragraph of error display to the card now if I were to not type in anything and just press get
weather we get this error message please enter a city to our card I'm just going to round
the corners to make it look better border radius let's do 10 pixels that's better okay moving on if
we do have a city if there's text within here we will try some code because it might cause some errors we will catch
any errors that happen we have one parameter of error if there's an error we can console.log or console. error the
error then let's call our display error function we'll pass along the error and display
it now we need to get the weather data within our Tri block we will create a constant of weather data equals now we
need to await get weather data function and pass in our city so with the weight we can
only use a weight within an async function since we're within an arrow function we could declare this Arrow
function as an a sync function so let's preedee our event parameter with a sync so that we can use a
weight we're going to wait for this function to return the weather data once we receive our weather data we will call
the display weather info function and pass along that data the weather data okay this function is complete once
you've typed everything in I'm going to close this function and we can close our display
error function too now once we want to get our weather data after we have a
city now we actually need to fetch the weather data we'll have to create a URL we'll create a constant of API
URL this is what we'll pass to the fetch function we will use a template string be sure to use a pair of back
ticks we'll need to get the following URL at this web page we need to find the API call where
we can pass in a city name we can copy this within our template string we'll paste it
we'll replace the city name with the placeholder and use our city variable for the API key we'll use a
placeholder pass in the API key this is what we'll pass to the fetch function we will create a response const
response equals a weight we can use a weight because we're with within an async function we will
fetch our API URL once we have a response let's check our response let's console.log our response
just to see what it is okay I will type in the city of Miami get weather our data should be within
console.log here's our response it has a status of 200 and it's okay we need to check to see if our
response is not okay what if we couldn't retrieve the data I'll make up some gibberish
City let's go to inspect console we have a response status 404 the response is not okay we'll write an
if statement if our response is not
okay we will throw a new error and pass along the this message could not fetch weather
data else if our response is okay we will return the response and we will
await our response convert it to a Json format using the Json method so at the end of this function
return an object that's in a Json like format this data is going to be returned to our event
listener after we get our weather data we need to display it we'll work on the display weather info function next this
one let's console.log the data we receive I will type in Miami so it looks like that
worked we have a name of Miami for the city we have the weather which is an array it's an an array of objects we
have coordinates clouds pretty much anything you can think of regarding the weather let's get the name within main
there is temperature the temperature will be in kelvin we need to convert it I'll get the humidity within weather
it's an array of objects we will get the description overcast clouds and this ID eventually we'll use the ID to return an
emoji there's different weather codes I'll explain that later so we're going to use some object
destructuring const use object destructuring with a set AC krly brackets we will access the name
property and create a variable of city city will be Miami in this case then we will access main main is a property that
contains an array take main use object destructuring again now we're within a nested object I
would like the temp and the humidity then let's select our weather so whether it's an array of
objects we'll have to use array destructuring followed by object destructuring give me the
description and the ID we have to set this all equal to data to use
destructuring and let me organize this to make it look nice our data is one gigantic object
that has nested objects and nested arrays so after destructuring we'll have these variables the city the temperature
the humidity a description of the weather and an ID for the weather code now we can use these like
variables so with our card currently we're not displaying it now I would like to to display
it we are going to take our card set the text content to be an empty string if there's already some text here we would
like to reset it such as if there was an error message take our card access its style
set the display property to be Flex for Flex box just to be sure that this is working
I'm going to get the weather without entering a city after we do type in a city it should
reset that's good that's what we wanted or if we make up some gibberish we have that error could not fetch weather data
but then if we type in something legitimate and get the weather it'll reset that's what we would
like okay now we have to create the elements the elements that we previously deleted from the div element we need to
recreate those we will create a constant for City display to display the
city document. create element our city display was an H1 element let's copy this line of code and paste it a few
times four additional times we have City display temp display for the temperature that was a paragraph
element humidity display humidity display that was also a paragraph element
a description display which we shortened to desk desk display that was also a
paragraph and a weather Emoji weather emoji and that was also a paragraph okay now we need to change the
text content of each of these elements but they're empty so to say let's take the text content of our city
display. text content property equals our city variable that we
destructured okay let's see if that works I'll type in a city get weather oh and then we need to append
it take our card append child we will append the city display element let's try that
again type in Miami get the weather that should display Miami let's try Dallas
Texas Dallas Oh and before displaying it we need to add the class list the CSS class
for the city display after adding the text content we will take our city display access its class list add the
class the CSS class of City display so then when we type in a city we should have that CSS styling all right now we
have to add the temperature following the same format we will take our temp display
access the text content equals I'll use a template string with a pair of back ticks I'll add a
placeholder pass in our temperature add a degree symbol you can hold alt then type 0176 for a degree symbol now this
is normally in kelvin actually I don't think Kelvin uses the degree symbol but we'll be changing that
momentarily take our temperature display access its class list add the following class add the CSS class class
of temp display then we have to append the element to the card element take our
card we will append a child element of temperature display so now we should see the
temperature but it's going to be in kelvin we have the city and the temperature for the temperature if you
would like Celsius let's use deg CI you have to subtract from the temperature 200
17315 okay but now we should probably round it so let's enclose this equation with a set of parentheses follow this
with the two fixed method of numbers to round it to one decimal place 15.6 de C if you would like a
Fahrenheit temperature this is the formula take our temp in Kelvin minus 273.15 we will multiply this by 9 / 5
plus 32 so let's enclose this all within a set of
parentheses so now we should get that temperature but in Fahrenheit oh and then add F to the
end 60° F then we'll get the humidity so take our humidity display element that we created access the text content set
it equal to be a template string using a pair of back ticks let's add the word humidity coin space add a placeholder
display our humidity variable We'll add the class list of humidity
display humidity display access its class list add the following class of humidity
display then we have to append the element to the card element card. append child append our humidity
display so we should get the humidity Miami 60° fhe humidity 81 let's add
percent 81% yep that does work then we'll add the description a description of the
weather take the element of description display access the text content equals the
description then add the CSS class to the class list for this element description display access the class
list add the following class of description display then add the element card.
append child we will append our description display let's type in Miami get the
weather currently in Miami there's overcast clouds now we have to get an emoji based on the weather with our
element of weather Emoji we will access the text content equals we will call the get weather Emoji function but we have
to pass in a weather ID so we will pass in the ID variable that we receive from
data once we get our weather Emoji we'll work on that momentarily we'll take our element of weather Emoji
access the class list add the following CSS class of weather
Emoji then append it to the card card. append child we will append our weather Emoji all right now before we canest it
we need to fill in the get weather emoi function so with this open Weather AI there are different group codes so our
weather ID is going to be either within the 200 range meaning a thunderstorm the 300 range means drizzle 500 is rain 600
is snow 700 is atmosphere such as Mist smoke or even a tornado 800 exactly is a clear sky anything greater than 800
means clouds so our weather ID is going to be one of these codes so we're going to use
a switch we will examine the Boolean value of true does the value of true match one
of these cases we'll have a case for group 200 if our weather ID that we pass in is greater than or equal to 200
00 and the weather ID is less than 300 that means there's a
thunderstorm we will return an emoji a thunderstorm Emoji
thunderstorm I don't like the look at that one that's
better okay group 300 is a drizzle so let's copy this case because I don't feel like retyping
it if our weather ID is greater than or equal to 300 and less than 400 that means we have a
drizzle we'll just add an emoji of a raining Cloud so group 500 is also rain but it's
a heavier rain so let's copy this case paste it if our weather is greater than or
equal to 500 and less than 600 will return rain as well group 600 is
snow if our weather ID is greater than or equal to 600 and less than 700 we will return a snowflake meaning
snow then we have group 700 if our weather ID is greater than or
equal to 700 and less than 800 we'll return some fog
Emoji 800 exactly means a clear sky we can display the sun if our weather ID is strictly equal
to 800 exactly we'll return a sun emoji anything within
the 800 range means clouds so if our weather ID is greater than or equal to 801 800
means clear sky so with this group code it only goes up to
809 if our weather ID is less than 810 return a cloud then let's add a default in case
we get a weird weather code default
return I don't know a question mark we get some unknown weather phenomena UFOs or something I don't know
okay and I think that should be everything let's close out of this close out of these
functions and now if I were to type in Miami and get the weather in Miami it is 60.3 De F humidity 81% there's overcast
clouds and we get a cloud Emoji because it's cloudy let's try Dallas we have a clear sky 45° fah
humidity 63% clear sky and we get a sun emoji all right everybody so that is a weather app
that you can make using Java JavaScript HTML and CSS
To set up a basic JavaScript project, create three files: index.html for the webpage structure, style.css for styling, and index.js for your JavaScript code. Use a code editor like VS Code with the Live Server extension to automatically refresh your browser and see changes instantly. Link your CSS and JS files properly in your HTML using <link> and <script> tags.
You can use console.log() to print messages to the developer console for debugging. For user alerts, window.alert() shows pop-up messages. To dynamically update webpage content, select HTML elements using methods like getElementById and change their textContent property in your JavaScript code.
For quick input, use window.prompt() which shows a dialog box asking for user input but returns a string. For more professional and interactive inputs, create HTML text boxes and buttons; then access user input using the value property of the input elements in JavaScript. Remember to convert input strings to numbers if needed using Number() or parseInt().
Asynchronous JavaScript lets your code perform tasks like fetching data without freezing the webpage. Callbacks handle async results but can lead to hard-to-read 'callback hell.' Promises improve readability by representing future completion or failure of tasks. Using async/await syntax allows writing asynchronous code that looks synchronous for better clarity and easier error handling.
You can select elements using getElementById, querySelector, or other selectors, then modify their styles, attributes, classes, or content. You can create new elements with document.createElement(), add them to the DOM via appendChild(), and remove them with remove(). Navigating through the DOM enables you to interact with parent, child, and sibling elements for complex UI changes.
Projects like building a digital clock with real-time updates, a stopwatch with start/stop controls, a dice roller simulation, or a random password generator are great to apply JavaScript fundamentals. Additionally, interactive games like rock-paper-scissors or creating an image slider will help you practice event handling and DOM manipulation effectively.
Use the Fetch API to make HTTP requests to external services, such as weather or data APIs. Handle the response by checking status codes and parsing JSON data into JavaScript objects using .json(). Incorporate error handling for failed requests. This allows your web app to dynamically display external data, such as current weather conditions based on user input.
Heads up!
This summary and transcript were automatically generated using AI with the Free YouTube Transcript Summary Tool by LunaNotes.
Generate a summary for freeRelated Summaries
Complete TypeScript Course: From Basics to Advanced React Integration
Master TypeScript with this comprehensive course covering fundamentals, advanced types, object-oriented programming, decorators, modules, integration with JavaScript, and building React applications. Gain practical skills to build robust, scalable, and maintainable applications using real-world examples and best practices.
Comprehensive Python Course: From Basics to Advanced Mega Projects
This extensive Python course covers everything from fundamental programming concepts, data types, and control flow to advanced topics like OOP, file handling, virtual environments, and AI integration. Featuring practical projects including a Jarvis assistant and chatbot, it equips learners with hands-on skills for professional growth and job readiness.
Unlocking the Power of Go: A Comprehensive Programming Course for Beginners
Learn Go programming with our comprehensive course for beginners. Master the fundamentals and build real-world projects!
Complete Python Guide: From Basics to Real-Time Weather App
This comprehensive Python tutorial covers everything you need to start coding, including 20 hands-on projects. Learn basic programming concepts, work with variables, functions, loops, error handling, and advanced topics like OOP, APIs, and GUI development. The series culminates with building a real-time weather app using an API.
Comprehensive Guide to HTML and CSS: From Basics to Advanced Techniques
This video series provides a thorough introduction to HTML and CSS, covering everything from the foundational elements of web development to advanced styling techniques. Learn how to create structured web pages, style them effectively, and implement interactive features using HTML and CSS.
Most Viewed Summaries
Kolonyalismo at Imperyalismo: Ang Kasaysayan ng Pagsakop sa Pilipinas
Tuklasin ang kasaysayan ng kolonyalismo at imperyalismo sa Pilipinas sa pamamagitan ni Ferdinand Magellan.
A Comprehensive Guide to Using Stable Diffusion Forge UI
Explore the Stable Diffusion Forge UI, customizable settings, models, and more to enhance your image generation experience.
Pamamaraan at Patakarang Kolonyal ng mga Espanyol sa Pilipinas
Tuklasin ang mga pamamaraan at patakaran ng mga Espanyol sa Pilipinas, at ang epekto nito sa mga Pilipino.
Mastering Inpainting with Stable Diffusion: Fix Mistakes and Enhance Your Images
Learn to fix mistakes and enhance images with Stable Diffusion's inpainting features effectively.
Pamaraan at Patakarang Kolonyal ng mga Espanyol sa Pilipinas
Tuklasin ang mga pamamaraan at patakarang kolonyal ng mga Espanyol sa Pilipinas at ang mga epekto nito sa mga Pilipino.

