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
