This is a complete JavaScript course taught
by the founder of Scrimba.com. it is a great place to start your JavaScript
journey. Hi there freeCodeCampers, and welcome to
this fun and practical introduction to JavaScript. In this course, you are going to solve over
100 different coding challenges, you can do that in two ways, either by cloning the GitHub
repository, and then solving it locally on your computer. Or you can head over to scrim
block comm where there's an interactive version of this course, so that you can solve the
challenges directly in your browser up to you what you want to do. Links are, of course,
provided below. Now, there's no JavaScript prerequisites for this course. But I do assume
that you know, a little bit of HTML and CSS as we're going to build a few projects that
needs some HTML and CSS. But if you don't care about that, you can skip those challenges
if you want, no worries, whatever the reason is that this course is actually a part we
larger front end developer career path, which we have a screen bar, which takes people from
zero to hireable, as front end developers. And of course, then HTML and CSS are also
part of that. Now, if you have feedback for me, feel free to reach out to me on twitter
at Pierre borgan. And if you liked this video, please give it a LIKE, I'd really appreciate
that. And with that, good luck. Hey, good old buddy, old pal, and welcome to learn JavaScript
eight practical introduction. I am so excited about teaching you this course. And who am
I? Well, my name is Pierre. I'm the CEO of scribble. And I'm also a front end developer
who's taught a bunch of courses and over 100,000 students have enrolled in these courses, when
I'm not coding My hobby is to take photography's of myself posing in front of a fast course.
But more about that later. What do I mean by this mean? A Practical introduction? Well,
it means that you will write the code, I'm not going to write the code for you. I'm just
going to show you how to do it after you've given it a shot first, because the only way
to learn how to code is to write a lot of code. A clever man once said that, however,
there are many ways to write code. There's the old, boring, theoretical, I met school
way of learning to code. And then there's the much more fun way of learning to code
where you actually build stuff from the get go. And that's what you're going to do, we
are going to start by building a subway passenger counter so that you can count people on the
subway in case that's one of your interests. For me, it actually was frippery or it was
my full time job when I was 19. So back in the days, I would actually need the suction,
then we are going to move on with a game the blackjack game, oh, I just love gambling.
So this is going to be so much fun. And then at the end, we're going to be a bit more serious
and build a tool for salespeople, namely, a so called lead tracker. And what's so insane
about this lead tracker is that it will be a Chrome extension that will deploy to Chrome
so that you can use it out in the wild or send it off to a salesperson who might need
such a tool, because it solves one of the biggest problems salespeople have, which is
to browse the web and collect and gather leads that they later can reach out to. So when
you have completed these three apps, you will have the ultimate superpower in today's world,
which is the power of knowing JavaScript is a very low percentage of people in today's
world who know JavaScript. So you will no longer be like everyone else at that point.
I am so ready to start this course. I hope you are too. So let's just jump into it. You're
very first exposure to JavaScript will come through building a passenger counter app.
Now you might ask yourself, Well, why on earth? Should we build a passenger counter app? And
what's the point of that? Well, you'd be surprised. Because when I was 19, right around this time,
my full time job was to count people who entered the subway. So every day I would stand outside
in the cold and be like, Oh, so there's 123456 people and bring the subway this morning,
How interesting. And that I would bring up my pen and paper and note down the number
six, which at times was really cold. So it would have been so much better if I had a
little people counter app on my Nokia phone so that I could just tap these buttons while
having the phone in my pocket. But this was long before I learned to code. So instead,
we are going to build this passenger counter app together so that you will learn the basics
of JavaScript and so that you are prepared in case you one time in the future have to
stand outside in the cold counting people who enter the subway. Welcome to this lesson where we are going
to take a look at the setup for our people counter app. Here you can see we have a basic
HTML structure which probably looks familiar to you can see we have the HTML tag the head
tag and inside of the body, we only have two elements, the h1 and h2. That is the title
up here and our counter element will To have some styling in our index dot CSS, you can
check it out here, this is just very basic styling that we're not going to go through
because you want to get into the JavaScript as soon as possible. So the first thing we're
going to do actually, is to simply inside of our body tag, create a so called script
tag, like that looks just like any other HTML time, it just says script. Inside of here,
we can actually write JavaScript. So inside of this time, I'm going to write a pretty
long JavaScript expression that you probably find a little bit frightening. But don't worry
about that you're not meant to really understand it. In this lesson, I just want to demonstrate
that this works. So I'm going to start by writing documents, that refers to the HTML
document itself. And then I'll do dot get element, I ID and then open and close parentheses.
Then inside of the parentheses, I'm going to copy the ID of our h2 element. So here,
we're saying, hey, HTML document, I want to get an element and I want to get it by its ID,
and the ID, is this count out? So what do you think we get as a reply? Well, we grab
ahold of this element right here. And then we can do dot inner text, set that equal to,
for example, five, find out run this code, you'll see that boom, we have changed the
text on the inside of the h2 element, this one right here, from zero to five, using JavaScript,
and that opens up a whole world of opportunities, it essentially gives us the power to breathe
life into our application and turn it into a real world product that solves problems
for people. That's why this is so cool to learn. However, we are not going to write
our JavaScript this way. Here, it's kind of an amateurish way to do it. But we rather
want to do is create an index.js file like that. Here is our index.js file, it's currently
empty. What I'm going to do is copy this line here, then paste it into the index.js file. And now out, add an attribute to my script tag called
SRC, which is short for source. And then inside of here, I'm just going to write index dot
j. s, we are in the HTML file, and the JavaScript file is in the same folder. So I don't need
to navigate into any folder or typing a complicated path here, stripe the name of the file. If
we now run this code, again, you can see that yes, it still works. So now we have a proper
setup for our app, and we are ready to get started building our people counter. Let's
move on. So today is actually a really important day in your life, because you're going to
create your first lines of JavaScript. And that is just such a powerful thing to do.
Because you take the first step into a world of opportunities with different shapes your
life. So in a year, you might want to celebrate this day as the anniversary the day you met
JavaScript and changed your life for the better. Anyway, you're going to write it's not this
long one right here, it's a little bit too difficult. At the moment, I'm actually going
to add a double slash in front of it like that. And you can see that grayed out, it
means the JavaScript will ignore this, since this is now a code comment, not real code.
So if we run the code here in the browser, we can see that now we are not modifying the
h2 tag anymore. So we are ready here down at line three to write our first lines of
code. Now, let's think a little bit. What do we need actually, to build this subway
passenger counter app? Well, the first thing we need is some way to store the count. And
that's a natural job for JavaScript, because it's kind of like the data we need to store.
And when you need to store data, you need to create so called variables to store the
data in, and I'm now going to create a variable called count. And the way we do that is we
write let count equal zero. Now we have a variable called count. And that holds a tiny
piece of data, namely, the number zero. And the way you can read this in English, it's
actually let count be zero. So really natural. And let's actually try and verify that actually,
our count variable does indeed equal zero, we can do that by using a tool that every
single developer uses every single day. It's called console dot log, then open and close
parentheses. And inside of these parentheses, you can put almost whatever you want. And
in our case, we are going to put this count variable here. We now run the code. You can
see that down in the console. At the bottom, we printed out the number zero, and the console
is something that the browser provides us with. It's there mainly for debugging purposes
for checking our code, like we're doing here, verifying that actually yeah, I want to take
a look at at count on and print that out to the controller. See my own eyes that it is
what I think it is. And indeed it was. And this console you see here is Rambus implementation
of the console. If you want to check out the real world console in the Chrome browser,
you can, for example, head over to google.com, or any page basically, and then right click
and choose the inspect option, you click that, it'll open up this tool called developer tools,
shows you a bunch of HTML. As for now, we're not going to worry about that, instead, just
click on the console option, that'll open up a blank console, where you actually in
addition to printing out stuff, which we did down here in the script console, can write
JavaScript as well. So if you want to write let count equals five, and then hit enter,
then write console, log and then pass in count in the parentheses, and then hit enter, you'll
see that it'll log out five as well. So the console is available to you in all browsers.
And it's a tool that developers use every single day. So I'm really happy that you've
learned about it this early on. Now I actually have a challenge for you, I want you to do
two things. First, you're going to create a variable called my H and then set its value
to your H, and then log the my h variable to the console. So go ahead and do this right
now. And then I will show you how to do it as well, when you come back. Okay, hopefully,
that went well, let's do it together, let my age, I happen to be 35 at the moment, then
console, log out my age, I'll do console dot log, open and close parentheses, my age, we
run this code. Now we are printing out both account and also my age. So we have verified
that our variables indeed work as expected. Before we move on, there's one thing I want
to show you. And that is to take this line console logging of my age, and place it above the my age variable declaration.
So now we try to console up my age before we define it, since JavaScript starts reading
at the top and works its way downwards. So what do you think then will happen if I now
remove these other console logs, and only keep the My Aged console log? Let's take a guess. Well, what happens is that we get a reference
error cannot access my age before initialization. So JavaScript actually understands what we're
trying to do. And we're actually referencing your value before it has been initialized.
And that simply doesn't work. So now that you are aware of that, let's move on. Okay,
so let's return back to our count variable, learn some more advanced concepts, which is
that you can actually use JavaScript kind of as a calculator. So instead of just writing
left count equals five, you can do let count equals five plus seven, for example. And when
you run that code, you will see 12 in the console, you can do minus, of course, that'll
result in minus two in the control or given divide, that'll be 0.71, a bunch of numbers
after that. And of course, multiply gives us 35. So there's a lot of mathematical operations
built into JavaScript. And you're not gonna learn about all of them now, because now instead
of just hard coding raw numbers, let's try to use variables here instead. Because oftentimes,
you won't see this kind of operation, you'll normally see numbers represented as variables
in real world code bases. So removing this right here, for example, let first batch equals
five. So this was the batch of people that first enter the subway wagon, and instead
of hard coding five here yet again, we're just going to do count equals first box. Well,
what do you think will be logged out here, then? quite correctly, it's five. Because first
matches five count is set to the same as five. And perhaps there was another batch as well
let second max group of people that entered just before the doors closed, maybe that was
seven people, well, then we can do. count equals first batch plus second batch. Yes,
this works well. So this is a much more common thing to see in JavaScript that a variable
is set to the value of, for example, two other variables added together. Now, I want to comment
out this, like that, if you're wondering how I did that magic have the alt multiple lines
at once, I did simply command plus k plus C, or replacing this with Ctrl if you're on
a Windows machine, because what I want to do now I want to gather this code up here.
And then I want to give you eight three parts challenge, where you are going to convert
your age into dog years. So first, create two variables my age and human dog ratio,
that is the ratio between human ears and dog ears. And for the sake of simplicity, we're
going to say that one human year is about seven dog years. Now the calculation is actually
a little bit more complicated than that, but that's not bad. And then the important thing
here is learning. So set, then the human dog ratio to seven, then multiply the two variables
together and store the result in my dog age. Finally, log my dog age to the console, this
is great practice, it's important to build up your muscle memory. So go ahead and do
this right now. And then return back to the screencast, when you want to see how I solved
that as well. Okay, hopefully that went well. Now let's do it together, remove the consoles,
we can get some more space here. And we'll start with my H, which still is 35. And we'll
do a human dog ratio. And that should be seven. Finally, the my dog age should be my age,
multiplied with human dog ratio. Let's verify that this works by logging out my dogs in
the court, and yes, we can see in the console, we get 245 my god, I would be an old dog if
I was really god. I'm human actually. So let's move on. Okay, so let's return back to our
count example. Now you've learned how to initialize a variable and even how to do mathematical
operations on it both with hard coded numbers and with other variables if we need that.
And that's all great. However, up until now, we've just been working on the initialization
or the so called assignment of the variable. What if you want to reassign it or in plain
English, if you want to change the variable? Well, then you can do that, for example, down
here on line five, just to count equals three. And if we now run the code, you can see that
we log out three as opposed to five, because JavaScript starts from the top and runs down
and uses the latest value it can find for any variable defined with the let keyword.
Now there are other types of variables that you can't reassign like this, but we'll get
to that later. As for now, we're just going to work with the let. And you can do this
as many times as you want. If I want to change it even further down down to one, you can
see now that JavaScript is only taking into account the line seven reassignment of the
count variable. So this is all good. But it doesn't really help us if we want to increment
our people entered count with one every time we for example, click a button, what we then
want to do is something like count as one, because we want to take the current count,
keep track of how many we've counted up until now and then just increment with one. The
way to do that is actually by simply doing like this. This might look a little bit weird,
since we have count on both sides of the equal mark. And probably you've learned at school
that the left and right hand side of the equal Mark should be completely equal in mathematics.
That's not how it works in JavaScript. Here we are assigning this variable to take on
this value. First, you want to calculate the value and the value is this point five plus
one will then count now will be equal to six. Let's run this code and see that it works.
Yes. And let's say we want it to incremented by two, then we do two and now it's seven
because five plus two is seven, do the same thing again. This time we can increment This
was 10. Now we're at 17. And minus that was two again, and then we're down at 15. I think
you get the point. Now I have a challenge for you. Okay, so you are to create a variable bonus points. So this could, for example,
be a game where your bonus points goes up and down. And I want you to initialize it
as 50 and then increase it to 100, decrease it down to 25. And then finally increase it
up to 70 again, and you're to use the same technique that we use here with account where
you reassign the variable to the old value of the variable and then adding or subtracting
the value. And I want you to console log the value after each step. So go ahead and do
this right now. And then I will show you the solution as well. Okay, hopefully this went well. Let's do this
together. We'll start with let bonus points be 15. So logging it out. And then we're going
to do bonus points equals bonus points. 50 because we want to get to 100. Again, I'm
soloing it Next up, bonus points equals bonus points, minus 75 because we want to get down
to 25 logging it out again. Finally, bonus points equals bonus points. Now we need to
increase it with 45 to get to 70. Let's comment out this code up here and run the code bring
up the console and yes 50 125 70 Great job. Let's move on. Okay, now you know enough JavaScript
for us to move on to the HTML and build the interface for our app. And it's not a lot
of interface, it's to begin with just a button. And later down the line, we're going to create
another button. But it has to be written. And you are going to do that. So I want you
to follow these instructions, you're to create an increment button that has the text of the
button with the ID of increment dash btn. So go ahead and do this right now. Okay, hopefully that went well. Now, let's do together.
But then I'll create the closing tag inside of here. All right, increment cowritten. counter,
I think increment is more of a technically descriptive words. So let's use an ID increment
dash btn. Like that, if we run this code, you will see yes, we indeed have this button.
And that is already styled How convenient. Let's check out the CSS for that we have a
general styling for buttons, which are reused across both of our buttons. This is their
using the button selector, and then our increment button. And our Save button has a specific
background, each of them their dark red and dark green. Great job doing this. Now the
question is, how do we make this button interactive, because right now, nothing happens if I click
it? Well, in the next lecture, we'll go through exactly how to do that. Okay, so now we're
going to put the different pieces in this puzzle together, and also add a whole new
piece. And in order to free up some space in our JavaScript file error, let's just remove
this previous exercise and actually write out in pseudocode, the procedures that we
need to do in order to make this work. So first, know that we need to store the count
somewhere. And we know that we want to initialize it as zero. And then as I said in the previous
lesson, we need to kind of listen for clicks on this button here. When it's clicked, we
need to increment our count. Then finally, which we aren't going to do just yet. But
I just want to write that procedure out as well, Joe, do you know what to expect? We
need to change the count del, this paragraph right here in the HTML reflect the new count.
So we know how to initialize the count to zero. And we know how to increment the count
variable. So to achieve these first three needs to do this task that is listening for
clicks on the increment button. And that can be done in a multitude of ways. The easiest
one is simply in the HTML, defining an on click event listener, you simply
write on click equals, and then something in between quotes. So this is an attribute
and the HTML, just like the ID is an attribute as well. Inside of here, you write the function that
you want to be triggered when the button is clicked. So I'm gonna write, increment, and
open and close parentheses. Now, that probably looks really weird for you. And that's totally
okay, if you're confused by what's going on here. Because we've seen nothing of the word
increment in our JavaScript yet, so rightfully so we need to create that function. I'll do
that down here. And I'll use the keyword function, then the name, increment, open, close parentheses,
and then open and close square brackets. So pretty funky syntax right there. And the first
time you type them, it feels weird, but over time, it becomes second nature. What you write
inside of these curly brackets is the so called body of the function. And that piece of code
that is in the body will be executed, every time this function is called, are invoked
as the same thing. So just to see it in action, right console log button was clicked like
that. If we run the code, and I click the button, you can see that in the console, we
see the button was clicked, if I do it again, and again and again and again. So every single
time the button is clicked, this piece of code runs, and it runs because we in the HTML
are saying, JavaScript, when this button is clicked on the on click event, I want you
to run a function called increment. And that's what's happening here. And then JavaScript
is like, Yeah, for sure, sits ready and listens for that specific click event. And JavaScript
can do that it pays attention to what the user does on the screen. And when it sees
someone clicking on this button, it fires off this piece of code. This was probably
a lot of information to parse in one go. So before we move on, and continue on turning
our pseudocode into real JavaScript, let's take a closer look at functions over The next
few castes so that you get rights and functions as well, and build up your understanding and
muscle memory. Okay, so let's pretend that we are building
a race card game. So here I have some comments, which are meant as pseudocode for the functionalities
of the game. And the only real functional part of it is these five console logs, which
are counting down from five to one. So we start the game by setting up the race. And
then we do 54321. If I run the code, you can see that is log to the console. That means
that it's go players are to start racing, and they will be running the race, and then
they're racist finished and a winner is declared. And then of course, we are getting ready for
a new race. However, with the current knowledge we have about JavaScript, the way we would
count down for a new race would have to be to copy all of these lines and paste them
in down here. So that now when we run it, we get 54321, printed two times to the console.
However, this isn't good. Anytime you see this kinds of repetitions in your code, you
should try to think is there any way we can extract this into a function, that is exactly
what we are going to do, we are going to refactor this so that it instead uses a function. Another
word for function could be command. So we are asking JavaScript to kind of remember
a command so that we can use it later on as well. And that command can be as comprehensive
as you want. In our case, it's going to be to countdown from five to one. So let's just
do this to see it in action to create a function, as I talked about in the previous cast, we
use the function keyword, and then the name of the function, I'm going to call this function
count down, then open and close parentheses, then open and close curly brackets. And all
of the action happens inside of the curly brackets. So I'm going to break that into
a new line. And I'm going to copy all of these console logs, and then paste them inside here,
like that. And here, I'm tabbing it out, just to highlight that this code is inside of that
function. This is not something JavaScript cares about to make our code easy to read
for humans. So now I have declared our function. However, if we remove this on here, and now
try to run the code, nothing happens. Because it is only been declared, it hasn't been what
we call invoked, or also called as this code inside of here will only run if we call the
function. So if JavaScript was a dog, and we've taught our dog to roll around, then
in order to get our dog to actually roll around, we have to say, roll around. Same thing here,
we have taught JavaScript to countdown, but in order for it to actually do the counting,
we have to say, countdown. And to do that, like this writing countdown with opening close
parentheses. Now you can see when I run the code, it indeed does the counting. But if
I comment this out, it does nothing. So what I'm going to do now is I'm going to take this
countdown, and I'm going to put it all the way here at the top. And then I'm going to
call it when we are ready to start the first race, and then also call it when we are ready
to start the second race. Now if I run the code, you can see that we indeed count down
two times before the first race and before the second race. And this is much better than
typing out all five console logs, both here on line 11 and on line 19. So we have compressed
our code a lot. So with this knowledge fresh in mind, let's move on to the next cast where
you are to write your first function. Okay, now it's your turn, you are going to create
a function that logs out the number 42 to the console. And you can decide the name of
the function. And when you've done that, make sure you call or invoke the function as well
to go ahead and do this right now. Okay, let's do this. I call it my logger. Opening closed
brackets. And then inside of the body, do console dot log 42. Now we decode my logger,
like that, we run the code. And yes, you can see we are logging 42 to the console. Great
job. Okay, time for a new challenge. So in our race car game, we have certain laps, and
of course we track how much time our players use to race through the laps. And here we
have three lap times in the variable lap one lap two and lap three. And the thing is, if
you create a function down here on line six, it will be able to access these three variables
from within the function. So what I want you to do now is create a function that simply
logs out the sum of all the three laps, so that'll be the total racing time for a player. So you decide what name you
want to get it, just write that function that logs out the total lap time, and then run
the function as well. Okay, hopefully that went, well, let's do this function. I'm gonna
call this function, log laptime, open and close parentheses. Here, I can either first
create a variable, let total time for example, lap one plus lap, two plus lap, three, and
then console, log out total lap time, like that. And then log lifetime, invoke the function
down here on line 11. If we now run the code, we can see yes, we are logging out 203. This
is one way of doing it. Alternatively, I could have skipped creating this variable in here.
And simply added the variables inside of the console log that will give me as you can see
the exact same result. Now, the reason I wanted to create this variable here, though, is to
just show you one thing, just that while this function could access these variables, from
the so called global scope, the outer scope, which is not on the inside of the function,
but on the outside of it, this doesn't work the other way around. If I now let's try to
console log total time, from the outer scope. If we run this gets a total time is not defined.
That is because when you define a let variable inside of this scope, it only exists inside
of this block of code. This is the scope in which the function lives. And that's why we
call let variables block scoped. So that might be a little bit confusing, that the lap could
go from the outside of the function and to the inside of the function. But total time
couldn't go from the inside of the function to the outside of the function. Don't worry
too much about this JavaScript will tell you when something isn't defined, and you can
be sure that you will miss step a times. But that's just a part of the process. Let's now
move on to the next challenge. Okay, so now we have to combine some of the things you've
learned up until now, in order to build this lap counter feature, because in our racing
game, we want to keep track of how many laps a player has completed. So I've created this
variable called laps completed, and initialize it to zero. So what I want you to do now is
create a function that increments the laps completed variable with one, every time you
run the function, then I want you to run or call or invoke or whatever you want to call
it, this function three times, so that on line nine, here, the value that's logged out,
will be three. Now, if you're wondering how to increment a variable in JavaScript, just
look back if you cast because we did that previously. So now we have to combine that
knowledge with your freshly acquired knowledge about writing functions to go ahead and give
this your best try right now. Okay, hopefully that went well. If not, no worries, let's
do this together. So that you get to see how we do it. function. And I'm going to call
this function, increment lock like that. Open and close parentheses, then open and close
curly brackets. And here after increment this variable, just as we did a few casts ago,
by doing laps completed, equals the old value of laps completed. Last one like that, right
now run, increment last one time, you'll see that we're logging out one, good stuff, let's
invoke it three times. There, we can see we are logging out three to the console. So great
job doing this. If you didn't manage it, just go back and try again, now that you've seen
my solution, because it's really important that you actually write the code here, so
that you build up that important muscle memory. Okay, we're back at the subway counter app.
And as you can see, I've deleted the increment function, because I want you to write it instead,
it's much better than me writing everything. You want to do it as a part of turning these
first three lines of pseudocode into real code. So you're going to initialize the counter
zero, you're going to listen for clicks on the increment button. And thus you have to
create that function that's triggered when the increment button is clicked, and then
you are going to increment the count. Matter, find a little challenge here and that is to
log it out after the count variable has been incremented. So go ahead and do this right
now. And then afterwards, of course, showing you the solution as well. Okay, hopefully that went well, let's do this
together, we'll do function increment, open and close parentheses, open and close curly
brackets. And we have the button, let's verify that it works. Good thing to do after every
single step. So that you know, at some point get a bug, you will have a better understanding
of where it happens is you know which steps you were able to get to without triggering
any bugs. So I'll do clicked, run the code, click the button, the Yes, that works. Okay,
not wanting to increment the count. So we're going to do that inside here. And of course,
then we need the count initialized to begin with. So count equals zero. Here, as you remember,
it's just as we're simply going to do what we did up with line four, we'll do equals
count, plus, now, finally, console, log count. I'm going to remove this and run the code,
hit increment. Yes, we see one, and two, and three, and four. Nice. So then we have done
these three parks, remove this helper code right here, we have the final part left. And
we can finally start understanding what this weird piece of code here on line one that
we worked with, in the very beginning of the course, actually means. Let's do that in the
next lecture. Okay, so we are ready to add the final piece of the puzzle, just to change
the count L. That is the age to buy care, which currently has zero. So that reflects
the new counts. And the view count is down here, which we are logging out. So we have
to do something down here at line nine. And what we're going to do is take this line right
here, which has just been lying here in the background all along. Now, in order to properly
understand this expression, I think we should break it into two, take the first part where
we're actually asking for the HTML element. The second part, we're actually modifying
the HTML element. So starting with the first part, I'm going to store this in a variable
called count L, like that, and do document get element by ID, close parentheses, passing
in count, l. Exact string right here. Notice that we're using different naming convention
here in the JavaScript. This is called camel case like that, where you capitalize the first
letter of the second word, but not the first letter of the first word. This is how you
want to write JavaScript variables. It's a very normal convention. Also, if we were to
try to use the same convention, as we've been using in our HTML and CSS, JavaScript would
actually tell us Ah, you can't do that. Because IE, we are getting a red line under this character,
which is Java scripts way of complaining to us because it's not a valid variable name
when you stash. So we got to remove it like that. Now, it's always what do you think we
should do now now that we've taken one step into the unknown? Well, of course, we're going
to use our good old friend console lock, because we have to verify at every single step that
we're actually on track. We haven't introduced any bugs. So I'll do console dot log, and
logging out, count out. And if we bring up the console, we see actually, we're getting
what looks like an HTML element in the console. That's pretty interesting. Now, it's actually
not a real HTML element. It's more of a representation. It's a model of an HTML element. And it gives
us a lot of other opportunities to change it using JavaScript as well. But for now,
it's perfectly fine to think of this as just yeah, that is the element that we are seeing
right here. It's a JavaScript representation of that element. Because remember, we said,
Hey, HTML document, why don't you get me the element that has the ID of count l? And the
HTML, I was like, yeah, sure, just take it. And then you stored that in the count variable.
And now you, as a JavaScript developer, have control over this element, and you can manipulate
it, which is exactly what we're going to do down here at line 14. Because now we're going
to move on to the second part of this big expression, which is modifying the element
itself, dot inner text equals five, or in our case, how would we write this? Well, we've
turned this big thing here into this variable. So we'll use this variable dot enter text,
that is enter text like that equals, and we're not going to set it to five because I wouldn't
make any sense. What are we going to set it to think a second about that? Neither is the
count, because we know from console logging earlier on that the count does indeed increment
correctly. And now we're just saying that Won't be enter text is the text on the inside of the tags, we
want it to be the count, we'll run the code, hit the increment button. And yes, it works.
Now we are incrementing, we are counting people really good job of reaching this point, your
JavaScript skills are starting to become dangerous, as you now know how to create interactive
apps. Now, before we move on, there's one thing I want to mention, which is that this
get element by ID here. And this dot log, both are functions in the same way, our increment
function is a function. Now they are hooked on to the document object and the console
object. But that's just new ones. They're still functions or methods as we call functions
that are hooked on to so called objects. If that sounds confusing, it's because it should
be at this point, because you haven't learned about the objects yet. And methods on objects.
But don't worry about that. Just think of them as functions. Actually, the thing we've
been doing here of adding something in between the parentheses of the function when we are
calling it is called to pass in arguments, which means that we are giving the function
some data to work with like here, we're specifying the ID of the element we want to grab. Otherwise,
if we didn't do that, this function will just be running in the wild and not know what to
look for. Likewise, in this dot log here, we're passing in which variable we want to
log to the console. If we didn't do this, the log function wouldn't know what to log.
So speaking in analogies, if the function is a CEF, that are to cook a meal for you,
then the arguments you pass in are the ingredients that chef uses to cook that meal. So hopefully,
that made everything a bit more clear. Let's clean up this code and move on. Now, before
we move on, I want to talk a little bit about what we're doing here where we're saying documents
dot get element by ID, because you'll often hear developers refer to this technique as
working with the DOM. And that's one of those three letter acronyms in web development.
sounds super complicated. And I was really confused about this when I was learning to
code. And I want you to avoid that confusion. So let's just unpack this expression. It's
short for a document object model. That sounds really fancy. However, it's actually just
how you use JavaScript to modify a website. It's just that the people naming this wanted
to give it a really abstract name. But if we look at each of the words separately, the
name actually does make sense. Let's do that starting with a document. Why that? Well,
that's because what you're interacting with an HTML document object? Well, that's because
the document keyword in JavaScript is of the data type object, meaning they've taken the
HTML document and shoved it into a JavaScript object. Of course, that's a little bit of
a simplification, but that's the essence. So this word document of the data type object.
Now, you haven't learned about objects yet, though, you're going to do that a little bit
later. Finally, there's Model Model is basically a representation or a model ation, kind of
like, you know, there's a real Saturn five rocket that NASA built. And then there's the
Lego model. And that's how it is here as well. There's the real HTML element, which you've
written in your dot html file, then there's the JavaScript model, the representation you
have over this element in JavaScript. So don't be frightened when people talk about the DOM,
just in your head to translate it to how to use JavaScript to modify websites. With that
out of the way, let's move on with the coding. Or actually, before we move on, I have to
say I fooled you a little bit. Because the problem with the previous lecture was that
I wrote the code. And that's just wrong, you are going to write the code. That's how you
learn. So I've removed the two lines of code that I wrote, namely, grabbing the counter
element and storing it in a count l variable. And also setting the count else enter text
through the count. So just do that. And if you struggle, just go back and look at my
solution. It's no need for me to write this out for you yet again, just go ahead and give
it your best shot and refer to that if you need help. And I will see you in the next
lecture. Okay, it's time for you to build some muscle memory, because you are going
to create a Save button and a save function. You're going to start with a function. Here's
the instructions create a function called save logs out the count when it's called.
We're going to modify this to do some other stuff afterwards. But that's for now I wanted
to just log out the count. Secondly, in the HTML, you are going to create
the Save button. You're gonna set the ID as save btn and have it call the Save function
when that is clicked. So, go ahead and do this right now and then return back to the
screencast when you want to see my solution. Okay, hopefully that went well, let's do this
function save, open and close parentheses, then the body of the function will console
log account. If we want to check that this actually works. Now we can call the same function,
run the code there, we can see yes, that the account is indeed locked out as a consequence
of us calling the function here on line 15. Okay, let's remove that. Going over to the
HTML, we're going to create the Save button, and we do open button tag, then I'll just
close it right away. Alright, the save in between the tags and give it the ID of saved
up BTM. Now we can actually run it to see that renders. Yes, it indeed does. But nothing
happens when we click it. And that's because we have to do on click, we want to run the
Save function. Here, we have to invoke it with the opening close parentheses, otherwise,
it won't call the function. So we're running the code and hitting save, yes, there we are
logging out zero, because of this line. Now we can increment a couple of times and see
Oh, now we're logging out six, pretty nice. Now we're starting to get somewhere, it's
only a matter of saving the count to the website as well and rendering it out under the buttons.
But before that, there are some new concepts you need to learn. So I'll see you in the
next test. Okay, so now it's time for us to build this little functionality here, which
allows us to save the number of people who have entered into the subway at each of the
departures. However, this requires you to work with this full paragraph, which actually
includes both numbers, which you can see but also like regular text, previous entries and
some symbols as well. And once you move away from just straight out numbers in JavaScript,
you're moving into the land of so called strings. And strings is a data type in JavaScript.
And in case you're wondering, yes, numbers is also a data type. And if you think the
word string is a little bit weird, well, you can also think of this as just text, the strings
you work with in JavaScript are normally meant to be text that the user reads on the page.
Now, we have been working with text here before and we've hard coded in some text here and
there in the HTML. And actually, as far as HTML knows, everything is strings doesn't
even know about numbers, HTML can do calculations for you. So when I'm talking about strings
and numbers, I'm talking about it in the context of JavaScript. And even though you've probably
not even aware of it, you've actually written the string already appear on line one, you've
wrapped the count dash l inside of two quotes. And that is how you create a string in JavaScript.
But you've had far from enough practice to start working with strings in our people counter
app. So in the next lesson, we're going to go over the basics of it. And then we're going
to solve some challenges so that we build up that muscle memory and make you capable
of using strings in our app. I'll see you there. So strings are used all over the place
and software, let's say that you, for example, are building an app where people can authenticate,
well, then most likely, you have to store some kind of username for your users, that
would most likely be stored as a screen, for example, Pear, wrapped in double quotes, then
this string, just like we did with numbers will be stored in a variable. So let user
name equals pair. Now we can console log out username, get pair logged to the console.
Now, one thing I want to mention is that I'm using double quotes here to create this string.
I could use single quotes instead, if I want to, you can see that works. However, I cannot
start with a single quote and end with a double quote. As you can see, now, our editor tells
us that this syntax is off. And if we try to run the code, we are getting a syntax error.
So you got to stick with one or the other. And I usually use double quotes, but that's
just a matter of preference. If you prefer single quotes, go ahead. Now I want to give
you a challenge. Here you are to create a variable message that stores the string, you
have three new notifications. Go ahead and do that right now. Okay, hopefully, that went
well. Let's do this message equals this string right here. Now what we want to
do here is combine this string with this string because this string right here is probably
the result have us checking in the database and seeing that, oh, there's three new notifications
that Pierre hasn't seen. So render out this ring right here. And then of course, we need
to combine it with the name. So what we want to do is message plus username like that,
when we add a plus here, we so called concatenate the two strings together. So let's have a
look at what happens when we run the code becomes a slightly ugly string, we have three
new notifications pair with no space in between the strings, so it kind of becomes like, this
isn't really what we wanted. What we then also can do is add a third string in between
here, which includes a comma and a space. Now if we run it, you have three new notifications
pair. And maybe we even want to add a exclamation mark at the end like that. As you can see,
when we use the plus for strings, simply concatenate the characters together. Okay, now I have
a new challenge for you. You are to create a variable message to user that contains the
message we have locked. By that I mean the entire message in here, this should be a new
variable. And then afterwards, I would log it out just to make sure that you have configured
the message to user in the correct way. Why don't do this right now. Okay, to do this,
you do left message to user equals message plus, comma space, plus username, plus, exclamation
mark. Now, we can replace all of this with message to user and running the code again,
we get the exact same string, which is just what we want it. Great job. Okay, time for another talent, you have to
create two variables, name and greeting. And the main variable should store your name.
And the greeting should store for example, Hi, my name is. And then you are to create
a third variable, my greeting that concatenates the two strings. And finally, log the my greeting
variable to the console. So this is just to give you some muscle memory. We had to do
this right now. Okay, let's do this. I'll do left knee equals pair, Harold, Oregon,
then let greeting. Hi, my name is and then a space at the end. And then finally, let
my greeting equals reading last name Ben. To see how this went. We do console log my
greeting. running the code? Yes, we get Hi, my name is Pierre Harold Bergen. Now, notice
that here, I added the space inside of one of the strings as opposed to doing something
like that. Forever being that would work the exact same way. So great job solving this
challenge. Let's move on. Okay, now let's mix it up a
little bit. And say that my name isn't pure Harold Bergen. It's
actually 42. a strange name. But anyway, what do you think will happen when we have one
number and one string? What will the result be? Let's do it. Actually, Hi, my name is
42. So the 42 here has actually been turned into string, and has been added into like
this. And that's kind of what happens in a wrestling game between a string and a number,
and the string always wins. Now this was a little bit of a weird example. So let's take
one that's a bit more interesting. Let's try let points equals four. And then let's say
bonus points. This is some kind of game that is 10. Lead total points equals points plus
bonus points, total points. Now, what do you think we'll log out here? I'm going to comment
out this one right here. Take two seconds to think about what the result will be. Okay,
let's run this. The result is 410. That is weird, because perhaps you expect them 14.
No, as I said, the string always wins. So when we see four plus 10, which is the values
of these variables, the form will be turned into a string. And the result when you concatenate
two strings, it's just very easy to see by just removing this fluff in between them.
410 if the numbers one, the wrestling game will be like this, it would indeed log out
14, but it didn't. So I'm gonna give you a couple of challenges here. What do you think
these four console logs will log out? Take a minute to think about That potentially write
your solutions in a code comment either above or perhaps even after each of the lines and
then return back to the screencast. And then we'll have a look at it together. Okay, here we have a number and a number.
So this will end up as a number as well, four plus five is nine. As far as I can remember,
your a string plus a string, even though they are number characters inside of the strings,
that doesn't matter. JavaScript still sees this as a string, and the result will be a
string of 24. Here, a wrestling match between a string and a number. Sadly, the number always
loses. So this will be history one. Finally, again, wrestling match between a number and
a string, the result is always at the string when so this will be 100 100. Like that, let's
run the code. Yes. You also can see from the console, the way the scribble console highlights
the difference between numbers and strings. As with the color, the strings are white,
whereas the numbers are blue. So great job, let's move on. Okay, it's time for a challenge.
This time, you are going to create a feature that we already have unscramble, because on
the dashboard, we welcome our users by saying welcome by compare Harold Morgan. That's a
normal thing a lot of apps do. So it makes sense to try to implement it. And we want
to do it is through grabbing a hold of this paragraph here, which I've given an ID of
welcome dash L. That is the first part of the challenge, you're going to store that
paragraph in a variable called welcome URL using this camel case convention. And then
you are to create two variables name and greeting that contains your name, and the greeting
we want to render on the page. In our case, that is Welcome back. Finally, you are going
to render the entire welcome message using welcome l dot inner text. So go ahead and
give this one a shot. And then I will show you the solution when you return back to this
cast. Okay, let's do this. We'll start by grabbing
the welcome l paragraph. Let welcome L equals document dot get element by ID passing in
the ID we have here. Like that. Now we need to create the two variables let name my name
is pair Harold, Oregon. Let greeting. Welcome back. And finally rendering it out. I just
done by doing welcome l doc. enter text equals greeting plus name. Now if we run this, we
can see we are rendering out Welcome back to pair Harold Oregon. But there's no space
between welcome back and my name that can easily be resolved by just adding a space
after Welcome back. Or we could of course hard coded in in between these two variables
when we concatenated the string as well. But that doesn't really matter that much in this
case. So let's just stick with this and move on to the next lesson. Okay, now there's one more thing you want
to do. Because Personally, I think this welcome message could be a little bit more lively
and fun. And what would help there is to add an emoji, for example, this emoji right here,
that would look pretty nice. So I want you to add that to the welcome element enter text.
However, there's a catch. You are not allowed to modify the code over line nine, you have
to write it below. So the question is, how can you add this emoji to the end here in
the browser by simply writing more code not by modifying any of the existing code. And
to give you a hint, you need to remember back what you did. When you increment the numbers,
this technique here, you can do the same thing with welcome l dot enter text. So go ahead
and give this a shot. Okay, hopefully that went well. If not, no worries, we'll do this
together. We're simply going to do here is instead of using count going to use welcome
l dot enter text instead of the one, we're going to use an emoji. So here we'll do welcome
l dot enter. Text equals the old welcome. Else, enter text, plus this new movie right
here. And an emoji is just a string. Like all other characters, it's just rendered out
a little bit fancy. So if we run this to see yes, we indeed get the emoji at the end. Now,
before we leave, I want to teach you a little trick. Because this line here is pretty clunky
writing the welcome l dot inner text twice. It's not something you'll see out in the wild
because there's a shorter version of writing this and that is simply using the plus equal
operator. What it does, it takes The current value you have, and then adds this one after
it fits the exact same thing that you were doing here. timbit weird. This plus equal
sign here was trying remember that it simply takes what you have here and adds this to
it. So that after this line, I'll come down to enter text consists of the entire thing
here. Okay, with that in mind, let's go back to our passenger counter app. Okay, just a
minor thing, before we start using strings in our app, I want you to use the plus equals
technique instead of this slightly longer count equals count plus one technique. Go
ahead and do that. Okay, hopefully, that went well, by simply doing like this count plus
equals one, run the code. Yes, it works. Let's move on. Okay, so now you're going to solve
a super cool challenge, you're going to take everything you've learned about JavaScript
up until now and use it to create this save feature can see it says previous entries,
and then four 511, with dashes that separate them. And these are, of course, added every
time you hit the Save button. Now, there's a dash after the three numbers as well. Don't
worry about that, it might look a little bit weird, but it's the easiest way to do this.
And we want to do it the easiest way. Now that you were building stuff like this first
time around, we don't worry about details, make it work first, then make it better. That's
my philosophy. So we're just going to make this work. Okay. So your three challenges
are listed as comments here in the JavaScript and the HTML, I'm going to write the paragraph
for you so that you have something to work with. So this is a p tag should say previous.
And Chris, like that, and I'm going to give it an ID equals save dash l for save element,
then you're going to grab the Save element paragraph and store it in a variable called
save L. And then in the Save function, which is triggered when the Save button is clicked
on, you are going to create a variable that contains both account, that is the number
and the dash separator. It'll look something like this, like 12 space dash space. And then
you are to render this newly created variable into the Save element using enter text. However,
you must make sure that you don't delete the existing content from the same old paragraph.
Because you do want to concatenate the string, not wipe it out entirely and replace the paragraph
with the latest entry. So you've got to remember your plus equal, luckily, you know how to
use plus equals and that might be helpful in this situation. Finally, one thing I want
to mention is that you might struggle a little bit with the spaces here and it might end
up slightly different than what you can see here. And that is perfectly okay. Don't worry
about that. The next cast actually we are going to do some searching online to figure
out if there are some alternative methods we can do this on, which will help us keep
these spaces. That's a critical part of web development, searching for solutions online. So I've left a little gotcha for you
here. So we get a nice little problem to solve using Google and some online docs in the next
guest. Don't worry about that. Just go ahead and give this your best shot. And if you need
help just revert to the screencast. And I will show you the solution as well. Okay,
hopefully this went well. If not, no worries, let's do it together. We are going to do let's
save our Adobe document dot get element by ID. And we are going to get the Save bash
l like that. Always I like to console log, just to see that I have the correct element
fetched. Let's run this code and he is bringing up the console, we see that we have grabbed
the correct element, then we can move on. First create a variable that contains both
the account and the dash separator. So what are we going to call this variable? I intentionally
didn't give you a name for it because I wanted you to think what could be a suitable name
for this string. And there's no right or wrong answer. But one thing you could call it would
be count string or count str. Like that. So it is the count. But we've turned it into
a string. So count string, kind of make sense. And the value of it will be count applause.
And then the string, a lot of space, a dash and a space or right three, render the variable
using enter text. Okay, let's do it down here. We'll do save l dot txt and then you might
have been tempted to do equal count r but that won't work. Let's just try it. run the
code, we increment we'd save boom, then we suddenly remove the previous entries. txt.
We will clear that out of course because we set all the intertext to be just this count
string. That doesn't work we have to take into account what was there Previously as
well. So we add plus equals like that increment increment increment save. Yes, that works
far right. So it works really well actually. However, this dash in there is gone, as is
our space here in the paragraph. And that is a bit weird, because we want to keep those
spaces. However, it's also a great opportunity to do some searching online in order to solve
this problem, which is a critical skill for any developers, namely, finding answers online.
We'll do that in the next cast. Okay, so we have this little problem here, which is that
our spaces aren't working in the way we want them to work. Basically, this space here gets
lost on the way somewhere, I don't know where but it happens. How do we go about figuring
out what's wrong? Well, looking at these two lines, which is where we deal with this save
element, paragraph, you think what would be a suspect which tool that we're using would
be a good suspect? And I'm gonna point to this one right here. Because I happen to know
that that is actually the guilty one, the inner text, and say, you'd guessed that as
well. How do you go about finding another tool that doesn't work this way? Well, one
thing you can do, is you can right enter text alternative. And then MDN, put that into Google
and see what it returns. MDN is short for Mozilla developer networks. And it's a great
resource. So if we do that, type that into Google, you can see the very first result
is node text content. Okay, that's interesting. Let's click into that. There, we land on an
interface, we're going to get very familiar with the MDN web docs that says node dot txt
content. Don't worry about this note here, it's kind of fancy way of saying HTML element,
sort of not entirely, but just translated to HTML element right now, and you'll be good,
then you can read the text content property of the HTML element represents the text content
of the element, okay. Seems pretty useful to me. And then we can scroll a little bit
down. And then you see they've actually listed up the differences between inner text and
text content. Here, if we scan through this, you can see that inner text only shows human
readable elements. And yet again, enter text is aware of styling, and won't return the
text of hidden elements. Okay, so it seems to be that the inner text somehow struggles
a little bit to return things that are hidden or not human readable. And like, yeah, space
is certainly not not human readable as a character. So maybe we can just change it then to dot
text content that said, let's try that. Text, content. Code, increment, increment increment,
save, oh, oh, yes, indeed, now we get the spaces. And one thing I want to highlight
here is that while the Mozilla web docs is a great resource,
it's very comprehensive, the language you'll see in these kinds of documentation sites
is often very technical. That's why I kind of skimmed through and found some hints of
human readable and hidden, and I kind of didn't worry too much about going into depth. And
I think you as well should think when you see a page like this, don't feel that you
need to understand everything. And for the love of God, don't try to learn the code by
just reading documentation. Some people say that's a good idea, I think it's a terrible
idea. You want to slowly learn how to get comfortable reading documentation. But you
also want to ignore all of the complex stuff that it's very often wrapped within. And there
are other sites as well, that explained things in various degrees of difficulty. For example,
there's also something called w three schools, which is very good there, Stack Overflow,
and many more. And you're going to see more of this as you progress in the course as we're
going to come back to this debugging concepts later on as well. But just for now, we've
just had a little sneak peek on the Mozilla Developer Network. And actually, it's kind
of trash talking the dot inner text here and saying that it's also computationally expensive.
So me, I've gotten enough hints that I actually want to use dot text content instead of enter
text. I'm going to change this up here as well. Like that, it still works great. Now our app is almost
complete, there's only one more thing we need to do. And we'll do that in the next guest.
Okay, so now we are going to put the final pieces in our puzzle, because we need to fix
the fact that if I increment this, and then hit save, and then the subway leaves the station,
and I'm going to count a new group of people then with the current solution, we'll be counting
further on from six like 789. And that's not what we want. We want this one to be set back
to zero every time we hit save. And to do this, you need to write two lines of code.
And at this point, I want to just throw you into the deep end of the pool and see how
you swim, if I'm not going to give you any hints or write any pseudocode, or tell you
where you're going to write these two lines, now you really have to think and think for
yourself, what do you need to do here in order to make this work. And feel free to hack a
little bit on it to try a solution, run the code, see how it works, console, log out the
values, just hack away at it and give it your best shot. And if you don't manage to do it,
no worries at all, because I will show you how to do it again, of course, when you return
back to the screencast. So then you can just try to do it again, after you've seen my solution.
Anyway, enough talk, jump into the code here and give this a shot. Okay, now let's solve
this together. So what we need to do is write a couple of lines in this save function, because
this is where the magic should happen, because it's when we hit the Save button that we want
this value to be set back to zero. And how do we set this element to be zero? Well, it
is the count element, which we've worked with previously. and setting it to zero. We know
how to do that we can do count l dot constant and set that equal to zero like that. By rerun
the code, increment the increment the increment, increment it save, and yes, it's now zero.
But if I now try to hit the increment again, you'll see Oh, five. That's weird. Why is
that? That's because we have indeed set the text content of the count element to zero.
So this is true right here. But in the JavaScript, we're still keeping track of the count. And
that count has been incremented, this point five times. So what we needed to do here,
when we set the text content to zero is to also set the count back to zero as well, because
JavaScript remembers what we've done previously, unless we refresh the entire browser, even
though JavaScript can see that, yeah, you're setting the text content of this element here
to zero, it still keeps track of the count here. And JavaScript can't deduct that, since
you want to set this here to zero. You also want this to zero, no, you got to give JavaScript
very specific instructions. So you need to do here, count equals zero as well. Now, if
we run the code, bam, bam, bam, save, it's at zero. And yes, we indeed start at zero
again. So great job reaching this far. So you have built your very first Javascript
app from scratch, congratulations, that is a huge accomplishment, that's all give yourself
a pat on the back, you have really learned a lot in this section. And to prove that you
are actually going to do a little recap. So you get to see in front of you, all of the
new concepts you've shoved into your brain at this point. So we started out with the
script tag, if you remember, we had it here in the index dot HTML file, and we wrote our
JavaScript internally, in this file. However, we realized that that wasn't the way we want
it to go. So we instead pointed this script tag to a source, namely the index.js file
so that we could write our JavaScript there instead. Then we moved on quickly and learned
about variables, namely the left variable, and we set its value to a number, which brings
us to your very first data type numbers, you learned how to work with numbers, do mathematical
operations, and even increment numbers here on line six, and also reassign the count variable
to zero, here on line 14. So a lot of work with numbers in this up. But you also learned
about strings, which was your second data type, here, you added a string to build the
same feature. And also you console log out a few strings along the way with code that
we have deleted now, so I added the list console log here to remind you about it. Because that
is a truly important concept in developing and you will use it throughout your entire
career. Also, another thing you will use constantly as a developer is functions. You learned how
to create functions like this increment and save function, and also how to call them aka
invoke them from the HTML file here on the button clicks. And that brings us to the next
concept which you learned a ton about, which is the DOM or the Document Object Model, or
what I like to call it, how to use JavaScript to change the website.
So we interact with with the DOM at several places. For example, up here we we did document
dot get element by ID, that's one you're going to get very familiar with. Throughout this
module, we passed in the ID as a string. So the JavaScript was able to head into the HTML
and fetch out the content you told it to look for. And another way we interacted with the
DOM was through the inner text property. We use that here instead of text content, but
then we googled our way to the Mozilla Developer Network, realize that actually, next content
is a better solution. So we learned about that and oh my god, this is a lot of concepts
to learn. totally understand if you're a little bit overwhelmed. And if you feel that you
are on thin ice on a few of these concepts, that's totally okay, we are going to repeat
all of these things over and over again throughout the module. But don't worry about that. Actually,
we are going to jump directly into a section where you are going to get assignments that
test you for the skills just to give you that repetition and muscle memory you need in order
to make these concepts become second nature. So let's go ahead and get some repetition.
And then once we've done with that, we'll move on to our next big project, the blackjack
app, which is going to be so much fun to build. So I can't wait to see you there. For now,
let's jump into a few quick fire challenges. Okay, in this challenge, you're going to repeat
variables. So first, you're going to create two variables, first name and last name. And
obviously, I want you to set their values to your first name and your last name. And
then concatenate the two variables into a third variable called full name so that you
have your full name. Finally, log full name out to the console, go ahead and give this
a shot right now. And then I will show you my solution when you return back to this screencast. Okay, let's do this. I'll do first name equals
here. And then I'll do let last name equals Morgan like that. Then we need to concatenate
the two together, let name equals first name, plus last name, like that. Finally, I want
to log it to the console. Console dot log, full name. Now I can run the code. And as
you can see, we're logging here borgen to the console. But there's no space in between
the two names. So I could achieve this in a multitude of ways, either by adding a space
here, now it's better or adding a space before Morgan. Still good. However, neither of these
are optimal, since I want the first name and last name to be the name and the name only
not an extra space. So what I'll do instead is in between here, add an extra space like
that. running the code, there we go. Now, first name and last name, contain only the
characters of my name, but we still get the space by adding this third string here, when
we create full name. So no matter how you did it, great job, let's move on. In this
challenge, you are going to create a function that logs out Hi there, Linda, when called.
And you have to use the name and the greeting variable inside of the body of your function.
And also there's a comma and an exclamation mark, you also have to include so that you
get this exact string log to the console. So go ahead and solve this one. And then I
will show you the solution afterwards as well. Okay, let's do this create a function, I'll
call it greet Linda like that. Here, we are going to console log, first the greeting,
we're going to have to plus the comma and the space, and then plus again, then the name
and then plus again. And then the exclamation mark like that final step to check our code,
we need to run it greet Linda like that, running the code. And there we see this exact string
in the console. Great job. In this challenge, you are going to practice your incrementing
and decrementing skills. So let's say that you are building a game and the player is
collecting points, which currently are at three and you need to create two functions
one which is called add three points, and one which is called remove one point and of
course then have these add and remove they're given points from or to the my points variable.
So remove one point should decrease my points with one add three points should add three
points to the my points variable. And your job is to create those two functions and then
call them however many times you need to call them in order for this line down here to log
out the number 10. So you are going to write your code in between here, you can add as
many lines as you want. That when you eventually run the code, my points should be 10. And
you should only have changed my points via calling these two functions a number of times.
So go ahead and give this one your best shot and then I of course will show you the solution
afterwards as well. Okay, hopefully that went well. Let's do it together. We'll do function
add three points. what that'll do is take my points and plus equal three. function,
remove one point. And that should do my points minus equal one like that. Okay, now we have
them, which means that we just need to call them a couple of times, we are at three, and
we need to get it up to 10. What I will do then is I'll first do adds three points, call
that three times, because then we'll go up to 12. My calculation is correct. From this.
Yes, we are indeed logging 12. That means that we can remove 1.2 times that should get
us to 10. Yes, we are logging out Tim. So we have solved the challenge. Great job. Okay,
it's time for some strings and numbers repetition, you're going to add a bunch of strings and
numbers together and try to predict what the result is. So here, after each one of these
lines, I've added two slashes, that means that you can write your prediction, try to
go through all these, and then run the code and see how you get it. And then I will give
it a shot afterwards as well. Good luck. Okay, starting on the number two is a string
plus a number, we know that JavaScript then turns both of these into strings. So it becomes
22. Here, 11 plus seven, that's just two numbers, we get 18. And as a number this time and not
as a string, six plus five, you might be fooled to think that JavaScript would treat this
as a number calculation since the number is first But no, actually, the string wins, and
it becomes 65. Likewise, with this one, here, it's very natural to think that what you want
to do is add these two points together so that it's my points is 14. But no, since you
have a string here, everything will be turned into a string. And the result will be my points,
colon 59, two plus two, that's for just a number. And finally, two strings, of course,
becomes a string 1114. Like that. Let's run this. And indeed, all of my predictions were
correct. That was good. Otherwise, I would lose all my integrity. So I'm really happy
about that. Let's move on. Okay, let's imagine that you are working on an ecommerce website.
And this website sells shoes. So here you can see a Nike shoe with a purchase button.
The HTML is located here, of course, with an image tag the paragraph for the Nike shoe,
the button, but then there's also an empty error paragraph. And this is pretty common,
because in case there's an error going happening, for example, the purchase didn't go through
or some kind of bug costly operation to fail, or whatever it is, we want to render something
inside of this paragraph. So that is your job. In this challenge, you are going to set
up the JavaScript so that when the user clicks on the purchase button, you are to render
out something went wrong, please try again, in the paragraph that has the ID of error.
That's, of course, this one. And the button they will click is of course, that one, you
can see there is some CSS here, but you're not going to worry about that, because this
challenge is all about the JavaScript. And of course, also hooking up the onclick event
listener on this button, you should know how to do that by now. And you should also know
how to render text inside of a paragraph. So go ahead and give this one a shot. And
then of course, I will show you the solution afterwards as well. So there are two parts
to this challenge. First, there's registering that the user clicks on the button, and then
there is rendering out the text in the DOM. So let's take First things first the button.
So I'll head over to the button and do an on click event listener. And here we need
to specify which function we want to run. We haven't written any function yet. So let's
do that. We'll do a function. I'll call it Curtis, because that's what the user is trying
to do. Open and close curly brackets. Now I can take this function and specify that
when the user clicks the button, we want to call this function. Good stuff. Let's just
console log out. Button clicked. On this code, try to click the button and yes, we are rendering out button clicked
good. The next step is to grab a hold of the paragraph that we are going to render text
inside of. So we'll do let error paragraph and do document dot get element
by ID. I think in or like that. Again, we can do console log, just to verify that we
have grabbed a hold of the right paragraph, we run the code and bring up the console.
And yes, we can see that we have the paragraph. Then inside of the purchase function, this
is where we want to trigger the rendering of the error text, other error paragraph dot
text content equals this string right here. Now, if we rerun the code, click the purchase
button. Yes, something went wrong, please try again. And as you can see, it's rendered
out in red text, which is very common, because we want to grab the users attention and tell
them that something wrong has happened. And that is, of course, something we have specified
in the CSS. But this challenge is not about CSS, it was about JavaScript. So great job
of solving this, let's move on. Okay, in this challenge, you're going to create a very basic
calculator. As you can see, in the browser, here, I've set up the UI for you. Here, we
have two buttons, here we have the numbers, eight, and two. And then there's four buttons,
add, subtract, divide and multiply. If I try to click one of these, now, nothing happens.
What do you then of course want to happen is that, for example, if you hit subtract,
you're to take eight minus two, which is six, and then render that out in the sum here,
so that it'll say some colon six. Taking a look at the HTML, we can see that the numbers
at the top number one L and num, two L, that's the eight and two are simply spans However,
they are empty. So how can we have competent them when they are rendered? Well, that is
because I'm doing that in the JavaScript, first defining two let variables num one and
m two, and setting them to eight and two, and then doing document, get element by ID
fetching out num, one L and num, two L, and setting each of their text contents to num,
one and number two, and that's why we're rendering out these numbers moving on to the buttons,
you can see that they are very simple. Only the tag and the text, I have not created the
event listeners, because that's your job. And then finally, the span with the ID of
some L is where you are going to render out the result of the calculation. So summing
this up, you are to create four functions here in the JavaScript file, add, subtract,
divide and multiply. And then you need to call the correct function when the user clicks
on one of the buttons. So obviously, when the user clicks the Add button, you are to
call the add function and vice versa with all the others, then inside of the function,
you are to perform the given calculation. So in odd, you need to add num one a num two
together, and subtract, you will take num one minus num two and divide, and so on. Finally,
render the result of the calculation in the paragraph that has the ID of some element.
So go ahead and give this one a shot. And then of course, return back to the screencast
when you want to see my solution. Okay, let's do this. I'm going to start by
creating here an on click event handler and call this function add because when the user
clicks the Add button, we want to invoke a function which ought to be named up. And then
we need to create the functional function ad. Here, what do we want to do? First, we
just want to check that it works. And the code ad Yes, we are logging out now then we
need to grab ahold of the some paragraph. So I'll do let some L equals document, get
element by ID. The ID is some dash l like that. Here, I'm just going to see if it works
by doing some l dot txt equals num one plus num two. rerunning the code. And yes, there
we can see, we're rendering out 10 however, we wanted to render out some colon equals
10. So let's try adding some colon, plus num one plus num two, running record hitting add.
And now we have come into a situation where actually, JavaScript is turning all of our
three values into strings. As you remember, when you add strings and numbers together,
they're all turned into strings. What we need to do here is first perform the calculation
and then concatenate that with the screen. So we'll do let result equals number one plus
number two, because here we're only adding numbers together and JavaScript will treat
them as numbers and thus perform a mathematical calculation and not a string concatenation.
So then we can replace this expression here with result. rerunning the code, clicking
add, add Yes, there we go. Great stuff. Now, I'm a little bit lazy. So I'm just going to
copy this, paste it in, and do sub tract and simply replace this with a minus, add the
on click equals sub drags like that running the code, quaking, subtract, six, brilliant.
Now we'll just copy paste again divide should get this use the division symbol and multiply
should use the multiplication symbol. Now we only need to add the last two event handlers
vide is the name of that function. Bass hair and multiply is the name of the final function,
running the code trying to add it was 10 brilliant, subtract give sex, that's correct divide rightfully
gives four and multiply 16 we have made a calculator. Good job, you have all reason
to be proud of yourself now. And if you didn't manage to do this one, if you found that a
bit too hard. Now that you've seen the solution, just go back and try it again. That's great
practice and gives you the muscle memory you need. And when you're ready, I'll see you
in the next cast. He and welcome to building blackjack. I'm so excited about this one because
you are going to learn JavaScript while building one of the most iconic casino games ever.
Here is a sneak peek of the app we are going to build. And while it's not a full blown
blackjack app, of course, it does share a lot of the functionalities with blackjack
apps you can play on online casinos. Speaking of that, that's actually a huge market, people
spend over $20 billion per year gambling on online casinos. And personally, I love playing
poker and blackjack. I think my life actually peaked when I want 100 euros on a casino in
Prague in 2016 made me feel like such a gangster, we spent the rest of the weekend squatting
in front of fast cars, like this Mercedes, this Hummer, this BMW and this Bentley. So
vital this section, of course, is to make you feel as cool as I did in 2016. And with
that out of the way, let's just get started. Okay, so we're going to kick this off with
a challenge, you are going to create two variables, the first card and the second card, then you're
going to set their values to a random number between two and 11. So that's the values you
can draw from the deck of cards in blackjack. Secondly, you are going to create a variable
sum and set it to the sum of the two cards. So go ahead and do this right now. Okay, let's
do this. Start with the first card, we're gonna set it to six, and the second card after
nine, then the sum, of course, equals first card. last card. Let console log out the sun,
run the code. And yes, indeed, we get 15. Great job. Let's move on. Okay, so we are
ready to build the logic of our blackjack game. Now let's have a look at how blackjack
works before we try to formulate this in JavaScript. So the point of the blackjack is to get a
hand that sums up to exactly 21. And if you don't get 21, at least you want to get as
close to 21 as possible, but never above 21. Because if so you're out of the game. So here
are three scenarios, one where you have two cards on your hand, that's your starting hand,
and they amount to 15. So you're still in the game, no big reason to either cry or celebrate.
And then there's the other case where you have a king and an ace. And since the ACE
here equals 11, and the king equals 10. You've got blackjack. So Woohoo. And the third scenario,
we started out with a 10 and a six. And then you asked for new card, but then you ended
up at 22. So you're over 21. And sadly, you've lost your money. So now the question is, how
do we translate these things into JavaScript? Sadly, JavaScript isn't as smart as you are
who can understand this, but just hearing me talk about it. JavaScript is kind of stupid.
And it needs you to describe the logic 100% correct. So let's just do that. So you get
to see it in action. We start off with writing if and then open and close parentheses. And
then it's the sum of our cards that we're going to check to say if sum is less than
21, just like we were doing here. So this crocodile mouth is something you might recognize
from your maths class at school. And it kind of makes sense because here on the right hand
side, you can see that's where the gap between the teeth of the alligator is the largest
verse at the left hand side here, the gap between the teeth is the smallest. So small
value here, large value here. If this condition is true, meaning that sum is less than 21.
Well, then we add two curly brackets and tell JavaScript that we want to execute the piece
of code inside of those curly brackets. So we'll do console log, do you want to roll
a new card, since that's what you can do in this scenario, you are still in the game.
And you can draw another card if you want to. But there are cases where this isn't true.
And we need to account for those as well. We do that by writing, else F, an open and
close parentheses, and here we write some equal equal equal 21. This is else if sum
equals 21, then we want this code to be executed. This triple equal operator is different. From
this one right here. Here, we are saying that we want the sum to become first card plus
second card. But here we're asking is the sum strictly equal to 21? You say strictly
equal when you see three equal marks, and don't worry about why it's three and not necessarily
two. We're going to get back to that later. For now on just use three equal marks. When
you write elsif statements, we are checking if a variable is exactly some kind of value.
So if the sum is 21, what is the case? Well, who the player has blackjack folder for log?
You've got, like back like that. And then the third scenario, we'll do else if yet again,
some. What do you think we'll use here, of course, we'll use this one right here. Because
if the sum is larger than 21, then the user has lost, some is greater than 21, open and
closed, curly brackets, console log, you're out of the game. I got lucky, let's have these
emojis as well. There we go. Now, one little thing I want you to notice here is that here,
I have to use double quotes to wrap this, as I'm using single quotes to create this
you've and your words, because if I was using single quotes here, it would be completely
off because JavaScript would have thought that I was intending to close off this string
right here, when I'm not intending that I was just writing you've instead of you have.
So just a little digression there. Now let's run this code and see how it works. We'll
hit run. And yes. Do you want to draw a new card? We triggered this, which seems correct,
since I'm plus six is 15. And that is indeed less than 21. Let's try to do n and 11. So this is blackjack?
Yes. JavaScript triggered line eight, which is what we wanted. And finally, let's say
that we got 17. On the first two cards, and we really wanted a new card, we wanted to
take the times, but we bombed out by getting six, if so are some would be 23. And what
do you think will happen? Yes, this line of code should be run, I'm gonna run the code,
and boom, you're out of the game. Now a final thing I want to tell you about before we move
on is that could actually skip all of this code if we wanted to do like that. Because
if some it's not less than 21. And it's not exactly 21, either, meaning we've jumped to
the third clause in our if else clause, then it must be over 21 mean, there's no other
alternative in the entire universe. So there's no point specifying that some here should
be over 21. For this block of code to be executed, meaning we can just skip it. So do we have
if sum is less than 21, execute this if sum is exactly 21. execute that and In all other
cases, execute this, this will work as you see by running the code in the exact same
way. Okay, now that you know that, let's move on. Now it is your turn to write an if else statement,
you're to check if a person is old enough to enter the nightclub, which has a lower
age limit at 21. And then you are to log a suitable message to the console in both cases.
And by that I mean if the user is less than 21, or if the user is 21, or older. So I've
defined the age variable here and also written pseudocode. If less than 21, then a suitable
message would be for example, you cannot enter the club else meaning all other cases because
if they're not less than 21, it has to be 21 or above, then you have to log something
like welcome. Go ahead and give this a shot. And if you have forgotten how to write in
a false statement, just go back and rewatch the previous lesson. And notice here that
I don't have an else if statement in between here. I only have the first If and the final
else, not the elsif, which we had in the previous lesson, and that is because I want you to
think for yourself and try to figure out, well, how do you write this with only an IF
and an else and not the if else in between, let's give it a shot. And I will show you
the solution as well when you return back to the screencast. Okay, hopefully that went well, let's do this.
If less than 21 we have to do age is less. Remember this alligator mouth here, and 21
like that, this means the person is maximum 20 years old, then we are to do following
well, console dot log, you cannot enter the club, and then we simply do else. Then we
open close curly brackets. and here we can console log allcom. running the code we get
welcome not correct. Trying to lower the age to 20 we get you cannot enter the club. Now
a final thing I want to point out is that you could also solve this by using another
comparison operator, which is the less than or equal to that means a slightly different
thing though, because it checks that this value is less than or equal to 21. So if we
take this back to 21, and run it can see we get you cannot enter the club, which obviously
is wrong, they should be able to enter the club at this point. So if we're using the
smaller than or equal to operator, we have to use 20. Because then we include 20, that
is an upper range that is inclusive of that number. So now it works. Whether you prefer
using less than or equal to or just the less than is up to you, you just need to keep in
mind all that changes the entire expression. With that, let's move on. Let's practice if
else statements a bit more, because in Norway, we have this super cool tradition where when
you reach 100 years old, you get a personal birthday card from the king. This is the king
King Harold, the fifth of Norway. And in this challenge, we are going to code the logic
for this. So here it is in pseudocode. If less than 100. And here I'm talking about
the age variable, of course, then you are to log something like not illegible to the
console. Else. If the age variable is exactly 100, you're to log something like here is
your birthday card from the king. And else In all other cases, meaning they're over 100
years old, you get not illegible, you have already gotten one because if they're 105
years old, they got their birthday card from the king five years ago. Okay, go ahead and
give this one a shot. And then I will show you the solution afterwards as well. Okay, let's do this. If age is less than 100,
we'll console log, not likable. And then we have to do the else if and specify the condition.
Age is exactly 100. When we console log, here is your birthday card from the cake. And else
In all other cases, the person is over 100 years old, they have already gotten their
card, the previous birthday, so not electrical, let's run the code. Yes 100, you are getting
the card at 45. You are not legible. At 145. You are not illegible either. Finally, before
you leave, let's take a closer look at this triple equals here because it might seem like
a little bit of an overkill to have three equal signs after each other. And that is
a valid point, you could use two. If we run the code, it still works with 145. And actually
with 100 as well, it would still work, you are getting your birthday card. However, the
thing with two equals so called the double equals is that it's a little less strict.
So let's say that you by mistake asked in a string here as well, which has the same
value of 100. But it's a string and not a number. If we run the code, you can see it
still works. However, with the triple equals running the code, then it doesn't work. Now
it says not illegible, even though 100 is here as a number and 100 is here as a string.
So double equals ignores the fact that this is a string. And this is a number basically
converts this into a number if it's a number on the left hand side as well, so that this
entire thing would be true. However, that's not what we want. We actually want to be strict
in our code, which is why I would recommend you to only use triple equals ignore double
equals, this forces you, as a developer to be a bit more mindful about how you are checking
your conditionals, you need to make sure that if you're starting out with a number up here,
you're also comparing it with a number down in the conditional. But that's just good practice
being thoughtful as to what kind of data type you are using in your code. Just stick with
triple equals, and you'll be just fine. With that, let's move on. Okay, so now we're back
at our blackjack game. And you might have noticed that we've lost the code that we previously
had. Well, that's the point of scrim, but you are going to write the code, not me. So
I want you to rewrite the conditional that I created previously. But with a slightly
different take, you have to follow the logic that I lay out in the pseudocode here. So
you have to use in the first if clause, the less than or equal to operator, so you have
to set it to less than or equal to 20. And then in the elsif clause, you can use the
strictly equal to check if the sum is exactly 21. And finally, you're going to use the else
clause and not an else F on the third conditional, which I did previously. So go ahead and do
this. And if you can't do it, or want to see my solution just returned back to this screencast.
And I will show you how to do it as well. Good luck. Okay, let's do this. First, there's the if
sum is less than or equal to 20, then we are console, logging out this string right here.
And then we do else if the same as we did last time, some triple equals 21. That's the
blackjack case. And here, I'm lazy. So I'll just copy paste this one. And then this one
in here. And then finally, Mark doing elsif. And checking for the condition, just doing
the else all other cases, and then pasting in this, you are out of the game, string like
that. Good stuff. Let's run the code. And yes, we have 17 here, and we rightfully so
logged out. Do you want to draw new harder? Good stuff. If we try to hit one more time?
with another 10? We are out of the game? Good stuff? And how about for blackjack? Oh, great
job. Let's move on. Okay, so our game is coming along really nicely
here. However, there's a big problem. And that is, let's say that you are playing this
game and you get blackjack. So you get a 10 and an ace and boom, you've got back back
down here at line 13. You of course want to cash out your money and get the pot on the
table. However, at this point down on line 13 JavaScript has no way of knowing which
console log it logged out. It doesn't remember that. So what we need to do then is introduce
a new variable that keeps track of this state, you can call it the state of the game, like
has the user gotten blackjack? Or maybe house the user last, or whatever it is. So what
we then want to do is for the scenario, have a variable that reflects whether or not the
player has blackjack. And when I say whether or not yes or no, is there a data type in
JavaScript that you think might be suitable for describing such a state? If you guessed
a Boolean, a true or false, it is correct. So what we'll do sudo, let pass backtrack
like that. And set that initial value of course defaults because default, you don't have blackjack,
then here inside of the if clause that describes the blackjack case, we're simply going to
reassign the Hass blackjack value to true instead. Now down at line 16. If we log this
out, has blackjack value and then run this code, boom, you can see that we're both logging
out on line nine, and we have persisted the state. So the line 16, for example, can start
writing the code for taking the cash that's on the table that now is rightfully yours,
and then deposited into your account. So now we have an app that keeps track of the data
of the state in a much more sensible way. I want you of course to write this kind of
logic yourself. So in the next cast, I'm going to give you another challenge so that we can
keep track of even more of the state of this game. I'll see you there. Okay, so now it's your turn, and you are going
to make the state of our game a little bit more robust, because at this point, we're
only tracking if the player actually gets blackjack. If the player busts out and gets
22 or more, we're not tracking it. And obviously we have to do that. So I want you to create
a variable called s alive and start by assigning it to And then you're going to flip that value
to false inside of the appropriate code block. So there's three code blocks, the if block,
the elsif, block, and the else block. And you of course, then have to pick the correct
code block, and then write that line of code that flips the value to false. And finally
logging out to check that you're doing everything correctly. So good luck, go ahead and do this.
And then I will show you the solution afterwards as well. Okay, let's do this. starting up
here, we're going to create a loop variable called s alive and assign that to true, because
when you're starting out, the player is still alive. And at which point is the player no
longer alive, meaning out of the game? Well, that's obviously here in the else block, because
that's the case if the sum is 22 or more. So here, we'll do this alive equals false.
And then finally, we'll console log is alive like that. We got true, because actually,
we have blackjack, and rightfully so, player is not dead. How about if we pretend that
we add a third card here, really stupid idea because there was card after you've gotten
blackjack, but let's just pretend that run the code, and boom, false, no longer alive.
Great job solving this challenge. Let's keep up the pace and move on. Now that you've learned about Booleans, let's
take a look back at the conditional you wrote, because one thing you probably didn't think
too much about when you wrote your conditionals is that the expressions inside of the parentheses
would be translated by JavaScript eventually into a Boolean. So it would be either true
or false. That's always the case with expressions passed into conditionals. Because here we
are comparing two numbers, and one of them are either larger than the other, or they
are two equal numbers. So the claim you come with has to be either true or false. Let's
try to play this out using an example. For example, when you've gotten two cards, a 10,
and an 11, meaning you have blackjack, in that case, some will be 21. And the claim
you come with inside of the first if statement, obviously, that is a lie. Meaning it gets
evaluated to false. In the second condition, though, you're saying that sum is equal to
21. And we know we are going to translate the sum into 21. Because that's what it is.
So here, you're saying 21, triple equals 21? Well, yes, that is a true statements. So that
becomes the true Boolean. And here, you can read through it. If false, well, then we're
going to skip the body of this statement. Else. If true, yes, we like true, then we
are going to execute that piece of code. So this is essentially what happens when you
run the code with specific values for these variables. rewinding it back. What I want
to do now is stress test your comparison and Boolean skills. So I'm going to paste in a
bunch of console logs here, and then comment out our blackjack game. Now your job is to
look at each of these expressions, and predict whether true or false is logged to the console.
So write either true or false after these two slashes on each of the lines from one
to seven. And then of course, when you've given it a shot, run the code and see how
it went. And then I will do the same thing afterwards as well. Go ahead and do this right
now. Okay, let's do this. First, Fort cripple equals
three. Obviously, that's wrong. gonna log out false. Five is greater than two. That
is true. And 12 is greater than 12. No. 12 is not greater than 12. It's exactly the same.
So this will be a false statement. We is less than zero. Again, that's also false. Three
is larger than or equal to three. Yes, that will be a true statement. Because it's not
larger than but it is equal to. So 11 is less or equal to 11. Again, it's not less than
11. But it is equal to 11. So it's true. And three is less or equal to two, no three is
actually larger than two, meaning that this is going to be false. So this is my prediction.
Let's run the code. Bring up the console. And yes, I was right. Very good. Let's move
on. Welcome back, my friend. I hope you are ready for a new challenge because that is
Exactly what I have in store for you. Now, actually, it's a three part challenge, because
you are going to make our program a little bit more robust in the sense that it might
be that these console logs here that we're just throwing out into the void log into the
console and forgetting all about can be used later on down the line, or that we have some
reason to want to keep track of them maybe want to render it out at multiple locations
in the app, maybe there's some notification, and there's text, there's a log of messages
you've gotten. Maybe we want to repeat it, I don't know, there's tons of reasons for
keeping this data. Very few reasons for just logging it out. Want to keep it in a variable,
just like we've done here, with the house blackjack, and it's alive. So your three part
challenge is to first declare a variable called message, and then assign its value to an empty
string. And then you are going to reassign the message variable to the string, we're
logging out, notice here and I'm using some fancy words like I'm seeing the clear instead
of creative variable, I'm seeing a sign instead of set its value. That's because I think you
now we're ready to hear some of these fancy JavaScript words. Because there are subtle
differences between these words, like here, we are actually declaring the variable. And
then we are assigning it when we set the value to true. This is, after all call to the assignment
operator in JavaScript, and then naturally, so when we change a variable or assign it
yet, again, we re assign it. So I just want to use the correct terminology here. But I
think it's important that you don't get put off by all of these words, and think that
you have to remember them all you do not, it's perfectly fine to talk about this, using
your own words, create change, set the value, whatever, I just want you to also be exposed
to these technically correct ways of expressing it. Anyway, enough talk, as I said, step two,
you are going to reassign the message variable to the string that we're logging out. So I
don't want any more console logs inside of these three code blocks. Because the only
code block is the one you're going to create in part three of the challenge when you are
going to log out the message variable. So go ahead and give this your best shot and
then return back to this screencast when you want to see my solution. Okay, hopefully that went well. If not, no
worries, let's do this together. First, we'll start by declaring this let variable, we'll
call it message. And we'll set it to an empty string. Then on line 1113, and 16, we need
to replace the console. log with a message equals like that, and also remove this, close
parentheses, do the same thing here, move this one, and the close parentheses and then
write message equals, finally, here as well. And then we are ready to log it out. Down
here at line 21. While log out the message, run the code. And as you can see, we're logging
you are out of the game. That is correct, because we have this really stupid move where
we got blackjack, but we asked for new card to remove this, run the code. Yes, you have
blackjack, again with for example, 14. And yes, I can now grow a new card. So great job
reaching this far. Let's move on. Okay, now it's time to fix our biggest flaw in our blackjack
game, which is that it has no user interface. If we want this to be a hugely successful
online blackjack game, it has to use HTML and CSS so that users can play it via a browser.
And I've actually set up the basics for you. Here, you can see an HTML file with a head
and a body. And then inside of the body, we have an h1 with text blackshark. And also,
we are linking to the JavaScript file here on line eight. And as you can see, if we bring
up the mini browser, this just renders out the h1 tag. So your job now is to link this
HTML file to the CSS file. You can see I've created just one CSS rule in this file. And
it will be applied, changing the color of the title when you manage to add a link to
the CSS file here on line five. So I almost every single time have to search on Google
for how to link to CSS from HTML, I end up at something like this. So I want you to do
the same thing. And one tip would be to find this w three schools right here, as they often
pop up on Google and contain the necessary information. So go ahead and figure this out
on your own, and then I will show you the solution afterwards as well. Okay, hopefully,
you nailed that one. If not, no worries, let's first check out Google. Then if we click into
the W three school site, you'll see the following. And it tells us that there are three ways
to insert CSS external, internal and inline. And we are using an external CSS file. So
we want to scroll down to external CSS. If we do that, we see The code here and the line
we're looking for is this one, Link REL equals stylesheet href equals my style dot CSS. Okay,
good. Let's do link rel, and that is short for it relation. So what is the relation between
this HTML file and the current file, you're going to point two now while it is that the
file you are pointing to, say stylesheet, because as you remember, CSS is short for
Cascading Style Sheets. And then it is the href, which in our case is index dot CSS,
we are in the same directory. So we don't need to navigate into a folder or anything
like that will just write index dot CSS. And the href attribute is something you should
be familiar with by now as that's also what we use when we are creating links. Now let's
run this code boom, you can see the color has changed, meaning we are indeed importing
this stylesheet. Great. Okay, now it's time for you to style this app. Because as you
can see, it looks kind of bad. I've added a few more paragraphs here, as you can see
one, which says want to play around and has an ID of message shell, and then just two
other paragraphs that will display the cards and some eventually, your job now is to take
this HTML and make it look like this. If we head into the index dot CSS file, you can
see it says complete the CSS styling according to the provided the sign in here I've created
two new selectors for you the body and the message. Oh, and the thing is, you can create
this entire design by only using these two selectors. So that's why I have them here
for you. I've also added a table dot png, inside of an images folder. That is for the
zero background that we are using here. And you've learned all about how to do this styling
in previous modules of the career path. So if you struggle, you can go back and rewatch
some of those lectures if you want. Now, before you start solving this challenge, I'm going
to add the font family for you. Because we're using the treble Shea font here. And you haven't
really learned how to do that. So I'm going to do it for you. We do font family up in
the body. And here I specify treble Shea. And as you noticed, what happened now was
that the editor gave me a bunch of other fonts as well. And
this is called a font stack. And the reason we use font stacks, because if your operating
system doesn't have treble Shea ms installed, well, then your browser can't show that font,
unless you've also imported it from Google fonts, for example, or included in your project,
neither of which we have done right now. So if your operating system can show Trevor Shea
ms, then we're telling it to look for new CSS Unicode, then, if you don't have that,
either, we'll look for Lucy around they and so on, and so on. So it's kind of ensures
that at least we'll find a somewhat similar file as it moves downwards in the stack. And
at least find a sans serif font here, which is our final choice. But let's start with
fonts there, I don't want to get deeper into it. Now we have the crib sheet font visible
and hopefully it's visible on your end as well, because crochet is one of those fonts
that are so called web safe, meaning that almost all operating systems have them installed,
so it's safe to use. Now, I want you to take a look at this design and add whatever CSS
you need to the body and the message shell so that you turn this boring page into what
looks much more like a real blackjack game to go ahead and do this right now. Okay, hopefully
that went well. I'm gonna start with the background image. So I'm gonna write a background image,
then fetch this table up PNG here, I can do URL open and close parentheses, then navigate
into the images folder, grab ahold of the table dot png, like that. Now we can see we
have the nice background. However, if I drag this wide, I can see that some point we reached
the end of the image and CSS adds the image yet again, after that, we get this ugly looking
line we should don't want, we instead want to use the background size property and set
that to cover. Now no matter how wide you make it, these image still covers the full
width. Okay, next step is to center this text and make it white. So we can do text align
center to center everything and polar white like that. So with this, we are turning everything
into right, except for the atrium, which you can see it here we have specifically specified
that the atrium should be colored goldenrod and that overwrites the color right on the
body element. Next up, you see here the text is a bit bolder, so we want to do that as
well. We want to do font, weight, bold like that. Starting to look good. There's just one final thing to start you
can see the message element which is The message for the user is an italic. Here, it's still
just normal. So in the message l will do font style and set back to italic. Like that. There
we have a nice looking blackjack game. So with that, let's move on. Okay, so now we
need to enable our user to click a button to play the game. And we're going to do this
through a challenge. Of course, I'm really excited about this one, because it includes
both HTML, CSS, and JavaScript. So this is the first time where you'll use all three
languages to solve a problem. And the reason this is so cool, is because this is how it
works. In real life, when you get a job as a professional developer, you'll juggle between
HTML, CSS, and JavaScript all the time. And this is an opportunity to start practicing
exactly that. So it's a three part challenge, starting here in the HTML, where you are going
to create a button that says start game, and it should call a start game function when
it's clicked. So obviously, then you also need to create that start game function, you'll
do that in the index dot j s. Here we are to create the start getting friction, and
move the conditional below line 11 to 20 knots, these lines into the body of the function
so that this code is run when the button is clicked. And then finally, you have to make
the button look good for the user, you are going to style it according to the provided
design. And that is exactly here, you can see the Start button. So just click to open
this slide whenever you need to take another look at it. I'm doing this translating a design
into CSS is something the front end developers do every single day. So it's great practice,
I've given you three values for properties here is the color of the text that should
have this hex value, the width should be 150 pixels, and the background should be golden
Rob, same as the text color on the A Tron. This is a big one. So I can totally understand
if you'll struggle a bit going through this one, but give it your best shot, and then
return to this screencast when you want to see my solution. Good luck. Okay, hopefully
that went well. Now, let's do this. Here, we'll do like up opening tag, and then I'll
do the closing tag as well. And inside All right, start game like that. Let's run the
colon looks not particularly good, but it's at least there and it's actually centered.
The reason for that is because here on the body, we are centering all of our texts, and
that also centers the button. Next up, we need to call the start game function when
it's clicked. And if you remember how that was, then you'd write on click equals, and
then the start game with open close parentheses inside of a screen right here. So when the
button is clicked, we're going to call or invoke the start game function, then we need
to create that function. And if you remember how to do that, it is through the function
keyword function, start game, open and close parentheses and then curly brackets for the
body on the function. Inside of here, we are going to take this code, copy it, paste it
in, I'm going to give it a tab so that it looks better like that, and remove the empty
lines. Now we have this let's rerun the code and see if it works. Yes. Previously, we got
this console log just by refreshing the page. But that doesn't happen. Now I have to actually
click the Start game. Then we run this then we console out the message. Great job. Now
let's move on to the CSS. Okay, this is how we want it to look. Let's take the first three
provided the sign hints and see how close we get just by implementing them. next color.
Notice the color property that hardly see it since the text is so thin, but that's okay.
For now. Let's just set the width with 150 pixels like that. Okay, looks a little bit
better. And the background should be golden Rob. Okay, so looking a little bit better.
Not quite this design here. As you can see, it has some space above and below the text,
versus this one is much more cramped. Let's add that. And if you remember from the CSS
section, you could add that space by using the padding. That's padding top and padding
bottom. Five pixels. looks about right. padding. Five pixels there as well. Yeah, not too bad.
However, as I mentioned, this text is really thin. And here it's much thicker. So let's
actually do font weight. bold. Yes. About looks much better. Now, the next thing I want
to fix is the border around the button. Because you can see it's totally clean here and has
no border. But the default styling that our browser provides has this little border. So
we want to do border, none. Okay? Now it's actually pretty similar or almost identical,
but only one thing separates them. And that is that you can see the edges are sharp on
this one, where's the edges are a bit rounder on our provided the site. So that is the border,
radius. And pretty subtle. So I'm going to try to pixels. And yes, that looks as far
as I can see, identical. So this was a huge challenge. And you had to context switch between
HTML, CSS, and JavaScript. So be really proud of yourself for reaching this far. If you
struggled, and didn't really manage to get to the finish line on your own, I think you
should just go back and try it again. Now that you've seen my solution, that's a great
thing to do to reinforce what you've just learned, whatever you do, I will see you in
the next lesson. Okay, so now our player can click the Start
game button like this. However, we're only logging out the message. Obviously, we don't
want to do that, we want to display that info on the page, along with, of course, information
about the cards and the sum. But starting with the message, I want you to solve a two
part challenge. First, you are going to store the message l paragraph, that is this one
right here in a variable called message l using the camel case naming convention. And
then you're going to display the message using message l dot txt content, then, of course,
you can remove the console log right here, since we don't need it anymore, as the message
will pop up here in our app instead. So go ahead and give this a shot and return back
to me when you want to see my solution. Okay, so the way to do this is, if you remember,
first by creating a variable with length message, l, and then using the document keyword, dot
get element by I Li passing in the ID, which we can see from the HTML and just copy from
there actually paste them in here. That's always Ctrl logging to see that we are on
the right track running this code. And yes, there we can see we are logging out to that
element. Now it's just a matter of deleting this line being messaged l dot text content.
And what we want to set the text content to. We want to set it to message like that. If
we now run the code, hit the start game button. Yes, there we go. Do you want to draw a new
card? Great job. Now there's one thing I want to do before we round off, that is actually
to remove these emojis because when they are italicized, they don't look that good. And
while that isn't the most complicated thing to fix, it's not something I think you should
learn. Right now, I want to keep up the pace. And also when we see this text here rendered
on the page. It's kind of our dealer speaking to us in metallic text. And I don't think
our dealer should show that much emotion. So it makes sense to remove these modules
like this. And also maybe make it a bit more neutral dealers will just tell us that we
have blackjack on shout out. Whoo. So makes more sense on your card. Yeah, looks good.
If we get blackjack. Yeah, I think that looks good. So with that, let's move on. Okay, so
let's make our game a little bit more useful, because now you can click the Start game button.
And indeed, we get the message from the dealer. But we have no idea what are some cards are,
so we obviously need to render that out. And we're going to start with the some though
it's a three part challenge where you first have to head into the HTML. And there give
the some paragraph that is this one, an ID of some dash L, then you are to store the
sum paragraph in a variable called sum l like this in camel case, finally render the sum
out. So here I'm talking about the actual numeric sum on the page using this format,
so some colon and then the given some you have up here. So here you have to keep this
text which is already in the DOM intact, but we have done that before. So hopefully you'll
manage it. If not, no worries, you can just revert back to this screencast and I will
show you how to do it as well. Go ahead and give this your best shot right now. Okay,
let's do this. First, we'll give this an ID of Some bash L, moving over to the JavaScript
will do let some l with the camel case this time, do document, get element by ID open
and close parentheses and the quotes passing in the ID that we just added to the HTML element,
some bash L. Now, just to be certain, let's just console log the sum L, from the code.
Yes, indeed, we are grabbing the element. And then we need to render out the string
of some, and then the actual sum, which in this case is 14, from this variable up here,
into the element itself. And the way I'll do that is I'll use some L, and then text
content, which you should see in a few times by now, and set that equal true, not only
the sum, because if we do that, let's rerun the code and stop the game, then we simply
just clear out the existing text verse, we want to keep the sum there. And we can do
that in multiple ways. But we all do it is simply just write some colon space, and then
plus here. So let me just reconstruct the default text as well, in addition to the
sum, I think this is a nice way of doing it. If we run the code, stop the game. Yes, there
we go. Now, before we move on, I want to teach you about a another way of grabbing elements
from the DOM. Because we've used to get element by ID a few times now. So I'm assuming you're
comfortable with this technique, and are ready to learn another one. And that is something
called the query selector. And to learn that, but comment out this one, and copy it to a
new line where we can change it. And here, instead of get element by ID, we'll do a query
selector like that. Since this is a more dynamic method, we have to be a bit more specific
in the value we pass into it. So here, we actually have to pass in a hashtag in front
of the summer to tell the query selector, that it's actually the element with the ID
of some URL that we're looking for. Because unlike the get element by ID, we're not specifying
that it's an ID. In the method name, it's just called query selector, which is kind
of a broader expression. So query, that's another word for question. And selector that
refers to CSS selectors. So we're kind of asking for an element by its selector. And
then we specify the given selector inside of the parentheses. So here, if we run this
start gate, the exact same thing happens. Now if you've forgotten what a CSS selector
is, we can head over to the CSS, and it's these guys right here, the body, that's just
selecting the body element, this one. And then there's the id selector right here, you
can see we are using the hashtag, grab the message L, because this paragraph has an ID
of message dash L. Likewise, some has an ID as well. So we're using the hashtag, to tell
query selector that this sum dash l comes in the form of an ID. Now, this means that
we could change this to a class instead. However, then we also have to change this hashtag and
replace it with a dot. Hopefully, you remember that the way to select CSS classes is by using
the.we. Run this, it still works. And actually, we could even pass in just the element name
as well, we could do body right here. However, it would break our hop since we're now Okay,
just clearing out the entire body when we are running this piece of code down here on
line 11, because now somehow actually refers to this entire body. So as you probably understand
queries lecture is very powerful. And you will see it used in a lot of tutorials here
on schema master right now, I just wanted to show it to you so that you are prepared
once you see it in other tutorials and out in the wild. In the near future, I am going
to stick with the document dot get element by ID as not just a job for us. And it's also
a very simple method to understand. So I'd like to avoid the added complexity of jumping
between get element by ID and query selector if we can. Without let's just move on. Okay,
let's continue building that muscle memory of yours you are going to do almost the exact
same thing as you did with the sum. But this time with the cards because obviously when
you start the game you can see or some now but you can't see your cards that has to be
fixed. So it's the same three part challenge starting in the HTML where you are to give
the cards paragraph, an ID of card cell, then in the JavaScript, you are stored the cards
paragraph in a variable called card cell with camel case, and then finally rendered out
in this format right here. So go ahead and do this right now. And then I will show you
how I will do it when you revert back to the screencast as well. Okay, let's do this first,
giving this an ID of cartel. Then storing the card paragraph in a variable
called also cartel, let cards l in camel case, this time, document dot get element by ID,
passing in cards, bash shell like that. Now, I'm just going to jump straight to this line
here and do cards l dot text content equals constructing the entire contents of the paragraph
this time, so we're clearing out the text that's already there and replacing it with
a new cards column. This will be actually cleared out and replaced using JavaScript,
then plus the first card and then have to add a space between the first card and the
second card. And then the second card like that. If I run this code, start the game.
And there we go, we have both of the cards rendered out. Great job. Let's move on. So
our game really starts taking shape. Now we hit the start game button, and we get the
message the cards in the sun. However, the critical part of blackjack is the ability
to draw a new card from the deck. So we need to start building that feature. And we are
going to first begin with creating the new card button, as you can see on the slide here.
So in this three part challenge, you are going to first head into the HTML and create that
new card button, then make it run a new card function when it's clicked, and then in the
JavaScript, you have to create that new card function. And for now, it should just log
out drawing a new card from the deck. Then in the CSS, you need to make sure that when
these two buttons are rendered out vertically, like this, so above each other, you'll need
to make sure that this small space between them is added because it won't be added by
default. Now, if you enlarge this browser, make it wider, they will render out besides
each other. But you are not to worry about that layout. So make sure that you keep this
browser window a little bit narrow so that the are rendered out under each other. And
then make sure that you get this little gap here. So this is again, a very holistic challenge.
You're to write JavaScript, HTML, and CSS just like it is out in the real world. So
go ahead and give this your best shot right now. Okay, hopefully that went well. If not, no worries,
let's do this together. In the HTML, we are starting with the button opening closing tag,
new card like that, I'll just render it out. Oh, there we got it actually got them beside
each other, we want them vertically like this. So there, we can already see that
we are missing in the gap, but that we want it. That's the CSS or the challenge. Let's
continue on with the HTML and get that wrapped up. We'll do on click equals and then run
this new card function which we haven't created yet, which we are going to create right now
down here. function, new card open and close parentheses. And then the curly brackets for
the body of the function inside here, logging out this string got provided in the comment
like that, I will run this code hit new card. And indeed, we are logging it out. Now final
step is to add this gap right here, we need to head into the CSS. And there are multiple
ways to do this. One way is to just say that we want any button to have a little bit of
margin below them. So this is about four pixels. So we can do margin bottom four pixels like that there
we see that our button works. Alternatively, let's say that we in some case, end up with
a situation where something comes too close to the button on the top side of it. Well,
maybe we need some margin on top of it as well. We find now add margin bottom and margin
top four pixels here, margin top four pixels, what you'll see is that the gap here became
twice as wide because it has the top margin that pushes it down, and also the start game
button that uses its margin bottom to get the gap even larger. So what we then instead
can do is take two pixels on each now we have something that looks very much like this.
We have created our buttons so that they always have some space below and above themselves.
I think that makes a lot of sense as buttons usually want a little bit of space around
them. With that, let's move on. Okay, let's make our new card function a bit
more useful, because now it's just rendering out the string for people wanting to do is
to actually draw a new card, and then add that new card to the sum, and then rerun the
code that is inside of the start game function so that the sum is added to the page. And
actually later down the line, we also want to show the new part of course, but as for
now, we're just going to worry about the sum. So this is a three part challenge where you
are to first create a card variable. And we're still just working with hard coded card variables,
you're just going to coat it to a number between two and 11, then we are going to add this
new card to the sum variable. And the sum variable as the one up here, of course, which
currently is the first card plus the second card. And in this case, it will be plus the
third card as well as you need to plus equal the sum variable. And then finally, you are
going to just call the start game function. Because what does the start game function
actually do? Well, first, it renders out the two cards. In our case, now we'll have added
the third card. So this will still be wrong. But line 13 will render out actually the new
sum, because at this point, some will have changed since we will have modified it down
here. And then it'll show the message based upon the new updated some. Actually, it seems
that we can use this start game function even after we've drawn a new card. And thus, we're
going to rename it a bit later. But for now, let's just keep it how it is. and your job
is just to call the start game function here on line 33. So go ahead and give this challenge
your best shot. And then I will show you the solution as well afterwards. Okay, let's do
this. So, let card here we'll set that to a random number between two and 11. I'll do
seven, and then we're going to add the new card to the sum variable. If you remember
how we add numbers to an existing variable, it's via the plus equal operator. So we'll
do some plus equal card, and then we'll call start in. So again, like that, let's rerun
the code first to start game. Okay, do you want to draw a new card, I happen to want
to do that. So I'll hit new card, and boom, I drew the seven card, which then made the
sum reach 21, which then again, made our dealer tell us that we got blackjack. So that is
exactly what we want. Now, let's see what happens if we instead of a seven, got an eight.
For now, rerun the entire code, start game and then hit new card, bam, then we're out
of the game since we have some equals 22. And if we got a six instead, rerun the code
start game your card, then we still get the Do you want to draw a new card text since
we're still below 21. Now I can actually hit the new card yet again. And then we are out
of the game. Now we're at 26. So this works for multiple cards. Of course, it's only the
sum that's reflected right now, not the card. So we'll have to fix that in a bit. But for
now, let's just move on and first fix this little problem. That's the start game function
name doesn't really make sense anymore. Since we're calling start game here at a point where
the game has already started so semantically, it doesn't really add up. So let's move on
to the next cast. So the problem now is that the start game function is triggered both
when we hit the start game button, which makes a lot of sense, but also when we click the
new card button, because even though the new card button triggers the new card function,
which is this one right here, that function itself calls start game as well. And while
this makes sense, because we want to run this code, the fact that start game still is called
start game doesn't really make sense. Because if another developer comes in here and looks
at that code, he'll be like, Why are restarting the game all over again, when clicking a new
card that doesn't semantically add up. So what we want to do here is actually just change
the name of the start game function, for example, to render game, because that's essentially
what we're doing, we're rendering out the current state of the game. So we can do render
game, just rename this one. And this one does that. So far, so good. But then the problem
becomes that we're actually calling start game here. And we could do a render game like
this. But actually, I want to keep this stock game function intact. Because down the line,
there might be some other things you want to do in this game initialization function.
So I want you now to create a function that uses the name, start game and then just calls
or invokes render game. That's all it should To show that this start game button will work,
because now I can see it doesn't work. When I click it, we're actually getting a reference
error saying that start game is not defined, because we're trying to call a function that
no longer exists. So go ahead and create the start game function here on line 12. And make
it just call this render game function right here, go ahead and do this right now. Okay, hopefully that
went well, the way to do it is through function, and then start game, open and close parentheses,
open close curly brackets, and inside here just called render game like that. let's rerun
the project, hit start game, and yes, now it works again. Great job. Okay, so now we
need to fix up with the rendering of the carts. Because if I hit start game, and I get the
two cards out and then hit new card, indeed are some increases, but our cards paragraph
are displaying only two of the three cards we've pulled from the deck, because we have
a 10 and a four, and a six, whereas we're only showing the 10 and the four in the browser,
because that is hard coded here to only do that, no matter how many cards we pulled from
the back, this line 16 will always just render out the first card and the second card. So
this line here in pseudocode says render out first card and second card. But what we instead
need is something that says render out all the cards we have, regardless of how many
cards if we have five cards to render out five cards, if we have two cards that should
render out two cards. But that's not possible with the current implementation. And what
we need is a central way of storing all of our cards, we need to store all of our cards
in one variable, regardless of how many cards it is. And the way to do this is actually
to use what's called an array, which is essentially a list of items. And I'm going to create an
array here, and it's totally okay, if you now feel confused, I just want to give you
a little sneak peek at it, before we take a deep dive and give you some practice on
it. I'm gonna do let cards equals and then open and close square brackets. That's the
notation for creating a race and inside of these square brackets, I'm going to paste
the first card, and then a comma, and then the second card. So this is now a cards array
that includes both cards ordered by the first card first and the second card Second, you
can call this an ordered list of items. Now we're down at what's line 18 now and replace
the first card by referring to the array instead. And doing open and close square bracket and
zero. Don't worry about that you understand that in a minute. Let's just now do the same
things for the second card will be cards open and closed square brackets, and one. This
is referring to this one right here. And one is referring to this item right here. And
that is because arrays are so called zero indexed, they start at zero and one. And if
we add a third card here, that would be index number two, but we don't have a third card.
So let's remove that. Now even though you might feel a little bit confused, now let's
just run the code, hit the start game and see yes, that still works. So this way of
doing it was the exact same as what we had previously, when you just hard coded in first
card and second card like this. Now this opens the possibility later down the line to render
out all of our cards in a dynamic way inside of the cards element regardless of how many
cards we have inside of our carts array. So almost a lot of information. Now we're going
to take a step back, work with race, get your hands dirty, so don't worry, if you didn't
quite understand this as you will surely do that after the next few lessons. Okay, so arrays are ordered lists of items.
However, that's a little bit abstract. So let's instead look at a real world product
and see if we can recognize any components that most likely use a race as a data structure.
So here we have a LinkedIn profile. This is Justin, he's a previous scribus student. And
looking at this, there's immediately multiple components that most likely use arrays to
render stuff out. You can see here on the right hand side, there are some promotions
actually three of them, and that's basically a list of items. And while their order might
be a little bit random, they still have a specific order. Likewise, with the people
also viewed here, that's a list of four people. Let's also scroll a bit down. Here we can
see even in the main section There's this component that says featured that is featured
posts. And that's basically just a list of items. So LinkedIn probably uses an array
to describe this data in JavaScript. So actually, let's just create that array, let featured
posts like that then equals opening closed brackets. The first one was actually just
in sharing the Netflix clone he built through a course here on scramble, and he actually
deployed it as well. So he's going above and beyond to check out my Netflix, clone like
that. The second one is actually a link just in the shared to source code, he's pushed
to GitHub, which is also a great thing to do, if you want to attract employers. So here's
code for my projects. Simplifying, of course, the data here because there are multiple parks
have this there's an image, there's text, there's comments, and so forth. But as for
now, we're just simplifying it into streets. The third item here is actually just in sharing
the portfolio he has built through a scrim, of course as well. So I've relaunched my portfolio
like that, there, we have an array with three items. This line is pretty long. So sometimes
you'll see an array formatted like this, as it makes it easier to see that it is indeed
three items. And a key thing to observe here is that we add commas after the items, but
not after the final item. So only between items, basically. So going back to LinkedIn,
there are tons of components here, that's probably utilizes a race, for example, the
work experience as a list of previous jobs, or licenses and certifications. So that's
a list of licenses, you can see the front end path right here, and skills and endorsements.
So a ton of examples. Now what I want you to do is to create an array that lists your
experience, or education, or licenses or skills, or something similar you are to choose what
you want this array to contain. But try to think how can you best describe your either
experience education skills, or whatever in a way that would make your LinkedIn profile
look tempting for recruiters as that's a smart thing to think a little bit about already,
even though you're very early in your coding journey. So go ahead and do that. And remember
that the items should just be strings, just as I've done up here, go ahead and do this right now. Okay, hopefully,
that went well. Now, I'm going to do that as well. So I'll do let and then experience. That's what I want to create my array about
my work experience. And I'm currently the CEO app scrim ba. Before that, I was a front
end developer at sometta. That's a Oslo based company for seafreight analytics. And also,
as you probably remember, from our subway counter app, I worked as a people counter
out in the cold, a company called Knorr stock. So that is my experience. Now, before you
move on to the next cast, I want to highlight the importance of actually being able to describe
your background and your skills in a good way on LinkedIn, just in here, the person
behind the LinkedIn profile we looked at, he actually lost his job in the petroleum
industry due to the coronavirus pandemic. And less than one year later, he now works
as a professional software developer. And as I said, he did that mostly through scrim
Ba, and was a super engaged student at our discord channel. And what's so cool about
how he did it is that he sent out over 100 job applications without getting much luck,
then went into optimizing his LinkedIn. And then suddenly, he got two job offers. And
the job he got actually came through a recruiter that found his LinkedIn profile as a result
of keyword searches. Actually, he ended up tweaking his LinkedIn profile so that he attracted
the right recruiter who got him an amazing job as a developer. So I wanted to share this
with you. And if you click on this image, you'll be taken to the page for the podcast
interview with did with Justin, so that you can listen to his story if you want to. For
example, when you're riding the bus or out walking or cleaning or whatever, I don't want
you to interrupt the course and listen to this. Instead of coding. It's more important
that you code. But you can keep it in mind for next time that you have half an hour or
something. Because I think you'll learn a ton about Justin who at the age of 33 did
his career shift. So with that little plug out of the way less important thing to know about race is that
they are so called zero indexed. And that means that you want to grab the first item
of the array, you do it through using the zero index, not the first index. And let me
show you what that means in practice beats posts. That's our rate. And I want to grab
the first item, the checkout mine Netflix clone. I'll do that through open and close
square brackets, and then passing in the number zero right now console, log this. And we run
the code, you can see yes, that we are indeed logging out that string. So this isn't entirely
intuitive since we as humans normally start counting at one. But in the race, you start
counting at zero. So if this is the zeroeth index, which index does this item have? Take
a guess? Well, it has the index of two, even though it is the third item, I run the code.
Now see that passing into logs out, I've just relaunched my portfolio. So here is the zero
index. This is the first and here is the second. Now, with this in mind, I want you to practice
this. So you are to take my experience array here and log out the following to the console.
And in this order. So we are to start with the front end developer in this net, and then
the people counter and then CEO, what scramble. So first, this one, then this one, and then
the first one. So you have to write three console logs, and place them in order here,
starting from line 18. So that I'm sure that you actually understand the concept of a race
being zero index, I'm going to comment out this one right here, so it doesn't disturb
you. Now go ahead and solve this challenge. Okay, hopefully, that went well. Let's do
this together. We're going to do console log, I want the front end developer at sonet. Ah,
that is not the first but the second item. And in terms of indexes, it's the zeros and
then the first index, so then I need to do variance. Okay, copy this one, paste it in
again. Now I'm going to log out the third item, which is the second index. So that is
experience. And finally, I'm going to log out this item right here that has the index
of zero. If I run this code, you can see in the console that we are indeed logging out
the items in this order. Now, before we move on, I'm going to confuse you a little bit.
Because let's actually delete all of this, this, remove the console and just go back
to this featured posts. If I now do featured posts, dot length, then console dot log this
out, which number do you think we'll see printed to the console? Take a guess? Well, the answer
is three. And that might be a little bit confusing, because I've just taught you that arrays are
zero index. So the first is zero, the second is 1/3 is two. So it would be natural to believe
that the dot length property of this feature posts is two because the final index is two.
But whereas indexes are zero indexed, the length is not zero indexed, we count the length
of an array in just the same way you would count anything in life, which is starting
at the number one. So that also means that the length property of an array is always
one larger than the final index. So this is one of those things that are a little bit
unintuitive and confusing when learning JavaScript. And you probably will mix it up a couple of
times. That's not a problem, just trust me when I say that, eventually, this will become
second nature for you. So let's move on. Okay, up until now, or erase have either included
only strings, or only numbers, whatever, they're not limited to that actually put any data
type you want into an array, and you can mix as much as you want. So you can think of an
erase as kind of a composition of multiple data types and their values. So this is why
arrays are what we call a composite data type. You can say it's composed by its items if
you needed to make semantically sense. And you'll often hear this also referred to
as complex data types, that is erase and also for example, objects, which you're going to
learn about later. They stand in contrast to the primitive data types you have worked
with, up until now. The three primitives you have learned are strings, numbers, and billions
because they are more primitive than arrays. They're not composed of many other data types,
which are race off an hour. So one analogy you can use is that the primitive data types
are the Lego blocks versus the array, the composite data types. It's kind of like the
full Lego model. For example, after you've built a little house with your Lego blocks.
But anyway, you shouldn't worry too much about this. If you find it a little bit abstract
and complex, as a developer, you don't go around thinking about Oh, is this a primitive
data type or a complex data type, it just becomes second nature and you don't even think
about it. So you shouldn't be put off by this, even though it's a little bit theoretical.
Instead, I think you should just practice, I want you to create an array that describes
yourself and use all the three primitive data types that you've learned so far. So it should
contain your name, which is a string, your age, which is a number, and whether or not
you like pizza, which should be a Boolean. So go ahead and do this right now. Okay, hopefully, that went well. Now, let's
do it together, I'm gonna create an array called pair. And my name is pair, Harold Morgan,
I am 35 years old. And I do happen to like pizza. And I especially like pizza with pineapple.
It's the best though I know that a lot of you don't agree with me. So let's not get
into a discussion about that, let's just move on with the course. One of the most common
operations you'll perform on a race is adding items to the end of it. That's, for example,
what you're going to do in our blackjack game, where you start with two cards, and then you
want to draw a new card that'll naturally then be put at the end of the array, for example,
six. However, the way to do that is not through actually changing it by rapidly, which I did.
Now, you use a method, which is called push, which allows you to well push things into
the array. So you do carts dot push, and then open and close parentheses, and inside of
these parentheses, you place whatever you want to push. So for example, six, if we now
saw log the cards underneath our push operation, you can see we have added six to the array.
So this here is actually called eight method, which is just a fancy way of saying a function
on an object. And you haven't really learned about objects yet. So don't worry about if
you think this sounds a little bit abstract, but this operation here is pretty similar
as the console dot log, and then passing in, for example, hello, do you think we have the
first object cards or console, that we have the methods to either log or push, then we
have whatever we pass into these methods when we call them. So this hair cards push is conceptually
very similar to what you've been doing all along. Let's now make sure that you build muscle
memory on this by solving a challenge. So I want you to imagine that you're building
a chat application, for example, the one I showed you here on LinkedIn, and the data
structure we'll use is, of course, a race. And we'll pretend that each of these messages
is an item in the array. So when someone types in a new message, and since it, well, you
want to push that new message to the array. So here you are to push the new message variable,
that's this one down here, into the messages array. That's this one here. And then you
are to log out the array to just verify that you actually succeeded in pushing the item.
Go ahead and do that right now. And then I will show you the solution afterwards as well. Okay, hopefully, that went well. Now, let's
do this, Lw messages dot push, and inside of the parentheses will pass in a new message
like that referring to the variable and not the hard coded value, which we did up here
when we passed in six. So a little bit different, but still the same concept. Now, let's console
dot log messages, and then run this code. If we bring up the console, we have pushed
the new message to the array, because we're logging out the array with same here at the
end. Now, a little mini challenge before you leave, let's say that you want to regret sending
this message, same here. And you want it to remove it from the messages to rate. How can
you do that? If you haven't learned this yet, this is a golden opportunity for you to google
it out and try to figure out how can you remove the last item in an array? So just see if
you can find the answer on Google and then try to remove the last item of the messages
array here on line 18. Go ahead and do that right now. Okay, maybe that's worked, maybe not, if not,
no worries at all. This is just a bonus. What you do is do messages, dot pop, and then open
and close parentheses. Now. If we log the messages again, and then run the code to open
up the console, you see, we are logging two versions of this array, one from line 15,
where the same hair string is included as the last item. And once again from line 19,
where the array is back to how it originally was like this. So pop is kind of the opposite
of push, and not as commonly used. But I just wanted to give you a sneak peek at it as you
might come across it here and there in your development journey. With that, let's move
on. Okay, now it's time for some repetition, you are going to do the exact same thing as
I did before we had our little arrays deep dive. So you're first going to create a new
array of cards that contain the first card and the second card. And then in the render
game, you are going to change line 18 so that it refers to the cards array when rendering
them out. So not referring to first card and second card this way, but doing it via our
freshly created cards array. So go ahead and do this right now. Okay, let's do this together.
First, we'll do let carts equals opening closed square brackets, and then we'll set the first
card as the first item in the array and the second card as the second item. And as you
hopefully remember, we can now refer to these values by doing cards, zero, cards, one like
that. We'll run the code kickstart game, and yes, indeed it works. Great job. Let's move
on. Now that we have the first card and the second card in the cards array, you'll have
to of course, add the new card to the cards array. So quick little challenge. After this
card has been created, and it has been added to the sum, we also need to push the card
to the cards array. So go ahead and do this right now. Alright, the way to do this is
by writing cards, dot, push, open, close parentheses, and then pass in the newly created card, like
that. And in order to verify that this actually works, we can on the next line console, log
out the cards array like that, let's run this again, start game, hit new card. And there
we can see in the console. Now the cards array has been logged out with all the three cards,
10, four, and six. So we still aren't rendering out the third card though. And to achieve
that, you have to learn how to count in JavaScript, or Strictly speaking, you have to learn how
to write for loops. So over the next few casts, we are going to take a deep dive into four
loops, and then later return back to the blackjack game so that we can fix it up. Let's move
on. Okay, so now you're going to learn how to count with JavaScript. That might sound
really silly. I mean, counting is so easy if you ask a human to count. For example,
if you say pair count to 10, I would go Yeah, sure. 1-234-567-8910. However, JavaScript
is like that annoying person who then replies and said, well, where exactly do you want
me to start counting? by counting to 10? Do you mean, including 10? Or should I stop before
10? And also, should I count every single number? Or do you want me to, for example,
only count the odd numbers are the even numbers or whatever. So JavaScript is really like
that annoying person that takes everything you say 100% literal. So when you ask JavaScript
to count, you have to be super specific, we need to specify where we start counting where
the finish line is, and what the step size S here, I've already written the code for
you. So let's just dissect it. We start with the for keyword. And that's because this is
a so called for loop. But don't worry about that. Let's now look at the things that are
inside of the parentheses here. Here, you can see our starting condition, let's count
equals one. So we're going to start our count at one. Then we have a semi colon. And then
we specify our finish condition where it says count is less than 11. So we want count to
always be less than 11. So maximum 10. In other words, we're never going to count over
this number. And finally, the step size is that for each counting, you're going to increment with
one. So count plus equals one. Now these three conditions together describe to JavaScript
how many times we want to run the code inside of the curly brackets and what the value of
count will be at every single iteration. So here we are going to run this code 10 times
and the variable count will change its value in every single iteration starting at one
and going up to 10. Jumping one number at a time. So we will count to them. Let's run
this code. And there you can see in the console, we get the numbers from one and up to 10.
If we now changed this here to true, what do you think will happen? Well, then we get
13579. Because we still start at one, we're going to end before 11. So maximum 10. And
we're going to jump with two. So in the first iteration, count equals to one. It's what
we said we wanted to start with. But then in the second iteration, we've told JavaScript
that we want to increase by two every single time. So then it's three, and then it's five,
and then it's seven, and then it's nine. And then at the last iteration, it's like, okay,
now I'm going to be 11. But that doesn't work. that violates our finish condition here. So
JavaScript stops the loop before that happens, and then continues on with whatever it has
to do underneath the loop. So let's take this back to one. Can you modify this one, so that
it count from one to 20? How would you do that? Hopefully, you identified that what
you want to change is the finish condition and set that to less than 21. We run this
because he in the console that we're logging out one to 20. Now, how would we change this,
if we want to count from 10 to 20, go ahead and try that right now. Okay, hopefully, you figured out that it is
the starting condition you want to modify, you're going to write 10 here. So that starts
at 10 ends before 21 counts one at a time we run the code is he we get from 10 to 20,
logged out to the console. So hopefully, you've gained a little bit of intuition on this.
Now, let's move on to the next cast. Okay, let's first walk through how to create a loop
from scratch. And then I want you to create your own loop or at least try according to
the specifications here on line three, and four. But to begin with, we'll create a loop
loop count from zero to five. So to do that will be for opening close parentheses, and
then inside of the parentheses, we have to define our starting point, our finish line
and how big our steps will be. This is done through a counter variable. So we could do
let count equals zero and then semicolon to end the starting statement. Because zero is
where we want to start with or worse count is a very semantically good word for this
variable. A common convention in JavaScript is to use the letter I instead, I could have
named it whatever we want. And you can use count if you think that's easier, but I'm
gonna use it from now on. Then there's the finish line, which we also need to define,
we want to count to five, so I should be less than six, and then semi colon again. So this
finds that I should always be less than six. And obviously then the last point where it
will stop when counting upwards is five. And then finally, we have to define how big our
steps should be. Now I'm going to do i plus equals one. Here, we don't have to use a semicolon
to end because this is the last condition. Actually, I can space it out a little bit,
we follow the same structure for all of our conditions. And then the opening close square
brackets for the body of our for loop. Then inside of here, we'll do console dot log.
Hi from the code, omega t 012345. Good. Okay, now that you've seen this, I want you to try
to create a for loop that count from 10, up to 100 in steps of 10. So it should count
10 2030 4050 and so on, including 100. And I want you to use console log, as I am doing
here to log out the count at each step of the iteration. So go ahead and do this right now. Okay, hopefully that went well. If not, no
worries, let's do this together. Blue for let in here. You might wonder if while we've
already used the I variable, can we reuse it down here? And the answer is yes. AI is
only defined inside of the curly brackets of the for loop when you do it like this.
So outside of it. For example, down here at line eight. JavaScript won't remember this
I variable. So whatever you've configured it to mean up here inside of the curly brackets.
doesn't affect whatever you set it We're down here. So we can do let i n equals 10. That's
where we want to start, I should be this time less than not 100, because then we'll stop
at 99 needs to be less than 101. Finally, I should not be plus equals one, oh should
be plus equals 10. Because at each step in iteration, you want to increase I with 10.
console log, I am going to comment this one out, run the code. And there we see 10 2030
4050, and so on all the way up to 100. So great job. Okay, now you're going to experience
how powerful for loops are when combining them with a race, because let's say that we
are building a china application like the one that LinkedIn has, which I showed you
earlier. And these messages might just well be items in a race, let's just pretend that
each of these messages are exactly that. And ignore all the metadata around the messages,
like the time and the profile, picture, and name and stuff like that. And just pretend
that we have the data structure, which contains a bunch of messages inside of an array. Basically,
just what we have here, the exact same array we've worked with earlier as well. Now pretend
that this is a console based array, so everything basically need to do is log out of these messages
to the console. But in order to do that, we can't just console log out messages, because
then we'll just get a long array. And that's not what we want, we want each of the messages
on its own line, and not with the square bracket and stuff like that around. So the hard way
to do this is by doing like this. It's one messages, two messages, we like to take the
index from zero to three and log all of them out. There we go. Now we have what looks like
a chart in the console. But this is a really bad way of doing it, we are repeating ourselves
again and again. And that's a general anti pattern, there's something called dry for,
don't repeat yourself, don't write more code than you need to, especially not if you're
just repeating the same code. And also, this doesn't scale because ads now at the end of
the array, and run the code, I'm not logging out the last one, I have to manually update
my code. So what we instead want to do is combine this array with a for loop. Now let's
comment out this. And write for let i equals zero semicolon. And then we want to buy to
stop before it reaches five. Anyone I to increment by one, every single iteration. Now inside
of this for loop, we log the value I see in the console that we get from zero to four.
And that actually resembles quite a lot. What we did the hair, however, we've even added
the index of the latest item as well. So how about we instead of just logging out, I simply
do miss suggests open square brackets, close square brackets, use the eye as the index,
and then run the code. And boom, there we go. We have all of the items logged out in
order one after another brilliant. However, there's still a little problem here that if
I add yet another message here, maybe an emoji and I run the code, the emoji isn't logged
to the console. browser, change this to six again. So it's still not fully like dynamic.
However, I have a trick, because how can I get a hold of the number six in a dynamic
way? Well, you might remember that race has a property called length. And that will refer
to the actual length of the array. If we use that we can be sure that our loop counts up
to the final index all the way up to the end of the array. If we now run the code, yes,
there we have all of our messages, regardless of how long the messages array is. So this
was a lot of typing from my end, though. So let's move on to a challenge so that you get
to practice this as well. Okay, so now let's return back to the example
of having cards in an array like we have in our blackjack game. So here I've created an
array that has three cards of the value seven, three, and nine. And I want you to create
a for loop that logs out all of these cards to the console, however, not by hard coding,
where the loop should stop counting, but using the cards dot length property. So go ahead
and do this right now. And then I will of course show you the solution as well afterwards.
Okay, oh This went well, let's do it before open close parentheses, and then let i equals
zero, because we're going to start at zero. And next, I should be less than carts dot.
And I should be increased with one at every except in that region. Oh, here for this last
condition, I actually want to show you another trick, because what you can do here is actually
do i plus plus, that'll do the exact same thing as this, it's just syntactical sugar
and the JavaScript provides us with to make our code a little bit neater. So I plus plus
increments I with one. So now we can do console log cards, and then passing in the I run the
code. And there we can see seven, three, and nine printed to the console. Great job. Okay, this is so cool, because now you're
going to combine what you've learned about arrays, and for loops with what you know about
manipulating the DOM. So we're going to pull the strings together and have you render out
this sentence inside of this greeting L. So you can see we have in our HTML, just an empty
paragraph, which has the ID of greeting L, we have fetched that element from the HTML
and stored it in this greeting l variable. And your job is to render the sentence that
is the array here. So you're to render all of these items inside of the array in the
greeting paragraph. And the way to do that is to use a for loop to loop through it and
render each of them into the greeting l using dot text content. So a lot of stuff you have
to keep track of here, but give it your best shot. And then I of course will show you the
solution when you return back to the screencast. Okay, hopefully that was well. Now let's do
this before, let i equals zero, because we want to start at the zeroeth index in our
array, we'll do is less than sentence dot length. And then we do i plus plus, because
we want to increment one time. Here, we need to grab a hold of the greeting L and then
do text confidence. And here, you might have been tempted to do equal and open and close
square brackets and passing in the index, that will just end up with rendering pair
because first it renders Hello. And then it clears out all the text content and renders
the second word, but then for every single time in this loop, it clears out all the text
content, we end up with just the result after the last iteration. And that was the last
word in the array. So what we have to do, we have to keep the previous content intact
inside of the paragraph. And as you might remember, we do that with plus equals. So
running the code again. Yes, now it works. Now though, I have a bonus challenge for you,
which is the following. How do you keep the spaces between the words if I remove these
spaces from the array? That is if I do like this, like this, like this and like this,
and we render it out? Because we have no more spaces? It looks like one long, weird word.
How can we on this line seven, modify it so that we get spaces between the words, go ahead
and try that. Okay, what we will do is we'll simply, at the end here, add a plus, and concatenate
our given item in the array with a space. So now we add a space after each of the words.
If we're under this, you can see yes, we get now the sentence exactly how we want it. Great
job. Let's move on. Okay, back at our blackjack game, it's time for you to create a for loop
that renders out all the cards in the cards array instead of just the two first ones,
which we are doing up here. So you are going to start your for loop down here at line 19.
I'm going to help you out a little bit because we are going to keep this first setting of
the text contents here. So we have the default text inside of the paragraph. And then you
are going to render out the cards. After this text inside of the paragraph. Go ahead and
create that for loop so that our blackjack game supports any number of cards inside of
the cards array and will render all of them out regardless of how many it is to give it
to a restaurant and returned back to me when you want to see my solution. Okay, hopefully that went well. If not, no
worries, we'll do it together. We'll start with four and then open and close parentheses.
Of course inside of the parentheses, we need to define that we want to start our increments
At zero, and we want to stop it before it reaches the length of the cards array. How
do we do that? Well by i is less than cards dot length, and then a semicolon. And we want
to increment i, at every iteration, the body of the for loop with curly brackets here,
we are going to plus equal on to this paragraph. So we'll do cards, l dot text content, plus
equals, let's start by just adding the cards, and then passing in the current value of i
our iterator, which will start at zero and to begin with, and before 201, and then run
the code start game. And yes, it works. However, it looks like it says 104 here, because we
haven't added a space between our numbers. So the way to do that is simply by concatenating.
A space after been card. Now if we run it, start game, yes, we've got it. And if we hit
new card, now we can see both the sum and the cards are now correct, according to the
state of our game. Great job. Let's move on. Okay, so our blackjack game is actually turning
out pretty good now, start the game and hit a new card 20, I can even hit yet another
card, boom, I'm out of the game, it's it's almost fun to play, though, you'll get pretty
tired of it's as you played multiple times, since you every single time get the exact
same cards. So not exactly an exciting blackjack game. And of course, that is because we have
hard coded the variables for our first card and second card here and also hard coded the
value for our third and fourth and every proceeding card here on line 40 will always get 10 4666666,
and so forth. So what we need to do is instead create a function, get random card that returns
a random number. So that we instead of hard coding the number 10 up here on line one,
we can do get random card and call that function. This function will then return a random card
that the first card variable will be set to. And we can do the same with the second card.
And also down here in the new card function, we can do get random card there as well. This
way we'd get a functional backtracking. However, there's a few thing you haven't learned yet,
which you need to learn in order to create this get random card function. So let's rewind
a little bit here. Get back to the hard coded numbers. And over the next few casts, you're
going to learn how to return values in functions, and also how to generate random numbers inside
of a function. Let's go ahead and do exactly that. Okay, let's return back to our racing
game example in order to learn about returning values and functions. So here we have two
players who've raced through the game and player one got the time 102 and player two
got the time 107. And our job is to create a function that returns the fastest race time.
So in order to do that, we first have to do a function, I'm gonna call this get fastest
base time, quite a long word, but at least it's the script. And inside of the body of
the function, we have to first check which of these times were fastest. So we'll do an
if statement and say, if player one time is less than player two time, well, then we are
going to return player one time. Because if it's less than player two, then it's the fastest
race time and we are going to return it. Now this return keyword here might now seem a
bit weird. And you probably don't understand yet what it means. But don't worry about that
right now. It'll be clear as we move on. And then we're going to do else if the next condition
is if we are to was faster than player one is your time is less than player one time.
So we are going to return player to time like that. Then an else f actually these two are
equal. So none of these expressions evaluate to true. Well, then the fastest time as any
players time because they have the exact same time could either return player one time or
player two time it doesn't matter. I'm just going to return player one time. Okay. Now
what we can do is we can do let us race I'm going to call this variable x. And now I'm
going to define that declare that variable as the result of invoking this function. So
I'm gonna do get asked disgrace time like that. Now, the value of fast race time will
be whatever this function has returned. And if we console log So it's race time, we can
see, we get 102. That's correct, because this function compared player one and player two,
and rightfully recognize that player one was faster than player two, and thus returned
player one time. What you might think now is, well, we're just console logging out the
value here. What's the point? Why couldn't we just, instead of these returns, let's do
console dot log, to do that directly inside of the function, do that first and run it
and see, yes, we are now indeed, running this line six. Here, we're console, logging out
the value. Briefly down here, try to see what is the
value of fastest race at this point, and run the code, you can see that we're getting
102. First from this line, then we're getting undefined from line 16. Because now, the fastest
race variable simply isn't defined because this function didn't return anything. And
it's actually quite valuable to have stored the fastest race time inside of this value,
as opposed to just having console log that out appear. Because now we can use this variable
for something else. So let's like this, and return instead, move over and remove the parentheses
as well. We're wondering how I got the cursor to be on multiple lines at the same time,
it's a trick where you first select a word, and then do Command D. Or if you're not on
a Mac, Ctrl C plus D, like the word Command D, one three times and now I have selected
all of the return e works so that I can delete them or retype them. That was just a quick
little tip. Now it's time for a challenge. So you are going to write a function that
returns the total race time, then you are going to call or invoke the function and then
store the return value in a new variable, you have to decide for yourself what you're
going to call that variable. And what you're going to call this function. Then finally,
you are going to log your variable out just to check that everything has worked. So go
ahead and do this right now. Okay, hopefully this went well, let's do this. Okay, function
get portal race, five. And the way to do that is simply to return layer one time plus layer
two time, then we can create a new variable called Lex. total time equals get total race
time. Now we can console log total time, thing like that, running the code. And indeed, we
get 209 in the console, which sounds just about right. So great job, let's move on.
Okay, it's time to take what you've learned about returning values and functions, and
implement that technique into our app. This is a three part challenge. First, you're going
to create a function get random card, that always returns the number five. And then you're
going to use get random card to set the values of the first card and the second card, and
then use it to set the value of the card variable down here in the new card function as well.
So you are going to write your function, get random card here, starting on line 14. And
now you might think, Well, that doesn't make sense. Because we have previously learned
that if you define a variable down here on line 14, we can't use it up on line two, and
three, that's at least how it is with variables you define using the let keyword. That is
exactly right. But when you create functions in the way we do, there's an exception. So
I want you to just try this and see if it works. And then I'm going to explain afterwards,
why it works. Go ahead and give this your best shot, and then I will show you the solution
as well afterwards. Okay, hopefully that went well. Now let's
do this, we'll do function get random part like that. Then inside of the body of the
function will simply return five, we need to use this pair app line to get random card
and on line three, get random card. What's happening here is we're calling this function
it will return five and thus second card and first card will be initialized with the value
five, as will our part down here. If we do get random card and call it these two really
important, otherwise it won't work but with them card will now have the value five. So
let's run our blackjack game. Stop the game. Oh, we got two fives. Nah, yet another five.
What's the chance? Obviously it is 100% at the moment, but that doesn't matter. Because
we now have the setup for inside of this function, writing the logic for getting an actual random
card back. So that's great. Finally, I promised to talk a little bit about the fact that we're
creating the function down here on line 14, and then using it on line two, that seems
to go against what we learned about variables early on. However, when you write functions
like this, which is called function declarations, the function gets so called hoisted to the
top, meaning that it's accessible even at line one, regardless of how far down you define
the function, we could have written this function on line 10,000, it would still be accessible
online one. Now there are other ways of creating functions don't give the function this extra
benefit. But as for now, we're only going to write functions in this way. So don't worry
about that. Because now you have another thing to worry about. And that is, how do we actually
modify this get random function so that it actually returns a random card? So from the
next lesson on, we are going to dive into exactly how to do that. I'll see you there. So I remember when I was learning this slightly
clunky way of generating random numbers in JavaScript and thinking, Well, why do I really
need to generate random numbers is that really such a common thing to do for developers?
Actually, it is, of course, there's our use case where we're building a card game, obviously,
we need to have some kind of randomness in which card you get. Otherwise it would be
meaningless. But also imagine all games that use dices a dice is basically a physical randomness
function with gives you a random number between one and six. But randomness is only important
in these kind of casino ish games, I would say all computer games randomness plays some
kind of role. For example, in this popular iPhone game crossy road where you are to cross
a road as a duck without getting hit by a car. Surely, there's some randomness underneath
here, which decides which cars appear on the road and when they appear, but it doesn't
stop there with games. Actually, cybersecurity random numbers is a key component in order
to authenticate yourself and generate keys as with in cryptocurrencies. So for example,
Bitcoin uses random numbers as well. The random numbers plays a role in the crypto economy
as well. And most importantly, we use random numbers in order to generate the suggested
tweet text in our JavaScript Miss advent calendar. So you can understand random numbers are everywhere.
And you need to learn the most basic way of generating that in JavaScript. And that is
through something that we call the math object. That's something that's already provided to
you in JavaScript or by the browser to be specific. And you can type math wherever you
want, with a capital M, and then do dot random, and then open close parentheses so that you
call this function or method. And don't worry, if you don't quite understand what's going
on under the hood here, you're not meant to do that right now. All you're meant to know
is that that will return a number to you, which is now stored in a variable called random
number. And then I'm logging out this random number. What I want you to do now is pause
this screencast and run this code a few times, so that you get to see a few of the values
that our random number variables can take. And then try to ask, succinctly and specifically
as possible, write your answer at what you think math dot random Deus, what does it return,
try to formulate that and write it down, then return back to the screencast when you think
you have the answer. So the way I would write this is that it generates
a random number between zero and one, and the parentheses, not inclusive of one. So
we generate a random number, including zero, and one, but not including one. So from 0.00000
to 0.99999999, kind of bunch of nines after that. So if we were to visualize this slightly,
say that math dot random, gives you a number from 0.000. And the bunch of zeros after that
I just didn't couldn't bother writing all of them to 0.99999999, basically a bunch of
nines as well. That is the range you are given when you give JavaScript this command. So
if we run this, you can see we get 0.68 and a bunch of numbers 0.95 and a bunch of numbers
0.88 0.001. Yeah, as you can see, we've already been almost very close to zero to very close
to one. Now, before we go, there's one thing I need to point out, which is that the randomness
here while it looks completely random for us humans, it's not truly random. There is
some deterministic variables going on under the hood here and it's actually a Really hard
problem and computer science to generate truly random numbers. But for our use cases, we're
not going to worry about that. As far as we hear these numbers regenerate with math look
random, or more than random enough for our use case, this is not a PhD in cybersecurity,
but but rather getting you started with web development. So with that, let's move on.
Okay, so now we know how to create a random number between zero and up to but not including
one. However, it's not entirely clear how we utilize math dot random in order to create
something useful, like, for example, a dice function. So let's take this one step at a
time towards creating such a function. And the first step we're going to take is simply
by multiplying math at random with six. Now I want you to do the same thing that you did
previously, which is to pause the screencast, run this code a few times and see what we
log to the console, and then answer the following question. Which range will a random number
be now? So from which number to which other number? It used to be from zero to 0.99999?
Now, it's something else, and you have to figure that out. So go ahead and do that right
now. Okay, the answer is that it still starts at zero. Now goes all the way up to 5.99999.
And a bunch of nines, I'm not going to type all of them. So if math dot random gave us
a number from zero to 0.999, Math dot random times six will give us a number from zero,
because zero times six is still zero to 5.999. Because zero or in a bunch of nines times
six is not entirely six, but it's almost six. So it's five point a bunch of nines. So now
we have kind of expanded our range, roughly speaking from being between zero and one to
being between zero and six. We did that by multiplying it to the six. Let's move on to
the next step. Okay, so now we need to learn another method on the math object. And that
is math dot floor. Florida's s, a takes some input a number and then does something with
that number. Return set filters, you can store that in a new variable, for example, like
Florida number right here, that is the Florida version of this number. So I want you to pause
the screencast, run this code a few times and answer the question, What does math floor
do to positive numbers? And the reason I'm saying positive numbers is I don't want you
to add negative numbers in here, because the mental model is slightly easier if you only
think about positive numbers. And it's a bit easier to write a concise answer to it and
my opinion. And finally, I've never used math floor on negative numbers anyway, it's usually
used on positive numbers. So try this, feel free to add a few different numbers in here
and run the code. And once you're ready, just type out your personal explanation. What do
you think math floor does go ahead and do this right now. Now, the way I think of math
floor is that it simply removes the decimals. If we run this, it returns three, we have
12.40, even 12.9999999. Still 12. Okay, so great job with that knowledge in mind. Let's move on to the next lesson. Okay, so
just as a quick recap, math dot random gave us a number between zero and almost one. And
math random times six, then gave us a number between zero and almost six. And now we are
going to combine this with a math dot floor, which you learned in the previous lesson.
I'm going to add it here. I'm going to write math dot floor and then wrap our entire previous
expression inside the parentheses of math floor. Now, what I want you to do is run this
code a few times, and then write down possible values. Random number now can hold. So there's
a limited number of them and your job is to figure out exactly which wants to go ahead
and do this right now. Okay, hopefully that went well. Now let's run this
together. See, we got 44014025 Hmm. Okay, so it seems we are getting the numbers between
zero and five. That actually makes a lot of sense because if we take this range here between
zero and almost six and shove it into the math dot floor function, then it will basically
remove All of the decimals and if we remove the decimals from this entire range, which
numbers are we then left with? It's just the whole numbers from zero all the way up to
five. So the right answer was 012345. Like that, okay, hopefully, you're still hanging
on, let's move on to the final step of our dice function. Okay, now we are going to complete
our dice feature, because we know that with this expression, currently get a whole number
from zero to five. So the question then remains, how do we turn this range into rather a range
between one and six, which is essentially the same as a dice, and I want you to try
this for yourself. Try to modify the expression so that we get a range from one to six instead
of zero to five. Go ahead and give that a shot right now. Okay, hopefully that went?
Well. To understand what we need to do, we can compare each of the numbers here can see
that first number here is one and the first number there is zero. And how do we go from
zero to one, we add one. And the same goes for all of the numbers here of how to go from
one to two, well, we add one, and from five to six, we add one. So basically, what we
can do is just two plus one at the very end. And then if we run the code, you see we get
to we get 6356 to one, yes, we indeed get the entire range of a dice. So really good
job reaching this far. Now I only have one last challenge for you. Let's create a function
called roll dice that returns a random number between one and six. So basically, you're
going to take what we've done here, and wrap it into a function and then return the results.
Go ahead and do that. Okay, to do this, I'll do function, roll dice, open and close parentheses,
open and close brackets. And inside of here, I'm just going to copy this line straight
in, and then return a random number like that. Now after you remove it from a pair, because
up here on line two random number isn't even defined, so we can't log it out. Random number
is now only defined inside of the role bytes function and the value of it gets returned.
So if we console log, and inside of the parentheses, we call the roll dice function like that.
Get, yes, a random number between one and six. Really good job reaching this far, this
was complicated stuff. So if you feel a little bit shaky with this, that's totally okay.
You can go back and rewatch it and retry all of the challenges if you want to. And then
when you feel ready, we'll move on and use this knowledge to make our blackjack game
much better. Okay, we're back at our blackjack game. And we are going to fix up this get
random card function, but we'll do it step by step. So to begin with, I want you to make
it return a random number between one and 13. So here, you can pretend that we are working
with the regular values that a deck of cards usually has. So with the ACE being the one,
the numbers from two to 10, of course being their respective numbers, then the jack being
11, Queen being 12, and King being 13. So from one to therapy like this, go ahead and
give this your best shot. And then of course, I will show you how to do it afterwards as well.
Okay, now let's do this. We know that if we do math dot random, we are going to generate
a number between 0.000 and a bunch of decimals after that, until 0.999, and a bunch of lines after that
as well. So the first thing we need to do in order to get this range to look more like
this one is to multiply this entire thing with 13 0.000 times 13 is still 0.000 is still
zero. And 0.999 times 13 is actually just 12.999. Or we have a bunch of nines after
that as well. So we're getting to something remotely similar. It's just a matter of how
many nines we have after the dots. But this is roughly the range we're working with with
this expression right here. So we want to remove the decimals. And how do we do that?
Well, if you remember from Previously, we can use the math dot floor function to wrap
the entire thing inside of the parentheses of math dot floor. Now we take this expression
here, this one and we n floor it which gives you like that and like that. So, zero to 12.
That's what we're returning here. The question remains, how do we go from zero to 12? One
to 13? Well, that's only a matter of adding a one to any given number. Let's do like that.
That should return a number between one and 13. Let's try to start this game and pull
a bunch of cards to see if we actually get the entire range. Seven for looking good so
far. 10. Okay, 13. Yes, file a bunch of other numbers. getting way too many numbers here.
Let's get that one. Yes, there we got it, a one. So we have the entire range from 13
to one. And then just about everything in between. This was not a normal blackjack round,
but at least prove the point that this generates a random number between one and 13. So great
job reaching this far. But of course, we have to modify it because in blackjack, we're not
following the usual value sequence for cards, so we need to modify our function a little
bit, but we'll do that in the next test. Now, we need to change our get random card function,
because in blackjack, the jack, queen and king are all worth 10, and the ACE is worth
11. Or, strictly speaking, the ACE can be worth both one and 11, you get to choose as
a player, what suits you best is the value you use. However, for the sake of simplicity,
we are just going to treat the ACE as 11. In our case, as having a dual value for this
card would add a lot of complexity to our game. And it's not something I want to focus
on. It's rather something you can, for example, do as a stretch goal later if you want to
modify the game at the end of this course. So for now, we're going to treat our ace as
11. So this means we need to modify our get random card function. If the number it returns
is one, then we should change it to 11. And likewise, if the number of returns is either
1112, or 13, we should rather return 10. To go ahead and modify this function so that
these exceptions are followed, you're going to have to define a variable
that this random number is stored in and also has some kind of conditional that checks for
these conditions, and returns the appropriate value. So go ahead and give this a shot. And
then I will of course show you the solution afterwards as well. Okay, hopefully that went well. If not, no
worries, we'll do it together. First, I'm going to instead of returning this directly,
turn it into our random number dropped, then we need to write our conditional to account
for these special cases, I'm going to start from the very top and check if a random number
is more than 10, meaning that card is either the jack queen or the king. So if a random
number is more than 10, what are we going to return then well, then we are going to
return 10 because that is the value of the jack, queen and king, I'm going to do elsif.
And now I'm going to count for the ACE itself. And for that I'm going to use the triple equals
random number, triple equals one. And I'm going to return 11 then In all other cases,
I can just do else like that no other cases, it must mean that we have drawn in row 23456789
or 10. If so, we're just going to return that value. So then we're just going to return
the random number directly like that, let's run the code. Start game. Okay, five, five,
I'm gonna hit the bunch of cards to see that we get the entire range. And indeed, it seems
that we have a two here we have an 11 here and have almost every single word in between.
I'm 100% sure that if we continue hitting the new card in the long run, we'll just get
random numbers across our entire defined range. So great job, we're almost reaching the end
of our blackjack game, you should really be proud of yourself for reaching this far, this
is starting to get advanced. But there's even more to learn. So let's just keep up the pace
and move on. Okay, there's one really weird thing with our blackjack game. And that's
easily exposed. If we console log out to the cards here at line 12. And then refresh the
page there we can see I got two and seven. And the reason that's weird is because I haven't
even clicked the start game button, I kind of just entered the casino and the casino
was already decided what cards I am to be dealt. That's fishy, we don't want that I
want the cards to be generated as I click on the Start game button. So the first card
and the second card should be generated inside of the start game function. And thus the cards
and the sum also needs to be reassigned inside of the start game function. And also the is
alive shouldn't be set to true by default. before I've even click the Start game button.
I'm not alive. I'm not even playing the game. I'm going to use that as an example. Set it
to false first, then inside of the start game function. I'm going to do is alive equals
true. So now we have the correct starting state before I've entered the game appear
in line six, and the correct value once I've started the game down on line 26. So what
I want you to do is make it so that the same thing happens with cards rate because it should
not be set here. And the first and second card shouldn't even be defined up here and
the sum should be zero by default. This is how the state of the game is before I've started
playing the game. Now, what you need to do down here at line 23, and 24 is generate two
random numbers, then reassign the cards and the some variables so that the game can start.
So you might find this a bit tricky, but do your best, there's no shame in trying and
failing, because I will of course, also show you how to do it when you return back to this
cast. Good luck. Okay, let's do this. We'll start by defining first card and second card.
And they should be defined by running the get random card function, I don't give them
we get random card function. Second card equals no card as well. Now we can set the parts
array to first card, the second card, and the sum to first card, plus second card like
that. And also actually get this console logged back in again. and rerun the browser you can
see now it's empty. The casino hasn't decided which card slam to get very good. So it's
start game and there I got my blackjack. Oh my god. That's amazing. And with that, I have
nothing more to say. I'll see you in the next caste. The next thing I want to fix is our
new card button because it's kind of broken. Let's see why. If I now start the game, and
I get two cards, and I draw a third card and a fourth card and I'm out of the game. At
this point, I shouldn't be able to draw more cards, but actually I am I can hit it and
I got another 10. So I'm at 34 shouldn't be possible to get to that number in blackjack.
So we need to stop it when the game is over. And also we refresh the browser able to I
shouldn't be able to start with just one card either, but I actually can. So there's two conditions,
we need to check both if I'm still in the game, basically if the is alive is true. And
also I can't have blackjack either. Now this requires us to learn something called logical
operators, which lets you combine multiple conditions inside of an if statement so that
a piece of code should only be run if multiple conditions are satisfied. So let's take a
little detour and learn about logical operators in the next casts. Okay, let's learn about logical operators.
Here we have a little bit of boilerplate code, namely two variables and a function. And the
imagine scenario here is a course platform much like scramble. And what we're trying
to solve is to figure out whether or not a user should get a certificate, that is whether
or not we should call this get certificate function. Because the deal is we only want
to call this function if two conditions are true. And that is has completed course. In
other words, the user has completed 100% of the course. And secondly, gives certificate
that is whether or not this is the type of course it makes the user eligible for a certificate.
Because you can imagine that very short courses doesn't give you a certificate to the course
has to be of a certain size to reward you with a certificate. So what we need to do
is figure out how we can check if both of these conditions are true, because then and
only then do we want to call this generates certificate function, you could actually achieve
this with the concepts you've learned so far, by simply nesting if statements. For example,
you could do if has completed course, equals to true, and then add the body of the if statement.
And then inside of the body, you could nest another if statement if gives certificate
equals true potential. So you get two F's inside of each other and the inside of the
inner if you do generate certificate. Now if we run this code, you can see yes, we are
indeed generating the certificates. And if we flip one of them to false, we are not generating
the certificate because here, this condition was not fulfilled. So neither of the code
lines inside of the body was run. JavaScript just jumped over the entire if statement.
However, this is a very clunky way of doing it a better way would be to actually remove
the inner if statement. For now, let's just comment it out. And then inside of the parentheses
here, we can add another condition by writing a double ampersand. And then the next condition
gave us certificate equals true, we now move this line, this line and uncomment, this one,
run this code, we see nothing happens because this condition here is false. And with the
AND operator, both of the expressions before an after the operator need to evaluate to
true for this entire expression to evaluate to true. So if we flip this to true, and run
this, now it works. But it's much better to have it on one line. And a little extra thing
we can do is actually omit the script equals true, because now, what was this and this
evaluator? Well, it's simply true, and, and true and true equals false true. But as for
now, in order to be explicit about the condition we are checking for, actually want to keep
these cripple equals here as well. So one way to read this in plain English is, if this
is true, and this is true, then run this code. Hopefully that makes sense, because in the
next class, I'm going to give you a challenge, so that you get your hands dirty with this
as well. Okay, let's continue on with our course platform
example. So in this challenge, you are to imagine that you are writing the code that
is to be run, after the student has struggled with the challenge for a little while, or
maybe the student has clicked a button and signaled to the platform that that she is
stuck. And the first one to check has the student solve the challenge she's trying to
solve, and has the students enter, hence left, because if the student has any hints left,
she can go and open those hints. But if she's used all of our hands, and she hasn't solved
the challenge yet, then we are to run this show solution function and just show her the
solution. Obviously, it just logs out a string, but you can imagine that it will show the
solution. So your job is to create an if statement that checks that both variables are false.
I mean, these two variables, and then if so, run the show solution function, go ahead and
give this a shot. And then I will of course, show you the solution when you return back
to the screencast. Okay, the way to solve this S, almost similar to what we did in the
previous cast will be F and then open and close parentheses. And here we need to use
a logical AND operator because we're going to check if both has solved the challenge.
cripple equals false. And the double ampersand has hints left is also false. Then, if the
user hasn't solved the challenge, and has no hints left, it's time to give her some
slack and show this solution. So then will trigger show solution like that. Let's run
the code. And indeed, this triggers the code because both of them are false. If we try
to flip them to true, then the code is not triggered. We're not logging anything to the
console, meaning that our logical operator that governs our if statement actually works.
Great job. So now that you've learned the AND operator, let's take a look at it's close
relative, Li OR operator. What does that do? Well, it allows you to check if either this
condition is true, or this condition is true. And if so, the body of the if statement will
be executed. So if you're in a situation where we only need one of two cases to be valid,
well, then you want to use the OR operator. As for this example, it doesn't really make
sense. It will now run since actually both of these are true. But if the gift certificate
is false, it will also run. But that doesn't make any sense. Because if the course doesn't
give any certificates at all, you're not supposed to generate any certificates regardless of
the user having completed the course. So let's use another example. instead. Imagine here
that you're building Netflix, and you've just launched this amazing new documentary, The
fire festival. I don't know if you've seen this, but it's truly amazing about a guy who
creates a festival that aims to be the celebrity Hot Shots festival of the world that just
becomes a disaster. It's really good. After this has been launched. You probably want
to recommend it to a ton of your users. And what you want to do is you want to check if
the user likes documentaries. Or if the user like startups, they don't have to like both
but definitely like one of these themes, then most likely, they will enjoy the fire festival
documentary. So I want you now to try to use the or statement that is the two lines you
can see here, you can copy them if you want, if you don't know how to get them from your
keyboard, and you're going to use this to call recommend movie if either of the variables
this the likes documentary, or like startups are true. I'm pushing you out on thin ice
here, I haven't written a complete or statement for you, but it works in just the same way
as the and statement. So I think you can do it if you just give it a shot. And if you
don't, no worries, I will show you the solution afterwards as well. Okay, let's do this. Let
likes documentaries. set that to true. And we'll do let likes startups to bathroo false
for example. And if likes documentaries, if that is true. Or if likes startups, it's true.
Well, then we want to recommend this movie like that. running the code, we can see we
are recommending the movie, even though this one is false, flipping both of them to false.
Now, if I run the code, nothing happens, because at least one of them needs to be true, this
or this. And if we make both true and run the code,
then of course, if both are true, then one or the other is also true. So that would satisfy
the condition, great job doing this challenge. Let's keep up the pace and move on. Now, you
are going to take what you've learned about the logical AND operator and modify this new
card function, so that you only allow the player to get a new card if she is alive,
and does not have blackjack. So those are the two conditions that need to be filled
for you to actually run this code. So give this a shot. And I will of course show you
the solution afterwards as well. Okay, so the way to do this is if open and close parentheses,
and then actually just open the body of the conditional and paste in this code. And when
are we going to run this code? Well, she has to be alive, we're going to do is alive. And
then if that equals to true as the first condition. And the second condition, which we also want
to be true, since we're using this logical AND operator should be that the house black
jack should be equal to false like that. If it's alive is true, and has blackjack is false,
then the dealer should be willing to give the player a new card. So let's try this we'll
start the game 15 new card 25 you're out of the game, let's try to ask the dealer if we
can please get one more card. Nothing happens. Works brilliant, really good job doing this
challenge. Okay, so our blackjack game is almost complete, there's just a tiny little
feature I would like to add as well. Because if you've ever played online blackjack, or
poker, what you normally see as your own name, and your credits or your chips somewhere on
the screen. So what I mean by that is something along the lines of this, like that, so you
see your name and how many credits you have, or chips or whatever. And this is nice because
then it's possible to later implement the concept of winning ever increasing your trips
and of losing as you're betting or playing rounds for critical components of any blackjack
game. However, I wouldn't want to hardcoded in the HTML like this, we of course, when
I represent this data and our JavaScript, that gives us the ability to change it. Now
I'm going to just show you how we could do this to begin with, by first giving this an
idea of player dash L and removing the competence of it. Then in the JavaScript, we could do
let play your name equals pair and let player chips equals 145 for example, and then we
could grab the element, player L equals document dot get element by ID, passing in the ID we
just created. And then do the player algo text content which you know by now, your name,
colon and a space and then $1 sign and then plus the player chips like that. If we now
run this, you can see yes that we render it in the exact same way. However, now we've
come into a situation where two values that are inherently connected together, like the
player and his chips, which currently live in two different variables, what would make
more sense in this situation would be to somehow combine this into a single unity. And that
is where so called objects come into play. That is another data type, which resembles
a race a little bit. But they are also different in fundamental ways, but they are kind of
also buckets where you store data. So in our case, we would perhaps want to create a player
object in which we can store both the player's name and the chips. So I'm going to show you
how to do this, you might feel a little bit confused as you see it. But over the next
few casts, you're going to practice objects yourself. So what I'll do, right let player
equals open close curly brackets. You've seen these before, they're used often in JavaScript.
But when you see them in a context like this, after the assignment operator, they mean that
we are creating an object. And inside of here, what I essentially want to do is add this
data right here, however, you can see that something is wrong here with all these red
lines. And that's because the syntax for creating items inside of our object is different from
how we define variables. First of all, we don't use the let keyword dump of the names.
And secondly, we replace the assignment with a colon. And thirdly, just as we have in a
race, we separate the items with commerce, but we don't do that on the last item. Finally,
here, it would make sense to omit the player as we've already used that name as the name
of the entire object. So we can just rather do name and I'm not going to capitalize it
and chips like that. Now we have taken our two variables and group them together in this
little bucket which we are calling player and the way we now can refer to these Values pair. And 145 is by using the first
the object name, player. And then the given key. Nice name. This is called a key, and
its value. So name is the key and Paris the value. Also chips is a key, and 145 is a value.
So to replace player chips with the reference to the trips inside of the player object,
we will instead do player dot chips. If I run this code, and see we get the exact same
result, you're probably a little bit confused now. So don't worry, if you think this was
hard over the next few casts, you are going to practice objects for yourself, so that
this becomes a second nature to you. Let's move on. One way to think of objects is that they give
you the ability to store data in depth. And with that in mind, we'll know that objects
are so called complex data types are also called composite data types. Because we use
numbers, strings, Boolean, or even a race in order to compose objects, so they often
store quite a lot of data. And they can even store objects within objects, that kind of
nested data structure, it's not something you're going to think about now. For now,
just think of it as key value pairs. And let's look this through the lens of a real world
example. That's always easier. So here on screen Ba, we represent our courses as objects
was here, you can see the CSS Grid course, actually, the very first course we launched
back in the days, and it has a bunch of different data, for example, it has the title, the number
of lessons, and the creator of the course, the length of the course and the level of
it. So let's actually translate this course into JavaScript into how the data structure
actually looks. So good. Let course equals open and closed curly brackets start with
a title, like that title, colon, learn CSS Grid for free. Now we have one key value pair,
title is the key. And the string here is the value, then the lessons that is natural to
represent as a number. So it was 16 lessons, the creator, which again, is a string. But
then we have the length, which while it says one hour here, that's actually not how we
represent that data in our database in this in this object, break it down into minutes.
So perhaps this course is actually 63 minutes. But as for the user interface, we don't go
into detail that much, we round it to the closest hour. And finally, there's the level
and here it says intermediate. That's also one of those cases where the data in the user
interface differs slightly from the data in the database. So our levels are represented
from zero to three, where zero is complete, noobs and three are in the advanced courses.
So the intermediate course, you can see here, we type out intermediate here, if this value
is set to two, now you don't have to worry about how our design. And what we say to the
user differs from the underlying data. It's just something I wanted to give you a little
heads up about, because it's very normal in real world code bases. It looks like we're
kind of done here. But we're actually not because there's a lot more data for a course
actually the North's represented here, for example, whether or not it's free or paid,
that's a Boolean. So it's either true or false like that it's free true. And this course
isn't free. And we also have tags for courses. And that's an array because we want to have
the ability to add multiple tags to one course. So we need a complex data type here as well
as the value of this tags key. So for example, this CSS Grid course has the tags, HTML, and
CSS. So this is a very real world example of an object. Now, if we want to access any
of these values here, for example, the length we do that through something we call the dot
notation, worse dot length, like that. Console, log outfits and run the code, you can see
that we log out 63. So course dot length gives us back 63. And you've used this dot notation
quite a lot, actually, up until now, even though you probably haven't been aware of
it, you have been using objects all along, like, what are we doing here? console dot
log, what kind of data type Do you think the console is? Well, it's an object. And just
to give you one more example, if let's say we want to log out this array here, well,
then we simply do course, dot tags from the code. When we open the console, we can see
that we are logging out and a radio because this entire array is the value that we get
back when we ask for the tags. Now, one thing I want to point out before we move on that
you can replace this start with an open square bracket, and then add a closing square bracket
and then turn the key name into a string. This is called the bracket notation. If we
run the code, we get the exact same thing back now, there There are reasons for why
you sometimes want to use bracket notation. But we're not going to get into that right
now. Because in the foreseeable future, you are not going to end up in a situation where
you have to do that. So I'm just going to tell you now to use the dot notation. It's
simpler. It's shorter, less code, read less code, right? It's very understandable. It's
actually what most developers prefer to use if they get to truce. So now I've been talking
for far too long. I want you to write code. Of course, this is grim. But that's what we're
all about. So in the next cast, you are going to write your own object, I'll see you. One
thing I like to do, if I'm bored is to search for epic places to live on Airbnb, for example,
castles like this wish list I came across right here, which contains a bunch of more
or less affordable castles to rent across Europe. So for example, this really
neat looking castle right here only costs $190. I mean, that's what people pay for,
like 10 square meters in a hotel room in central London. So pretty cool that you can rent a
castle for that same price. But anyway, the point being that these listings here on Airbnb,
most likely take advantage of the object data structure in order to store all of the data
that they need to present to the user. So this can also be a great exercise for you.
So that we can build up that object muscle memory of yours, I want you to basically create
an object that represents an Airbnb Castile listing, it should contain at least one Boolean,
one string, one number, and one array can contain a bunch more if you want to, if you
want to go above and beyond forever, that's the minimum requirements. And at the end,
I want you to log out at least two of the keys using the dot notation. So go ahead and do this right now. Okay, hopefully,
that went well. Let's do this together. I'll do let hostel equals open and close brackets,
we can use the title level like Chang and my thought like that. That's for the number, I think the price it's very natural
to use price. $190. And what about the Boolean? Which components here naturally lend themselves
well to using a boolean data type under the hood? Well, I think the fact that two of these
are super hosts. And the third is not points to this being a suitable piece of data for
the boolean data type. Because you're either a super host, or you're not. So yes, super
host. This one happens to be true. And then finally, there's the array. What kind of data
here? Would it make sense to place inside of an array? Well, it could be that these kind of bullet points
here are arrays that are pulled out of the underlying data on are kind of the featured
selling points that Airbnb wants to list out. Or, actually, you can see that there's multiple
images here, if you see this carousel indicator, so the images it's very natural to have inside
of an array. And also the reviews, that's definitely a list of many items. So doesn't
matter what you choose. Or if you choose something completely different. The point is just that
I wanted you to write an array inside of an object. So I'm gonna choose images like that,
make that an array. And here we probably have URLs to the specific images, who it might
be I am ri slash aspell, one dot png, empty slash Castile, two dot png, and so on and
so on. I won't bother writing anymore. Now, let's log out to these using the dot notation,
console log caspo dot price, assault log caspo.is Super host, we'll run this. And indeed, we
print out 190 and truth to the console. Meaning we have completed the rate jobs holding this
one. Let's move on. Okay, welcome back. Now it's your time to
render out the players name and his or her chips on the page. So it's a four part challenge.
First, you're to create a paragraph with an ID of player out. Then you're to move over
to the JavaScript and create the player object here at the very top and you have to give
it two keys name and chips. Then you are to move down to where you are grabbing elements
from the DOM and then grab hold of the player l paragraph and store it in a variable called
player L. Then you are to render the player's name and chips inside of playoff. So pretty
big challenge. But you've seen me do it before and you've practice how to work with objects.
So I think you're gonna nail this one. Give it your best shot and then I will show you
how to do it as well afterwards. Okay, hopefully that went well. If not, no worries, let's
do it together. First, we'll do a paragraph here. And we'll give it the ID of player Nashville
like that. Nothing happens because It's moving over to the Java scripts we are to create
the player object. Player equals closed curly brackets are to define its name, my case pair,
use a comma to separate the items. And then ships. Let's say I have $200 in chips right
now, three, grab a hold of the player l paragraph and store it in a variable called player L.
Okay, we know how to do that. Let player L equals document dot get element by ID, passing
in the player dash L, which is what we created right here. At this point, let's console log
out player L. And indeed, we are fetching it from the DOM. Finally, we are to render
the players name and tips inside of player L. We know how to do that as well. Player
l dot text content equals, and here we have to concatenate the string and dig into the
object to find the correct values. So we'll start with the player dot name is Frank, I
have a colon and a space, and then the dollar sign in front of the tips. And then do plus
again, play your dot chips. Now, this is all set up, let's run the project. And there we
go. We have rendered great job solving this challenge. Now that you've learned about objects, I want
to tell you about a specific coding pattern that we've actually been using quite a lot
here that that we aren't going to implement from scratch ourselves in this module. But
since we still are exposed to it, I want you to understand what's going on under the hood.
And that pattern is to create functions inside of objects, something which we also call methods,
because let's say that, for example, we create another key here, we'll just say, Hello, and
then a colon, and then as the value will actually write a function like this, we won't give
it a name, it'll just be an anonymous function. And inside will console log. So that's how
the inner region. And now if we want to invoke this function, we'll do player dot say, Hello,
and then open and close parentheses. If we run the code, now, you can see Indeed, we
are logging heizung to the console. And now the reason I wanted to show this to you is
because Don't you think this syntax looks a little bit familiar, like first a variable,
and then a dot, and then a function that you're calling with the parentheses at the end. Because
actually, that's the exact same thing we're doing here, when we're saying document dot
get element by ID, and the parentheses. And here, we're also passing in a value, but it's
essentially the same thing. And also here down at math dot random, also the same thing,
math is an object, and random is a function on that object, also called a method. And
even our girlfriend console dot log is the exact same thing, object with a method. So
this is not something we are going to implement ourselves in this module. But I just wanted
you to be aware of that. So that when I speak about methods, you know that they are simply
functions that are attached to objects. So with that, let's move on. So you have built your very first JavaScript game congrats with
that this is perhaps the first of many games, you're going to build perhaps the start of
a career as a game developer, I don't know. Anyway, give yourself a pat on the back, you
have learned a ton. And actually, let's do a little recap. So we remind yourself about
all the awesome things you've learned throughout this section. One thing, which was key to
our app, and it's key to basically every web app out there is the erase, we define a card
array. And also when you reassign the array down in the start game function where you
define it with items. And then all the way down at the new card button. You also pushed
to the array, so you're starting to get some serious array skills. Also, we worked with
objects up here we created our player object. And the object, as you remember, contains
key value pairs. And it's also a data type that is used in basically every single web
app out there. The third data type you learned was Booleans. Namely the true and false for
the house blackjack and it's alive variables. we flipped them around. So we set is alive
to true down here and has backtrack set to true down here and thus creating country state
for our game. This brings us to the next important concept you learned what is the if else statements
that are wrapped the Boolean and so many other things. This is key, you cannot build apps
without these kinds of conditional statements. Both the if the else if and the else are absolutely
key in any programming language. And in order to make these if else statements would work,
we used comparison operators, that's the skies in here less than or equal to or triple equal,
they helped us define the conditions as to when we wanted to render the blocks of code
in the FL statement. Moving on, we also did logical operators, the AND operator, which
check that both this condition and this condition was true in order for us to run this code
in the block of the if statement. And something we also learned was the for loops. It was
here in the render game function where we used the for loop to loop through our cards
array and render out each of the cards, again, for loop is just one of those foundational
things in programming, because so much of programming is evolved around looping through
data and doing things based upon the data, whether that's rendering it out making calculations,
sending it off from a server to a client, or just summing it together, for example,
it doesn't matter. It's just something you'll do again and again. So I'm really happy that
you've learned it as early as Now, another useful tool you've learned is the math object.
That allowed us to create this get random card function by using math dot random, which
gives us a number between zero and one and math dot floor, which basically floors the
numbers to the nearest whole number moving downwards. And you build upon your further
knowledge of functions and learned how to use return statements in functions. Because
in this get random card, we had to return values. And that's something you didn't know
before this section, there's still more things to learn about functions. So we'll definitely
continue on with functions in the Chrome extension, we're going to build a bit later. But for
now, just be proud about the fact that you've at least come to the point where you can return
values in function, that's a big, important step. So with all of these things learned,
I completely understand if you feel that you're a little bit on shaky ground here, and that
all of these names basically just confuse you even more, I don't think you should worry
about that, I would have never remembered the difference between comparison operators
and logical operators. When I learned JavaScript, what they are called, doesn't really matter.
The important thing is that you know how to compare two variables, for example, or that
you know how to create a true or false variable, whether that you call them Boolean or true,
false isn't something you should be too worried about right now. So even though this might
look scary, try to not let it scare you just focus on coding as much as you can. Because
over time, these concepts will mature in your mind and become second nature. And actually,
on that note, you are going to get some practice right away. Because before we jump on to the
final project and the Chrome extension, I'm going to throw a few challenges on you, just
so that we're sure that you really understand these concepts, and that you build out that
ever so important muscle memory. So let's go ahead and do that right now. Okay, in this challenge,
you're going to practice objects and functions. So first, you are going to create a person
object that contains three keys, name, age, and country. And the values of those keys
should be set by using yourself as an example. So your name, your age and your country. And
then you're to create a function called log data that uses this person object, it just
grabs it from the global scope to then create a string in the following format pair is 35
years old lives in Norway, obviously, Pear 35, Norway, are pulled from the person object
directly. Whereas the rest as a string that is hard coded inside of the function. Finally,
call log data in order to verify that it works. So go ahead and do this right now. And then
I will show you the solution as well when you return back. Okay, let's do this. We'll do let person equals
open and closed curly brackets. Name, should we pair age 35 and nor right like that, and
then the function log data like that. Here, we will console that log. This string and
you can see the first value is actually pulled directly from person dot name. So we'll do
person dot name, plus, and then S, then plus person dot age. That's less again, years old,
and latest n plus person dot. Like that. Now the final step is to call the function log
beta. run the code. And yes, we can see here is 35 years old and lives in Norway. Great
job. Okay, now you are going to practice conditional statements. So that is the if elsif and Elsa
statements. And the problem you're going to solve is a very common one for train companies
or a bus service, which is that the price of the ticket is based upon the passengers
age. For example, if the passenger is less than six years old, there's a free pass six
to 17 gives a child discount 18 to 26 gives a student discount 27 and up to 66. That's
the age range that pays the full price. And the people over 66 get get the senior citizen
discount. So your job is then to create a conditional statement that accounts for all
of these scenarios. And based upon the age variable up here logs out which discount the
passenger will get. So go ahead and give this a shot and return back to me when you want
to see my solution. Okay, let's do this. I'll start with the F.
And if age is less than six, while then console log free. Else if the next condition is that
age is less than 18. Because novolin practice mean from six to 17. here because it less
than 18. Yeah, that's 17 and below, wherever we've already accounted for up until five.
So the code here will be triggered from six to 17 console dot log. Oh, discount. Okay,
next one elsif. Here we'll do age is less than 27. tall, large student discount, because
this one kind of starts at 18, since this one stopped right before 18. And it should
be up until including 26. That is in other words less than 27. Then we have the full
price orders for people now left in the group who are less than 67. Or in other words, 266
console log full price. And finally, then we have the else we don't need to specify
an IF because In all other cases, the passenger should get the senior citizen discounts like
that. Let's run the code at 15. Yes, we're getting the child discount correct. At 55.
We're getting the full price very good 75, we are getting the senior citizen discount.
So it seems to be working for at least these three things scenarios. And I hope it works
for the rest. So let's move on. Okay, it's time to practice your for loop skills and
your geography skills. Because I've created this large countries array here, which contains
the five largest countries in the world by population size. So it's China, India, USA,
Indonesia and Pakistan. And what you're to do is to use a for loop to log out the following
to the world. First a sentence the five largest countries in the world, and then each of the
countries on a new line with a dash and a space in front of the country name. So you
are to use a for loop and loop through this array here, you can simply hard code out all
of the console logs that wouldn't serve any purpose. So try to remember how to use a for
loop. If you can't remember it, you can look back at previous casts, as we certainly have
gone through it. Or of course, I will also show you the solution afterwards as well.
Okay, let's do this. I'll start with the for loop, because that's the meat of this challenge.
For let i equals zero, we'll start at zero because as you remember, arrays are zero indexed,
and we want to use the index in order to fetch out each of the items. So starting there and
stopping before I reaches large countries dot length, length of list is five. So before
it reaches five, that is four and indeed Pakistan is the fourth index. So that should be right.
And we want to increment upwards. Like that. Here, we'll do console log, and in first the
batch and the space like that concatenating this with large countries, passing in in the
square brackets, the greater variable i and now let's run this code and bring up the console
and indeed, it looks to be working. Now we only need to console log out the five largest
countries in the world Like this, running the code, and yes, it works. Great job. Okay, now I need your help because I have
messed up our large countries array. As you can see, in first place, I have Tuvalu and
in fifth place I have Monaco. However, neither of those countries are large enough to deserve
a spot in this large countries array. Actually, Tuvalu is a tiny island state far out in the
Pacific Ocean with just over 10,000 inhabitants. And Monaco is a tiny state in Europe, that's
smaller than Central Park in New York. So surely, it does not belong in this array.
The first and fifth place belongs to China and Pakistan. So I need you to help me fix
up this large country's rate so that China and Pakistan are added back into their respective
places. And to solve this, you are going to use the fort following tools, first push and
pop, which you've learned earlier in this course. And then their counterparts on shift
and shift, which I haven't taught you about. But that is intentional, because I want you
to Google how to use on shift and shift. And what I will disclose to you is that they are
kind of a mirror image of push and pop, because whereas push and pop will work with the end
of the array on shift and shift works with the beginning of the array. So pop will remove
an item at the end, like this was push will push an item into the end like that. And likewise,
shift will remove an item from the beginning of the array like this, and on shift will
shove an item into the array at the start like that. So with that short explanation,
and Google, you should be able to, I want you to try to solve this challenge. And of
course, I will show you the solution when you return back to the screencast. Good luck. Okay, hopefully that went well. Let's do this.
I'll start at the end. So I want to replace Monaco with Pakistan, then I'll do large countries.com
in order to pop away Monaco, and then large countries push asking in Pakistan. Let's now
console log large countries to see if this works. running the code, and yes, there we
go. Now, to remove this first item here to follow, I'm going to have to use shift. And
here I completely understand if you're confused as to why shift is the name shift. And ns
shift is named on shift. It's about the two most intuitive method names in JavaScript
in my opinion. And one way to think of this is that on shift is a longer word than shift.
So on shift makes the array longer. Let's just us push is a longer word than pop. So
push makes the array longer. Anyway, let's just do this large countries dot shift. Let's
see if we've removed two volumes by running the code now. Yes, Tuvalu is gone. That means
I need to do large countries.on shift and pass in China like that. running the code.
Yes, we have fixed up the large countries array. Great job. Now it's time for a scary
challenge because you are going to check every Friday the 13th. And if so you're going to
log out this spooky face because as you might know, Friday the 13th is kind of a scary date
if you've seen the Friday the 13th horror movies. So you have two variables date of
month, which is meant to be from either one to 31 depending on which day of the month
it is and then a weekday variable which is meant to be Friday or Tuesday or Wednesday
or any of the days in the week. And if it is both Friday and the 13th and only if both
of those conditions are satisfied you are to log out the spooky face. So just remind
you, you have to use the logical AND operator which we learned is symbolized with these
two ampersands. So go ahead and give this a shot right now. Okay, let's do this. We'll do if opening close
parentheses and heroes day of MONTH critical equals 13 if it's the 13th day, and if it
is the week they have triple equals Friday. Then we are going to log out the spooky emoji
like that running the code Nothing happens because it's Friday the 31st. Flipping this
around Friday the 13th. Yes, we are logging out the spooky face. And if we change this
to Tuesday, nothing works out because this time, the first condition was satisfied it
evaluated to true, but the second one was not satisfied. So it evaluated to false. And
the AND operator requires that both the first and the second evaluates to true in order
to execute the code in the body of the if statement. So, great job. Okay, now you're
going to practice returning random numbers. And the problem you're to solve is the rock
paper scissor game, if you try that, it's a game where two people truce with their hands,
either a rock paper or a scissor. And the way it works is that the rock will beat the
scissor, but the paper will wrap itself around the rock so that the rock loses. And if the
matches between the scissor and the paper, the scissor will cut the paper into pieces.
So if those rules were a bit confusing, don't worry about it. That's not the point here,
your only job is actually to create a function that returns one of the random items in this
array when it's called. So you need to work with math dot random in order to achieve this,
go back and watch previous cast. If you've forgotten about that, or search for it on
Google, that's even better. And finally, when you have coded up your solution and want to
see mine, just revert back to this screencast. And I will, of course, show you how to do
it as well. Okay, let's do this. We'll call the function
get ham. And inside of it, first need to generate a random index that we're going to use in
order to fetch out Rock paper or scissors. So we'll let random next like that, equals,
first I'll just do math dot random like that. And then actually, I'm going to return a random index, and then debug along the way, just to be sure
that I understand each step I'm taking. So here, I'll console log, the result of running
the get hand function like that. So now if we run this, we're logging out 0.05, or 0.1,
or 0.07, or 0.927. So a value between zero and one, not including one. So 0.99999 is
the top value, okay? First, then what we need to do is multiply this with three. Now if
we run it, you see that I'm getting a value between zero and 2.999990 2.999, is my current range.
Now, the value I want is either 01 or a two. So I'm not too far from this. And the way
I can get that is by stripping away the decimals by flooring it in other words, math dot floor,
like that. You can do to zero to one, yes, now we are generating random numbers between
zero and two. How can we use that to get back a random hand either rock paper scissor ladder,
simply by doing hands, and then using the random index as the index. Now let's run this.
We're getting scissor. We're getting paper, and we're getting rock. Brilliant, great job.
Now I have a fun little challenge for you. Because you can see this fruits array here,
which contains emoji fruits, basically, three apples and two oranges mixed together, you
are going to take these fruits and sort them onto the apple shelf, or the orange shelf,
the apple shelf is the one at the top here and the orange shelf is the one at the bottom.
They are just simply divs, I've given a little bit of styling. So you are to create a function
that when called puts the apples onto the apple shelf and the oranges onto the orange
shelf. And you should use a for loop, a conditional statement and the text content property to
achieve this. Now, one thing you might be wondering is how do you work with emojis in
JavaScript, and actually, you can treat these as normal strings. It's just as if it said
orange here instead of having the mot. So with that, I wish you good luck, and I'll
see you later when I'll show you my solution. Okay, hopefully that went well. Let's do this
function. I'm gonna call it short fruit like that. And then inside of the function, we
first need to loop through all of the fruits for let i equals zero. I equals less than
fruit, da Thanks. And I should be incremented upwards. Now inside of this, we need to check
at every step in the iteration. are we dealing with an apple? Or are we dealing with an orange
shell do if fruit I, that's the current fruit, triple equals, then I can just copy this apple
here. If it's an apple, well, then we are going to do Apple shelf dot txt content. In
here, we're not going to do just equal the apple, we're going to plus equal because we
want to gather all of our apples here and not wipe them out every time we run this code,
then, I'm going to do an else if fruit I triple equals this time an orange, well, then we
are going to head over to the orange shelf and do text content plus equals the orange.
Now, it would have worked perfectly fine if we just admitted this as well like that, because
in our array, if it isn't an apple, we know that it's an orange. But we might be getting
other erase which some of bananas in them as well. And if so we don't want to put any
bananas in the orange shelf, we want to check explicitly that we are dealing with an orange
before we put the fruit up on the shelf. So finally, we just need to sort fruit to run
the code. Let's do that. And there we go. We got three apples and two oranges neatly
sorted on both of the shelves. So great job. Hey, and welcome to this excellent
where we are going to build the Chrome extension, which is just so freakin cool. Because Chrome
extensions, if you haven't seen them are programs that can enhance your browser experience in Chrome.
This is an example called honey. It's really brilliant. Because what it does is gather
coupons from all over the web. And when you visit a page where you want to buy something,
it gives you whatever coupons it can find online, so that you can save money and it
was acquired by PayPal for $4 billion. So pulling Chrome extensions is huge, because
I mean, everyone uses browsers and and surely what comes out of the box when you use Chrome
surely hasn't thought of every single problem people might encounter when they are using
browsers and browser extensions is our way as developers to build solutions around these
problems. Here's another one, Grammarly. I use it all the time here. So when I write
for so for so for example, when I write tweets, it sits on top of Chrome and checks my spelling
because it has access to what I do on the page, and then suggests how I should improve
my spelling and my writing in general. And this one right here is a lifesaver. It's motion.
And it saves me hours every single day by stopping me right before I tried to enter
for example, Facebook, and it does this with a ton of other distracting sites as well so
that I can focus on what matters, like for example, creating courses on scrambler writing
code or doing productive stuff. So, so cool. If you want to check out more extensions,
you can head over to Chrome dot.google.com slash webstore. There, you can search through
all of them. And also, if you want to open your extensions in Chrome, just click this
puzzle icon in the top right corner and you will see all of your extensions. And here
is the lead tracker. What's that? Well, that is the one we are going to build in this section.
It is based on an insight I had when I worked as a developer in a company called Sen, which
is a provider of price information for people who are shipping containers. Because what
I saw there was that the sales team at that company spent countless hours tracking down
leads or sourcing leads, as they also call it. And that is looking for people online
who might be interested in your product. So what they do is like, browse through a bunch
of pages and look at people and like no, this guy is probably not interested in our product.
This will neither are Yes, here we have a potential customer, let's save this one to
our system. Moving on, this person does not look like a potential customer. But this all
of us. Yeah, and this one does as well. But this one does not look like a potential customer.
So what they then had to do is take these three potential customers and store them somewhere
so that they could reach out to them in the next face. And this is something that and
this is something that basically every single sales representative does, because I mean,
you need people to sell to, so you need to find them somewhere. So early Stryker will
be a tool for these kinds of people. The way it works is that you visit a website, for
example, a profile on LinkedIn, and then you open up the extensions, click on the lead
striker. And there you can see, you get the ability to save input, that is any URL that
you pass into this input field, or hit Save tab. If you hit Save tab or extension heads
over to this tab grabs the URL and saves it in a list and then you can move on to another
page for example, my LinkedIn page and then hit Save time again and boom there we have
the URL to my profile. And then moving on. This is Syndra our CTO in screamer yet again,
we Click Save tab, and his profile URL is saved. And this data is persistent. So I can
close down the app or chrome, turn off your computer on when you come back, it's still
there let you as a sales representative, and then grab these leads and do something else
with it. So this is actually a pretty useful tool for sales representatives. And it's actually
deployed in the browser so that you can use it in the real world. And the point with this
is to give you the powers to do this to actually create Chrome extension that has value and
also give you the skills you need to deploy it to someone's browser. So once you've learned
this, I would really recommend you to look for opportunities. Look for problems you see
out in the world, maybe there's a problem you have or, or someone you study with, or
someone you work with, or just a problem someone tells you about when you come across problems
people have, I want you to think, can I build a Chrome extension to help solve this problem,
because if you can do that, you truly have a superpower. And that will manifest itself
in opportunities that you will get throughout your career, if you're just willing to use
that superpower, which JavaScript and web development is. So this was a long introduction,
I hope you are as excited as me, let's just move on and build your very first Chrome extension.
Okay, in this challenge, you are going to create the basic markup we need in order to
start building our app. So you're to create an input element, which is of type text and
has the ID of input to dash L. And then you're going to create a save input button. That
is when the user will click in order to save the input, make sure to have the ID of input
dash btn. And here, save input should be the text inside the button. So go ahead and do this right now. Okay, let's
do this. I'll start with the inputs, and give the type of text and ID of input L. And the
input element is a so called void or empty tag, it only has an opening tag. So you're
not supposed to create closing tags, because you're not meant to write anything in between
input tags. This user LED is meant to add the input. So this is how you create an input
tag just mentioned, often called void or empty tags, or you'll also hear them referred to
as self closing tax. Anyway, let's move on to the button. button. And it's not a void
tag, it should have a closing tag and an opening tag. And in between, we are going to write
save input and the ID and set here as input dot btn. We now run this code you can see
yes, indeed, we have an input field and a button. Great job. Okay, now you're going
to style our app according to this design. So in the CSS file, which is where you're
going to work, you'll see that I've already styled the body tag a little bit. Specifically,
I've cleared out the the margin, since browsers often add a default margin to the body tag,
I had to set that to zero to neutralize that, because I don't want any margin on the body.
However, I've set the padding to 10. Because I do want a little bit of padding. You can
see here on the body element that there's some space between the edges and where our
elements start. That is the padding that is provided. In here, I've also set a font of
Arial, not as a web safe font, so that one should work without, for example, using Google
fonts in our project as well. So just click on the slide here when you want to see the
sign and click outside of the slide when you want to go back to the code. And I've also
added a little helper text here, which is the hexadecimal code of the green color, which
you can see on the button and on the borders of the input field. Now you can see on the
bottom image here that I've added some text to the input field, the slightly bluish color
in the background here, it's not something you are to configure, that's just default
styling that is added by the browser. So you don't have to think about that. As far as
you know, the background of the input element will be white. Now I'm going to get you started
here with making the input element full width, because that's a little bit unintuitive. And
I want to show it to you. Because as you can see here on the input element, when we enter
text into it, we have a little gap between the text and the edge of it. However, in our
app now that you will see that there is basically no gap. So we have to add a little bit of
padding on the left side, let's say 10 pixels. And there you can see we got the gap. We want
the same gap on the right hand side as well. So I'll do padding right of 10 pixels as well.
Now we have that and you might wonder why I started there. It's a little bit weird,
but let's say that we now want to provide the styling for me This input field to be
full with, well, then I'll do with and then set it to 100%. That means take up all the
available space I have inside of my container. And for the input field, the kind of container
it lives inside of is the body type. So that means that 100% should make the input
field take up the entire body, and the body has a little bit of padding as you know. So
I would expect this to actually stop at the right 10 pixels before the end of our browser.
But actually, it doesn't do that it continues on an actually goes past our browser, which
is a little bit weird. The reason is that the true with this element now is 100% plus
10 pixels plus some pixels, because it includes the padding left and the padding write an
ad stat on top of this width. So that's a problem. And it results in our input field
being wider than our body tag. And we don't want that. So the trick I'll use to avoid
that is something called box sizing. And here, I say they want you to size the box long its
borders, the right border, box, and there you can see now, full width, includes the
padding, as well as the 100% now takes into account the padding. And just make sure that
the entire thing spans across the entire body tag, but not overflowing it. I wanted to show
you that because it's not entirely intuitive. Now you have what you need. Your job is to
use only these two selectors, the input and the button selector and make it look like
the design you can see here on the slide. So go ahead and give that a shot right now.
Okay, hopefully that went well. Now, let's do this together. I'm going to continue with
our input elements, that's here, we'll see that it's very cramped above and below the
text were written in the input field. So what I can do as padding, bottom of 10 pixels,
and padding top, also of 10 pixels. Now we have something that looks much more like what
we have here. Next up, we also need the color on the border. So we'll do border, one pixel
solid, and then use its green color here, like that look good. Now, we can actually continue with the button.
The first thing is the background color, which is green color background and use this green
color again, like that. Okay, so the text is white color, right like that. There's also
padding here as well, which we need to add, there's a little bit more padding on the left
and right hand side, try padding top 10 pixels and padding, bottom of 10 pixels. And then
padding left of 20 pixels. So yeah, starting to look good padding, right 20 pixels. Now,
I actually want to clean up our code a little bit, because you can see we're using this
very verbose way of writing padding spots here. And here. In the body, as you have learned
previously, in this career path, you can use the shorthand. And if all of the top bottom
left right are of the same value, we can just use padding, I can remove all of these and
padding 10 pixels. Here, it's a little bit more complex, but the top and bottom are identical.
And the left and right are identical, what we then can use as padding, and then 10 pixels
for the top and bottom, and then 20 pixels for the left and right. So the first value
kind of becomes to the y axis above and below and the second value becomes the x axis to
the left and to the right. Move this. Now see, it looks identical as how we had it previously,
but we've removed a ton of lines, which is good. Now, another thing on the button is
that has these default borders. We don't want that according to our design. So we'll do
border numb like that. Now it's really starting to look similar, but there's two things we
want to both the text and we need a little gap between the input field and the button.
So font weight to bold, yes. And the gap between the button and the input can be added to either
of the elements. I'm going to add it to the input field, use a margin, bottom and set
it For example, for pixels, there we go. Now we have something that looks pretty much like
what we have. And it's also responsive. So we are ready to move on. Okay, now we are
going to move from the CSS over to the JavaScript, because we have to make our input button work.
And while you won't make it useful in this cast, you will at least have it log out button
clicked when the user clicks it. So you know how to do this, you're going to have to modify
both some HTML and write a function in the JavaScript file, to go ahead and do it so
that when I click the Save button, the console will log out button clicked. And once you
are done, return back to the screencast. And I will show you the solution as well. Good
luck. Okay, hopefully, you remembered that. The way to do this is to create an on click
handler on the button, there, you want to type in the name of the function that you
want to trigger. Let's call this function, save lead, for example, open and close parentheses,
then we'll head over to the index.js file and create that function, function, save lead,
like that. And inside of it, we'll do console log. Like that, we'll run the code, click
the button. And indeed, we are logging out button clicked. Great job. So while this way of writing event listeners,
where we define a function and trigger it via the onClick attribute in the HTML works
perfectly fine out in the wild will most likely see professional developers use a slightly
different technique. So it's important that you learn that one as well. And the way we
do that is by first grabbing a hold of the ID of the element, we want to hook an event
listener onto. So I'll do let input btn equals document dot get element by ID, passing in
the input batch btn. And then what I'll do is input btn dot add event listener like that,
inside of the Add event listener function or method, which is also called, I'll first
specify what kind of event I want to listen for. And here it is the click events, then
I'll write a comma and do something which might look a little bit weird, because now
we are going to define what are we going to do when someone clicks on this input button?
Well, we are going to invoke a function. And in order to invoke that function, we first
have to write it to the function, open and close parentheses and then the curly brackets
and break it onto a new line. And inside of this function, we can write whatever code
we want to be executed when the user clicks on this input button. So here, we'll do console
dot log button clicked from an event listener, like that. And let's change this to button
click from onClick attribute. Now, if we run this code, hit the button, you can see both
this line and this line is executed. However, now we can actually remove this onclick event
listener from our HTML. And some would say that this results in a cleaner separation
of concerns where the HTML doesn't worry about any event listeners, that's all gathered in
the JavaScript. So of course, then we should also remove the Save lead function. And we're
left with this running the code, clicking the button and only this line triggers. So
in the next cast, you are going to get some practice writing this type of event listeners.
So let's dive into it. So in this challenge, you are going to practice
writing event listeners using the technique you just learned. So it's a three part challenge,
where you first are to grab the box from the DOM and store it in a variable. Here you can
see the box, it's just a rectangle that says open the box, you can imagine that this is
some kind of Easter egg on a ecommerce website, where if you open the box, you get a coupon
or something like that. And as for HTML, it's just a very simple div with an ID of box.
And of course, I've styled it a little bit in the CSS file, but we're not going to worry
about that. So when you have grabbed the box from the DOM and stored it in a variable,
you are to add a click event listener to it. And then finally, log out. I want to open
the box when the box is clicked. So if you struggle to remember how to add an event listener,
using JavaScript, you can go back and rewatch how I explained that Or even better, google
it out, and you should find the solution as well. With that, go ahead and solve this challenge
right now. Okay, hopefully that went well. Let's do this
through let box equals document, get element by ID passing in box, and then add eventlistener.
It's box dot add event listener, passing in first event we want to listen for that is
the clinch. And then what do we want to trigger? when the user clicks? Well, it's this function
right here. inside of it, we're going to console dot log, I want to open the box like that.
Let's run the code. Click the box. And yes, it works. Great job. Okay, we are back at
our lead tracking app. Now, of course, you are going to do what I showed you before you
learned about addEventListener, which is to refactor our app, so that it uses the dot
addEventListener. When you click on the Save input button, because this is crimbo, I am
not supposed to write the code. So even though I've already done it, Now, it's your turn
to go ahead and do this right now. Okay, hopefully, that went well. Now, I will quickly do it
as well, we need to grab a hold of the button. I'm going to grab the ID here. And do let
input btn equals document dot get element by ID passing in the ID. Now that we have
that we can do input btn dot add event listener, we're going to listen for clicks. And the
code we want to run. When users click the button is inside of the body of this function
right here. So I'm going to copy this console log, paste it in there. x Now I can remove
the Save lead function. And I can also remove the onClick attribute in the HTML. Like that,
I'll rerun the code and click Save input. And indeed, it works. Great job. Let's move
on. Now, we need to set up the infrastructure for being able to actually save the leads
that we enter into our input field. And for that, we need two variables. First a my leads
variable which should be assigned to an empty array. Secondly, the input l variable, which
should be assigned to the text input field. With that I mean, the input field right here.
So go ahead and create these two variables right now. Okay, the way to do this is let
my leads equals an empty array like that. And for the infidel, you probably did let
input L equals document, get element by ID passing in the input L. However, what I'm
going to do is swap out this let with const. That's weird. Why am I doing that? You might
wonder that is because modern JavaScript developers use both let and const to declare variables.
And now I think it's about time that you learn both of these methods. So we're going to set
the input data const and also the input btn. Now, the main difference between const and
let is that cost cannot be reassigned. And the name kind of hints to that. It says const,
which is short for constant. So whatever you assign it to, should be constant, meaning
you can't reassign it. And if you don't remember what reassignment is, it's when you do input,
for example, equals Hello. This won't work. If I run this code can actually
see assignment to constant variable. I tried to assign the input L, whether it's a constant.
So JavaScript is saying, Ah, not allowed. Now, you might ask, why do we need this? This
seems to be something that just makes it more difficult for us to code because it gives
us less freedom? Well, that is a very good question. So in the next cast, we'll dig into
exactly that so that you properly understand why you want to use both let them const and
actually get some practice using both of these variable types. Okay, let's say that we are
back at our blackjack game, and we have two variables player name and credits. The first
one is a const verse The second one is a let. Now, immediately upon seeing these two variables,
a developer will understand that player name is not to be reassigned. However, this developer
wouldn't only think that credits can be reassigned. Let's actually assume that credits are to
be reassigned further down in the code. So the developer would expect something like
credits equals credits minus 10, for example, and the reason for that is that developers
often use the following to decide whether or not they should use const. Or let. So if
possible, default to using const. If not, use let, if these two lines follow this methodology,
it would mean that it simply wasn't possible to write credits as a const. Because there
is going to be reassigned later down in the code. And thus, we skipped the default of
const, and use left instead. And this is actually the biggest benefit with const. It gives us
a way to quickly signalize to anyone who are reading the code, what we want to do with
the variables. So in addition to expecting that something like this here would happen.
The developer would also be very suspicious, if we saw something like that your name equals
something else down here, because that would mean that the person writing this code mixed
up their let and const, or perhaps didn't even understand it, as we know, this will
give us an error. So with all of this knowledge, and following this methodology, I want you
to do a challenge, which of the variables below should be changed from left to const?
Here, the situation is an ecommerce shop, we have a base price, a discount, shipping
cost and shipping time. At some point though, the details of the shipping changes, and then
you calculate the full price. And finally notify the customer. So go ahead and change
some of these variables to cost. And then I'll show you the solution afterwards as well.
Okay, let's do this. I'm going to start down here on where things are reassigned, it's
easy to see that these are reassignment, since we're starting a new line with just the variable
name, not let in front of it. So here we are reassigning shipping cost and shipping time,
meaning these two can be left. And this is a new variable. So actually, here's the end
of our code and base price and discount, they haven't changed. So they could be const. And
it says here, if possible, use const. So default to const. So then I'll do const and const.
Like that. And the code works perfectly fine. I haven't broken anything. Is there anything
else we can do? Yep, actually, it is. Here at full price, we see that this variable is
only assigned once it's not reassigned further down, just used here in the console log, meaning
that this one also should be a constant. So hopefully, you now understand why we want
to use const. And let, and if it's still a bit confusing, don't worry about it, we're
going to continue using these variables throughout this course. So eventually, it'll be completely
natural for you to switch between these two variable types. With that, let's return back
to our lead tracker app. Okay, we are back in our lead tracker app. And now we need to
make sure that when the user hits the Save input button, a lead is pushed to the My leads
array. For now, we're just going to use a hard coded lead. So www dot awesome lead.com,
for example, and that value should be pushed to my array when the input button is clicked,
go ahead and give this a shot right now. Okay, hopefully, what you did was to here inside
of the body of this function, right, my leads dot push, and then pass in www dot awesome
lead.com. Like that, if we now also console, log out the my leads array like that, we will
actually verify that it works. I'll hit the Save input button. And there you can see,
we now have one lead in the my leads array. If I hit it again, we have two and three and
four. However, it's pretty useless, because we're just pushing the exact same thing to
the array. So let's fix up that in the next cast. Okay, so now we are going to take whatever
the user enters into the input field right here and push that value into the my leads array
when the Save input button is clicked. So push the value from the input cell into the
my leads array, instead of the hardcoded www dot awesome leads.com value right here. However,
I haven't taught you how to actually get the value from the input URL. That is, for example,
this www dot example value right here. So you need to Google that. And that's great
practice because googling is, as you know, something professional developers do every
single day. So here is what I recommend you to Google Play to find. For example, a stack
overflow question and see if you can figure it out on your own. If you don't, no worries,
I will solve this for you when you return back to this cast. So go ahead and do this
right now. Okay, hopefully this went well, let's take a look at how we can find the answer
to this by googling. So we'll take the get value from inputfield JavaScript, which is
my suggested string and just paste it into Google. There, you can see we are getting
a ton of results. The first one is the W three scrolls, I want to go to stack overflow.com.
So I'll click here, we go into Stack Overflow. And in here, we can see the question being
asked, it seems super relevant for us. And it's been viewed two and a half million times.
So it's super relevant for a lot of other people as well. Let's scroll down a little
bit to the answers because that's where the juice is. Here, we can see there are various
methods to get an input textbox value directly. And here, method one, that's probably what
you want. You can see document dot get element by ID passing in an ID and doing dot value.
Oh, that's pretty handy. So how would we go about doing that? Well, we already have the
document get element by ID. And we have stored that in the input l variable. So perhaps we
simply can do input l dot value, then let's now refresh this and do www dot board lead.com.
Save input. And yes, we can see in our console that we have pushed the value we entered into
the input field leads through.com input, and that works as well. Great job, let's move
on. Okay, now that we're able to take the input value, and push it into the Miley's
array, so that we store our data, it's time to set the stage for going the other way around
as well meaning rendering out deletes. And as you might remember, when you want to render
all of the items of an array out, you first need to loop through that array and grab each
of the items. And that's exactly what you're going to do in this challenge. Whoever to
begin with, you are going to work with some dummy data just to make it a little bit easier
for you. So I've pasted in three dummy leads in the my leads array here. So the down here
starting on line 12, you can simply write out a for loop that logs out the items in
the my leads array. Hopefully you remember how to do this. And if not, no worries, I
will of course show you the solution afterwards as well. Go ahead and give this your best
shot right now. Okay, hopefully this went well, let's do this, we'll do for let i equals
zero, because we want to start at the zero index of the my leads array, I should be less
than the length of the array. That's my lead start length, and we want to increment i upwards
with one for each step. Then the inside of the body of the for loop, we'll simply console
log out my leads using the i r iterator as the index. And I run this code you can see
in the console, yes, we are indeed logging out all three of our dummy leads. Great job. Next up, we are going to transform this for
loop from simply logging out the leads to actually rendering them out on the page. However,
in order to do that, we have to actually create that unordered list where we are to render
the leads out. So you are going to do that through a two parts challenge. The first part
is to create the unordered list element, the UL with an ID of ul dash l that's for unordered
list element. And then after you've done that, return back to the JavaScript, grab this unordered
list and store it in a const variable that's called bolwell. Little bit of a weird name
there. But of course, also short for unordered list element with the camelcase convention
we're using in JavaScript. So once we've done that, we have set the stage for actually rendering
the data out instead of just logging it so that we can do that in the following lessons.
So go ahead and solve this two part challenge right now. Okay, hopefully, that went well.
Let's do this together. Starting in the HTML, we need to create the unordered list ul and
closing the tag, giving it an ID of ul dash l that if we run the cold, nothing happens
in the browser because for the element is empty. So let's just move on to the next part.
Here we are to create a const bullet ul l Send it to document dot get element by ID,
passing in URL dash, e l like that. Now, just to make sure that we've done everything
correctly, let's console log out this element from the code, and there we can see it is
being logged to the console. Good job solving this one, let's move on. Now, you are going to render
the leads out in the unordered list we just created using the dot text content property,
which I've used in previous sections. So you are to replace the console log here with the
rendering of each item into the unordered list. Now, what will happen here is that you'll
simply render out plain text inside of an unordered list, for example, www.read.com.
If we run this, this is how it will look. And as you hopefully know, this is not how
we write list items inside of an unordered list. The way to do it originally is to use
Li elements like that, run the code so that we get this dot thing link that it's a list
item. However, for now, you are simply going to render out plain text inside of the unordered
list. So we're kind of doing it wrong first, and then we'll fix it up later. So just go
ahead and render all the leads as plain text inside of the unordered list using dot text
content, even though that's not the correct way to do it. But I wanted to do that first
because the most important thing is to make it work. And then we make it better. That's
the philosophy here. So I'm going to rerun this page so that we don't have any leftovers
from when we looked at the HTML. Now we just have an empty unordered list. Go ahead and
do this right now. Okay, hopefully this went well. To do it, you do, you ll you'd grab
ahold of the unordered list dot txt content. And here you might have been tempted to say
equal my leads, and then the index. Let's see what happens if you try that it only renders
out great lead, which is the final one. The reason for that is that at each step in the
iteration of the for loop, cleared out the entire text and assigned to whatever lead
you're looking at at that step in the iteration. So for a split second, the value of the text
content was awesome lead for another split second, it was epic lead, and then finally,
just cleared out yet again and sub two great lead. And that is what we are seeing in the
browser. Now since the for loop then stopped, it had looped through the entire loop and
then broke out of the loop. So what we rather need to do is plus equals something we also
did in our poker game, if you remember that I don't take the previous value, and then
concatenate it with the current lead we're looking at. So if we run this, you can see
now we have all three leads render out, but it looks horrible, we want to add at least
a space in between them. So if you remember that can do that with plus, and then a space.
Now, it looks slightly better if we shrink in the screen actually break out on separate
lines. But if we enlarge the screen, they are just render out in one line. So this is
still the wrong way of doing it. Since we've just added plain text inside of the unordered
list, we want to add list items. Now we at least know how to take the data in my leads
and render it out on the page. And we also know how to take whatever the user inputs
into the input field and push that value into the lead. So we kind of have a very simple
implementation of each part of the app that we simply need to put together so that we
at least have a working first version. So let's continue on. Okay, now we need to fix
the fact that we are simply rendering out plain text strings like this, inside of the
unordered list. That's that's not what we want, we want to wrap them in a list page,
of course, like this. So in order to do that, let's first try to add, for example, an Li
opening tag before the lead and an Li closing tag after the lead. Run this you can see Oh,
we simply rendered out the HTML tags as plain strings. That's not what we want. We want
our browser to parse this as HTML, so that it can really turn them into list items. And
the way to do that actually, is simply replacing this text content property. with something
called inner HTML, we do that and run the code in there. Now we have them as proper
list items with these bullets that are included on the default styling of list items. So this
means that the browser actually looked at this string right here and understood, okay,
this is actually the starting of a list element, I'm going to avoid rendering that out as a
plain string, and instead convert this entire thing to a list item. So this opens up a whole new
world of manipulating the DOM, suddenly, you can create HTML elements with JavaScript.
So let's take a closer look at inner HTML and give you some practice on how to use it.
So to help you learn inner HTML, I have a really silly example for you here. Because
let's say that you're working on an e commerce website, somehow, your colleague, the HTML
developer, has forgotten to add the buy button inside of the div container, that is a crisis
because your customers out can't buy your product. So you ask the JavaScript developer
to have to do that instead. So you're going to use the dot inner HTML property, to render
out a Buy button inside of the div container, you have to grab ahold of the div container
first, and then use the innerHTML. And the text inside of the button should be by with
an exclamation mark. So go ahead and give this your best shot right now. Okay, let's
do this. So first, I'll look at the HTML, the ID of the container is indeed container.
So I'll you start with const container equals document dot get element by ID passing in
container. Notice we have that we can do container dot inner HTML equals, here, we'll create
the button button by inside of the button, and then the button closing tag. If we run
this, yes, we can see that we have a really neat button already styled because our CSS
developer had indeed did their job. And so have you to give yourself a pat on the back
for doing this. And let's move on. Okay, let's continue on with our e commerce website. Because let's say that you want to thank the user after he's
made a purchase. That's that's a nice thing to do. So what we want to do is that when
the user has clicked the button, we are to render a paragraph under the button, but still
inside of the same container. So this container right here in which the button is rendered
inside of and the paragraph should say thank you for buying. So I'm going to help you a
little bit on the way here by creating an on click event listener inside of the button
that will try to invoke a function called by when the button is clicked. So your job
then is of course to create that by function and have it render a paragraph inside of this
container using dot inner HTML so that the user is thanked. And one thing we don't want
to remove the button, when you render this paragraph, it should be under the button.
Go ahead and give this your best shot right now. Okay, let's do this. We'll do function
by and then inside of the body of the function, we need to target the container yet again,
container an inner HTML. However, if we try now to just render out a paragraph like this,
and run the code, click the buy button, then we lost our button. Because here we just cleared
out the inner HTML, and say we want whatever's inside of the container. Right now, we don't
care about it, we want to set it equal to this paragraph in this paragraph only. What
we instead have to do is use our good old friend plus equals for now, if we run this
call, again, hit buy. And there we go. Thank you for buying neatly placed underneath the
button. Great job. Okay, we are back at our Chrome extension app. And now your job is
to do exactly what I did if you castable. And I replaced the text content with the inner
HTML so that we could render the proper Li tags instead of just plain text inside of
our unordered list. That is this element right here. So go ahead and use your freshly acquired
knowledge about inner HTML to solve this challenge. Okay, hopefully that went well. The way to
do it would be to first add a opening tag before our leads is rendered out with that
with a double quote, and Li and then of course, eight plus out we already have this empty
space previously. We don't need that anymore. But we do need a closing Li tag, if we now
run this, because he Oh, it doesn't work? Well, that is because we're still using dot
text content, we have to change it to inner HTML like that. running the code. There we
go. Three list tags rendered out exactly how we want them. Let's move on. Now that you've finally managed to work with
inner HTML, I'm going to be a little bit annoying and teach you an alternative way of solving
this that doesn't use inner HTML. Because while I prefer to make a lot of the choices
for you as to which technologies you should use to build apps, especially as a beginner,
in this case, it makes sense that you learn it in two different ways, even though we're
only going to proceed with one way in this app. And that is the dot innerHTML. But you
will see this other method being used both in scribus, front end developer career path
and out in the world. So I'm going to teach it to you. And the way to understand it is
to break this line of code into three steps. Because let's have a look at what's actually
happening here. So first, we are kind of creating the Li element. So create element, then we
are setting the text content of that element. Finally, we are taking that expression, and
kind of appending it to the unordered list. Because appending means to add something at
the end of a document. So append to unordered list. So with this, we have the pseudocode
for our solution. Let's now comment out the the original way of doing it, and then write
out in YUI. So the first thing we need to do is create the element that is done by document
dot create element. It looks almost like this document dot get element by ID here. However,
now we are creating something not fetching. And what are we creating? Well, whatever we
place inside of the parentheses, naturally, in our case, this would be an L II element.
And this is how we specified we don't need to wrap it in these HTML tags symbols. Now
we have created the list element. So we need to store it in a variable, I'm going to use
const Li. And next up, we got to set the text content. So we'll do Li dot text content equals
my leads I okay, final step appending it to the UL element? Well, then we'll do ul, oh,
Alt, append, and what do you think will append? Well, Li Li, of course, we'll take this and
pass them in there. Now, if I run this code, you can see it works. However, in my opinion,
this is easier to understand intuitively than these three lines. Because here we get to
see at least the HTML element in a more humanly readable way. But you will come across this
method as well. So now what I want you to do is basically do the same thing as I did
try to make this work with the new method. And with this line of code commented out.
And if you need help, you can use this pseudocode to Google your way to the solution. Or you
can of course, go back and watch how I did it. But after you've done it, I'm not going
to go through it again. Because I've already done exactly that. This is just a little digression
for you to get this practice of doing it another way. And then when you're done, we are going
to return back to this dot innerHTML method here from the next cast, and work a little
bit on the performance of our solution. So give this a shot right now. And then I'll
see you in the next cast. Now it's time to improve the performance of our rendering by
first creating a variable list items to hold all of the HTML, then concatenating, the HTML
element onto that variable so that you after the loop has finished can render all of them
in one go. So just to go through this, this is a three part challenge where you first
create the empty variable, which we should call list items. And that should eventually
hold all of the HTML for the list items. But to begin with, you're going to assign it to
an empty string. And then inside of the for loop. Instead of manipulating the DOM every
single time the loop runs in every iteration of the loop. We're going to rather add the
item this one right here to the list items variable instead of using the innerHTML on
the unordered list itself. And then finally, after the for loop has completed, then you
can take the list items which not contain all of the HTML you need, then render it inside
of the unordered list using inner HTML this way will make our code more performant. And
faster. So go ahead and give this a shot right now. Okay, hopefully this went well. Now let's
do this. First I'll start with the list items, I'm going to have to use a link for that one.
But it's going to be reassigned as you know, for that we cannot use const. So to begin
with, it should be an empty string like that. And here, we are going to add the items, these
guys to the list items variable, instead of setting the innerHTML directly. So this is
simply replacing this here with list items. Now after this code has been running three
times one for each lead in our array, this list items variable should contain all of
the HTML we need. So then we can render it out or doing well l dot enter HTML equals
list items like that. Let's try this run the code. And as you can see, we get the exact
same result, meaning that it works. If you're still a little bit confused of what's going
on here, I would recommend you to for example, console, log out the value of list items so
that you get to see what the value of that string is in every iteration throughout the
loop. And once you feel you have a good grasp of this, we'll move on to the next lesson.
If you find yourself struggling to remember as to whether or not the performance way was
to do dot inner HTML inside of the loop or outside of the loop, you can remember this
sentence DOM manipulation comes with a cost. And with that, you can ask well, if it comes
with a cost is it best to manipulate the DOM, namely, using inner HTML three times inside
of the for loop? Or is it best to just do it one time outside of the for loop? Well,
if it has a cost, you'd prefer to do it one time than three times. So just remember that
DOM manipulation has a cost and look at your code in the light of that. Finally, if you
are a bit confused of what's really going on under the hood with this string that we
are constructing by running through our loop, what you can do is log out list items down
here, underlined 16, just to inspect how it looks in every iteration of the loop. So feel
free to jump in and do that right now. And when you are ready, I will see you in the
next lesson. Okay, now that we have many of the pieces
of our app working, let's stitch them together so that when a user enters a lead and hits
the Save input button, it'll actually be rendered out opposed to us having to actually add the
dummy data from the get go hard coding it here on line one, so I'm going to remove these
lines and your job is split into two. First you are to wrap the code below that is from
line 13 to 17. And a render leads function and then you are to call the render leads
function inside of the event handler for the button clicks. And I'm going to remove this
console right here to make it a bit cleaner. We're just to talk through the logic here.
And what will happen is that when the user adds something into the input field, and hits
the same input, this epic lead, as you know, will be pushed to the My leads array. And
then if we call the render leads, and have this wrapped inside of that render leads function,
it should according to our plan, render out whatever items there are inside of the my
leads rate, which would be much better than what we have now where simply I can hit the
Save input as much as I want, but nothing happens, my lead just stays in the input field.
Not good. So go ahead and try to knock this one out. Okay, hopefully that went well. Now,
let's do this. All right function, render leads, and then the body of the function inside
of that, I will copy this code and also tab it out so that it's easier to read like this
looking good. And then we have to call the render leads function. We do that by doing
render leads and adding the hope and close parentheses. Now if we run the code, www dot
epic lead.com. Save it. Yes, it works. www dot awesome. leads.com, who actually works
really good job. Now we have stitched together the various pieces of our app, we have what
looks like a functional prototype, you should be really proud of yourself reaching this
far to give yourself a pat on the back. And when you are ready. Let's move on. So while
our app now works, it has a little bit of a usability issue, because if I now try to
add a lead here, and hit save, you can see it is indeed saved, the buck still persists
in the input field as well, most likely, we'd want to clear out this input field. So that
is what I now want you to do here on line eight, clear out the input field, though I
haven't told you how to do that. And that is intentional, because now I want you to
Google it. And even better I want you to try to figure out on your own what you want to
write into Google to try to solve this issue. I'm not going to give you the text you are
to paste into Google this time, you just have to try and figure that out on your own and
see if you can find the answer. Because that's a critical skill. As a developer, you will
come across problems out in the wild every single day, and you won't have me there to
tell you what to Google for you obviously have to learn how to think of a phrase to
Google yourself. So go ahead and do that. Try to figure out how you can clear the input
field, write the code, you think works, test it out. And then of course, return back to
the screencast when you want to see my solution. Okay, hopefully that went well. If not, no
worries, let's do this together. So I would, for example, Google clear input value with
the JavaScript here, you can see we get a ton of results, I normally jump to the Stack
Overflow question for let's click into that one can see HTML, how to clear input using
JavaScript. So this user is using a slightly different technique than us with a function
and something called a target. However, most of the time, I hardly even read this, I just
quickly scroll down to the first answer to see if there's some kind of hint there as
to what we are to do. And in here, you can almost ignore all of it, except for the line
in the middle here that says target dot value equals an empty string. That's interesting,
that looks like something we can use. So here, perhaps we can do input l dot value, and set
that to an empty string input l value equals like that, from the code, we'll do the three.com.
Save input. And indeed, it worked. So great job. Let's move on. Okay, now our job is to make
our leads list clickable. Because as you can see here, on the Li item, or in the browser,
this is just plain text, where we want it to be a link so that after a sales representative
has gathered all of the leads, she can click and check them out again at a later stage
if she wants to. So in order to do that, we need to map the lead in an anchor tag, that's
the a tag inside of the list item. So you need to change this expression here so that
my leads is also wrapped in an anchor tag. And then you need to use the href attribute
to point to the specific URL, which is the same as the text you are rendering out. And
I also wanted to make the link open in a new tab. And if you don't remember how to do that,
it's super easy to forget, you'll just have to google it out and figure it out on your
own. So go ahead and knock this one out, and then return back when you want to see my solution.
Okay, hopefully that went well. If not, no worries, let's do this together. So we want
the anchor tag on the inside of the Li tag. So I'm going to add in the same strings as
we are creating the Li elements, an anchor element as well. So like that, and we'll set
the href. Now, just to bits hashtag symbol right here, that I'm going to close the anchor
tag on this side. If we run the code, or add some lead into the input and save it
there, we indeed can see that we get the default link styling. So our link works. Now at this
point, you might wonder well, why am I using single quotes for the value of the href? Why
isn't it wrapped in double quotes, as you might have seen people do other places when
writing HTML? Well, that is because here we're using the double quotes to tell a JavaScript
that we're working with a string. And if we then use a double quotes here as well, then
we're actually ending the string here, as opposed to ending it here. So this is a little
bit complicated when you start having strings that need quotes inside them, then you have
to use either single quotes on the inside and double quotes on the outside or the opposite.
And now this actually becomes even more complex, because what we need to do is inside of here,
replace this hashtag with the my leads, because it's going to point to that URL as well. How
do we do that? Well, now we actually need to close off the string before the hashtag,
because we're going to add a JavaScript variable. So then we will add the double quote, a plus
sign, and then a plus again, and then a double quote, yet again, start this string right
here, of course, then this hashtag now serves no purpose, it's just an invalid character
in JavaScript, we need to replace that with the my leads. So you can remove this space
right here. Now, if we actually console log out, list items, you run the code, and try
to save an input as well again, then you can see we are getting an expression, which looks
like valid HTML, one more thing we need to do is to make the link open in a new tab.
And I told you to Google that, so let's just do that as well. And here, I will just google
href, open in New Tab. And actually, Google is smart enough to just give us the answer
at the top here. You can see it's pulled up from this rapid tables.com article. And here
you can see in order to open a link in a new window or tab at Target equals underscore
blank inside of the age doc. All right, well, I'll do target equals and kind of quotes Do
we need to use now on the inside of the string? Well, we need to use single quotes, underscore
blank Otherwise, we would have escaped out of the string again and into JavaScript land.
And we don't want to do that this is just a string. And we don't need any JavaScript
variables to express it. Now, one thing is that when you try to click these links in
this grammar browser, even though you're using target blank, it won't work properly will
open up a new tab, which just has a super weird URL, that's just a scrim Quirk. So don't
worry about that, if you run this code from your local computer, this anchor tag will
indeed work. And we now we have all of this. And it works for this string is really long.
And great, in my opinion, it's a complicated expression. And I would like us to simplify
it and avoid using these mix of single and double quotes and all of this plus signs.
And maybe we also want to write this expression on multiple lines as you normally do in HTML.
However, that won't work. As you can see, it breaks our entire code and syntax highlighting
seen by the fact that the syntax highlighting is completely off at this point. So in the
next cast, I'm going to teach you about template strings, which will solve exactly that. So
just stay tuned, and I'll see you there. So in order to make this expression a lot simpler,
we'll use what's called template strings. And to make it super clear for you the benefits
of template strings, I'm actually going to comment out this current string, and then
on a new line, create the template string so that you can compare the two. And the way
you turn a normal string into template strings by replacing the quotes that wrap the string
with backticks instead. So let's do that. And pay attention to what happens with the
syntax highlighting of my leads and the plus operators. When we do that, I'm gonna do that.
And that, as you can see, it all just became blue. So now, this is no longer a JavaScript
expression. It's just a string. But we are of course going to fix that after we've looked
at the first huge benefit with template strings, which is you can break it into multiple lines,
something we couldn't do with a normal double quote string up here. So this gives us the
opportunity to write our HTML looks like our HTML looks like in an HTML file like this.
This is a much easier expression for us humans to parse than this one up here. So now we
have that it's time to take these sections here, which previously rendered out the leads,
but now just our plain strings, and simply delete them and replace them with $1, sign
open or close curly brackets, then passing in whatever JavaScript expression we want
inside there. This is how you kind of escape out of the string, and shove a JavaScript
expression into the string my opinion, much easier than what we had here with the quote,
the plus and the expression that another plus then a quote, simply replace all that with this. And now if you want to go even further, we
can add the appearance of the anchor tag in a new line. So that we get this really nicely
formatted expression looks just like it would write it in the HTML file. We now run this
code. Save the input, it works just as it did previously. But now we have removed all
of the ugly pluses. All of this wrestling, we had to do between single quotes and double
quotes and make sure that we used each of them in proper order. Here, we can do whatever
we want, we can even replace this here with a double quote and use single quotes. They're
all that's not a good practice. This just shows the power of the template string. But
now I've been writing code for far too long. The point here is that you should write the
code. That's what scrim is all about. Go over the next few lessons, you are going to get
your hands dirty with template strings. Now, you are going to practice template strings,
or template literals. As people also call it, I prefer template strings though, as that's
just an easier expression. Your job is to take this string, which is a concatenation
of two hard coded strings and a variable and turn it into a template string. I'm console
logging it down here on line eight so that you can see results. If we run it, you can
see that it says hey James, how's it going? chairs pair? So go ahead and change this from
a standard double quote string into a template string. And then of course, I will show you
the solution when you are done. Okay, hopefully this went well. Let's do this. I'll start
by simply replacing the first double quote with a backtick and the last double coat with
a backticks then the entire thing is a string. So now if we run this, it'll say hey, plus
recipient, how's it going? Obviously, not what we want. We want James to be logged out
as well. So we can remove all of this clutter all of these plus in quotes and do dollar
sign open close curly brackets, and then type in recipients run this. Yes, it's now a template
string. Great job. Let's make our email variable even more dynamic,
so that it also can take a sender value, which is the person sending the email. So you want
to create a new variable and call it sender and set its value to your name, then in the
email template string, you are to use your center variable instead of pair, you are going
to replace this text with your variable, then just run the code and you will verify that
it works through the console log. Good luck. Okay, let's do this, we'll create a const,
call it sender. And I'll actually set it to my entire name here, Harold, we're getting
so that we can see that it actually works. When we log it out scaping out of the string
and do center like that, run this, yes, now we are logging out my entire name at the end
of the string, great job. big benefit with template strings is that you can break them
into multiple lines, which is really handy. For example, in our email case, here, you'd
most likely want to write this on multiple lines, like have the hay in one line and have
the text in one line and then the tears and the final line. And this is possible, unlike
with regular strings, like we're using here for my name, prove that let's actually try
to break this into another line. What you see here is that we get this red underlines,
and the syntax highlighting has been completely broken. And if we try to run this, I'll see
that we get a syntax error. So obviously, not something we can do, you have to get it
back on one line. But for our template strings, it will work. And that is the challenge as
well, I want you to break the email string into multiple lines, however you think it
makes sense to do that. And then you are to run the code to see that it works. However,
there's a gotcha here, which is that in the scramble console, you will only see one line,
regardless of how many lines the string actually consists of. Here is an example where I've
created this random string, which is on three different lines, you can see that in the grammar
console, we're logging it out on a single line. Whereas in the dev tools, which I've
opened here in the console that lives in the dev tools, yes, indeed logged out over three
lines. So this is a quirk with the script console is not as robust as the chrome console,
basically. So for this challenge, you will have to open up the original browser console
in order to verify that you've done it correctly. And if you don't know how to open the developer
tools, I will show you now when you're in the scrim, move your cursor up to the header
area of the screen, then right click so that you open this menu, click on Inspect, that'll
open up the developer tools, make sure you are on the console tab. Now, of course, this
is how it works in Chrome, and I'm on a Mac computer myself. So if you are on a different
operating system, and using a different browser, it might be slightly different ways of opening
up the console. But it shouldn't be a problem. If so you just need to google it out how to
open the console on Windows using Firefox, for example. So go ahead now break the email
string into multiple lines logging out and then open the console and verify that you've
done it correctly. Okay, hopefully that went well. The way to
do this is super simple, you can just make this into a new line, let's enter a new line
and can even do this. And sometimes I even like to format this as we're writing a function
body or HTML so that I tab it out. So we see it like this. But you could do like this,
if you wanted or you could do like this. I mean, the point here wasn't exactly formatted
the way I would do it. The point was just to break it into new lines, run the code,
see that in the programmer console is still just one line. Hopefully you saw that, when
you log in and out the original console, it became multiple lines. Great job. Okay, we are back at our Chrome extension
app. And now you are going to do the same thing I did before we went on our little tangent
about template strings, which is to take this list items and turn the string here into a
template string so that you can get rid of all of these pluses all of these double quotes
and auto break it into multiple lines if you want to go ahead and do that right now. Okay,
hopefully this one's well. Let's do it together by replacing the outer quotes with backticks.
And then I'll just go ahead and break it into multiple lines to get better readability.
Like that. Now I can easily see that it's a list item, which wraps an anchor tag on
a new line. And here we still have these clunky plus signs. I'll remove all of those, wrap
the JavaScript expression here, and the dollar sign and the brackets like that. Then really
exact same thing here. Oh, like that. Even break this into yet another line. So now it
looks much better. And if we run this It still works exactly how we want it to. So let's
move on. Now let's take a little break from JavaScript and head over to our index dot
CSS file, because I want you to style our list according to the provider design. And
here is the provider design, you can see the links have the same color as the rest of our
app, we don't have the bullet points, which you can see are here in the current example.
So I want you to fix that. And the three selectors you are to use are the UL Li, and the anchor
tag, and I've set them up for you. So you just have to write a few CSS properties and
values inside of these. And then once you're done, return back to the screencast. Because
then I also will show you my solution. Okay, let's do this. The first obvious thing
is that our list in the design doesn't have these bullets. And the way to remove those
are to do list style. And then none, as you can see, they are gone. Now is the space on
the left hand side, namely the padding, which we have here, which you also want to eradicate
through the padding left and set back to zero. All right, next up, the most obvious thing
is the color of the anchor tags, it should be the green one we have already in our app.
So let's fix that. We'll do this one right here and select the anchor tag color should
be not Yes, pretty good. Let's compare the two Now, what I think is that we have some
more spacing here, there's more spacing between the list items and also a little bit more
spacing above the unordered list. So starting with the unordered list, I think we can give
him margin top like 20 pixels slightly down. And for the Li elements, I think we can give
them also a margin top, maybe then five pixels. Yeah, now they have a little bit more space
in between them. So I think this looks pretty good. So this challenge is done. But before
we move on, there's one thing I want to point out. And that is that we are using very broad
selectors for our CSS, we're basically selecting any unordered list or any list item or any
anchor tag on the page. And this comes with the consequence that if we, for example, want
to add other anchor tags in our app that are outside of this list of leads, for example,
let's say we added an anchor tag in the very top of our app, kind of like a navigation,
if we run this and see says home and we add ultimately, it's in the same styling as ultimately,
this might not be what we want. Oftentimes, anchor tags and links will look slightly different
depending on the context they were shown in what we could do to solve this problem would
be to down here, when we are flipping the color specify that we only want to do that
if the anchor tag lives inside of a list item. And we'll solve that by doing l i and then
a space and then the A. Now you can see the home link has the standard styling was the
anchor tag in our list as our green styling. So this is a way of saying only target anchor
tags that lives inside of list items. However, in this case, we can get away by just targeting
our anchor tags. That's we're not planning to add any other anchor tags across the page.
So we can remove our home tag. And then just target this list item in the easiest possible
way, which is what we have here. So that's perfectly fine to do, as long as we're understanding
the future possible consequences of doing that. And now I think we do that. So let's
just move on. So even though we haven't completed our app, yet, there's still many features
left to build, I want to go ahead and deploy it right away, because I just think it's so
much fun to actually see your app out in the wild. And that gives me a ton of motivation
to continue on, which is why I often like to deploy my projects early as possible. So
in this cast, we're going to prepare our first deployment so that we in the next cast actually
can do the deployment and try our app out in the Chrome browser. As you can see, on
the left hand side here, I've added a couple of new files, namely the icon dot png, that's
just a PNG image, which looks like this little icon right here really suitable for our app
with this dollar sign as our sales representatives are to be reminded that this app will bring
in more dollars for their Commission's so you'll see a manifest dot JSON file at the
bottom here. And you might wonder, Well, what is JSON? I've never seen that before. And
you're right. We haven't talked about that earlier. But don't worry, it's nothing dangerous.
json is short for JavaScript Object Notation. And it's a way for us developers to store
and send data. And it's often used when you, for example, want to send a piece of data
from a server to a client that is to a browser. And in our case, we are using this manifest
dot JSON file to configure our app and to provide metadata about it. So Google Chrome
will read through this and look at the name. Oh, it's called leads tracker will then Google
Chrome will give our app the name leads tracker, it will also see that the version is 1.0.
So that the next time we deploy, and we change this to, for example, 1.10, no, that oh, we
have updated our version. And that's information. That's definitely useful to note for Google
Chrome. One thing you might wonder here is why these key value pairs as you can see,
which you hopefully recognize from JavaScript objects, have keys that are wrapped in quotes, because
if you remember from when we worked with JavaScript objects, previously, we didn't use quotes
around our keys. That's something you have to do when writing JSON. So don't be tempted
to think that this actually is a JavaScript object. Right now, it's not it's just plain
text, but it's using the JavaScript Object Notation for it's mimicking JavaScript object.
And you later learn how to turn a JSON object into a JavaScript object. If this is a little
bit confusing, don't worry about it, it'll sort itself out. As we look more into this.
Let's just move on and look at the two final key value pairs here, we have Manifest Version
that's just telling Chrome, which version of this JSON file we are using, there used
to be a version number one that people used, and then there was a version number two, but
now we have a version number three. So that's version number three. And finally, there's
the action. And that's kind of the meat of our application. It configures. What happens
when the user clicks on our application from the Google Chrome extensions toolbar, let
me show you that. Here, we have Twitter. And if I click on the extensions button up here,
in the top right corner, this little puzzle piece, you can see it opens up all of my extensions.
And when I click out, for example, Grammarly for Chrome, it opens up the grammerly extension.
As you can see, it uses a little icon here as well. So in the action, the default icon
that you provide, this icon, PNG here, which points to this image file we've provided,
will pop up here besides this puzzle piece button, and also the default pop up the index
dot HTML that we provide inside of our action. Well, it's our pop up. And in our case, it'll
simply be the HTML we've been building all along. Now there's one thing we need to fix
just that a Chrome extension will only be as wide as it needs to be. And Strictly speaking,
our app doesn't need to be any wider than this, because that's the way our button needs.
So we need to set a min width on the index dot CSS. And I'm just going to go ahead and
do that min width of 400 pixels, for example. Now you can see, if we go below 400 pixels,
our input field is now outside of the app. So Google, Chrome will understand that we
don't want that we want our app to be like this, this is the minimum size. So now we
finally have everything in place, your next step is to download this code. You do that
by clicking on the Settings icon in the bottom right corner and download as a zip file, download
the zipped folder, you can then open that zipped folder, for example, in your dev directory,
call it whatever you want. Here, you can see all of the files that you recognize along
with a readme file, which you can safely ignore or delete. That's up to you. And when you
have that, we are ready to deploy our Chrome extension. So let's just move on to the next
cast do exactly that. Okay, it is time to deploy our application.
And I'm so excited about this, because I just love seeing products move out into the world
and start solving problems for people. So let's just jump into this. The first thing
you need to do is to head over to Chrome dash slash lash extensions, that'll bring up this
UI you can see right here, which lists out all of your extensions. Now this address here
is a little bit funky, so you can just copy it from the file right here and paste it into
your address bar if you want to do that. And once you're there, I want you to trigger the
developer mode on so just click up here in the top right corner. Then you'll see these
three buttons appear load unpacked pack extension and update and you are going to load an unpacked
extension. So click that button. That'll bring up the file chooser menu. There you are to
navigate to the leads tracker folder that we downloaded from scrim button, the previous
cast, choose that folder and hit select and once you've done that, boom, your lead tracker
is now in the extensions interface and Actually, that's it. Now if we open up another tab,
for example, I'll open up the LinkedIn profile of Frodo, one of the cofounders of scramble,
and then I can click on the puzzle icon here in the top right corner, that will bring up
all my extensions. And there we can see our lead tracker. That is just so cool to see
the little icon here. And if we click, it brings up the user interface for our app.
So that is amazing. Now I can, for example, right in the URL we're at at the moment and
hit save input. And there it is saved to actually now we have something that you can take with
you on every website you visit and save information. But Rob has a critical flaw. Because if I
now close this app, if I click outside of our HTML file, and it closes automatically,
and then want to open it up again, hmm, actually, our leads have been deleted, because that's
just as if we were saving something to the input here. And then seeing it in the list,
and then refreshing the page, and boom, it's gone again. So every time we open up our Chrome
extension, it's a full refresh. So we need to learn how we can store data across each
refresh. How do we do that? That's not something you've learned yet. But it's not that hard.
So over the next few casts, I'm going to teach you exactly that. So that our app becomes
truly useful for sales people who need to traverse the web and gather leads. So let's
just move on and get that sorted out. So in order to fix our problem of storing leads
across page refresh, let's actually open up a browser window and see if we can find a
way to do this, by playing around with the developer tools to here I have wikipedia.org,
we're going to right click, and then hit the inspect so that we open the developer tools.
Here, we're starting out at the elements, so we see the HTML elements of the page. But
where our action happens is over in the application tab, so I'm going to click that. And there
you can see, we get a new list of fancy words here on the left hand side serviceworkers,
storage, local storage cookies, some of these names you might have already heard before,
and they're probably a bit scary. And to be honest, you don't need to know about any of
them. At this point, what we want to look at is this one right here called local storage costs. When we click that, we can see it says
wikipedia.org here, and if we click into that item as well, it opens up this table here
on the right hand side where we have keys and values. And that's something you probably
recognize from JavaScript objects, for example, or even the JSON notation. Here, you can see
that Wikipedia has created three were looking keys and given them some values. So it seems
as if Wikipedia is trying to store some value about me, because these values here in local
storage will only be available for me, they are local to me, when I visit this domain,
this data isn't shared by default with all other users to visit Wikipedia at this point.
For example, you can see portal session ID somewhere long string, that's probably totally
unique to me. But without getting into too many details here. What's important is that
this is kind of like a local database that we can use. So let's try to do that. If we
hit on the console tab, and open up the console, which you've previously seen, and then type
in, for example, local storage dot clear and open and close parentheses to call that function,
and then navigate back to the application tab, you can see that we have cleared out
all of the key value pairs in our local storage. So we were able to interact with these values
using JavaScript. Going back to the console, we can get again, for example, do local storage
dot set item, and then pass in first my leads as a string, and then comma, and then I'm
going to pass in the string of the URL that we visited previously, that is FLOTUS LinkedIn
profile, and then hit enter. If we now go back to application, again, you can see that
we have a key value pair in our local storage. The key is my leads. and the value is the
URL to photos LinkedIn profiles. And what's so cool about this, if I now try to hit the
refresh button, what you'll see is that yet again, Wikipedia adds back these three key
value pairs, but the my leads key and its value persists. And that is exactly the feature,
we're looking for persisting data cross age refresh. So with this in mind, let's move
on and try to interact with the local storage from our index.js file in the next cast. So
I'll see you there. So now we are going to use local storage in our app. And we do that
the exact same way as we did it using the console on wikipedia.org. Whenever we're writing
it in our JavaScript file, it means that we can simply use the local storage variable
that's accessible in the so called global scope. So when you're running JavaScript in
the browser, you have access to this variable wherever you are. We'll then do set item,
open and close parentheses, and then we'll first write the name of our item, we'll call
it my leads, then we'll specify the value, I'll just do, example lead.com. This is the
key. And this is the value. If I now run this code, nothing seems to have happened. But
if we actually delete this entire line, and even rerun the browser, again, so that we
know that the only way to get ahold of that data would be if it has persisted in local
storage. And then try to do exactly that by doing local storage dot get item passing in the name of our item, the
key, and that was my leaks. And then we console log that out, running the code. Ah, there
we go. Example e.com is logged to the console, because our browser remembers that we previously
saved a lead under this name. And now we can get it by is pretty cool, it opens up so many
possibilities. Now I want you to try this, you're going to solve a three part challenge.
First, you are to save a key value pair in local storage in the exact same way as I did,
and then you are to refresh the page and then get the value and log it out to the console.
Finally, I want you to clear out the local storage as well. And as a little hint, I have
added the three methods here to use down here, local storage dot set item, passing in key
and value, get item passing in key and clear, which clears out the entire local storage.
So you need to use all of these three. And one little gotcha before you take a stab at
this, both the key and the value that you pass in here and here need to be strings.
That's a limitation with local storage, meaning you can only store strings. So it is a very
primitive database, but it's what we got. So give this your best shot, and then return
back to the screencast if you want to see me do it yet again. Okay, let's do this. First, we do local storage
dot set item, I'm gonna call this one mine name and set it to compare Harold, Oregon
like that. I'm gonna run the code so that now hopefully this has been saved. Meaning
I can actually comment that out because we don't need it anymore. Now I can do local
storage dot get item, and then pass in my name like that. Actually, I'm going to score
this and a variable called name, just a little bonus here, and then console log out the name,
instead of just console logging out this expression. And we run this you see, yes, we are logging
out my name. Good stuff. Let's move on to the final part of the challenge. I'm going
to comment this out. And then I'm going to do local storage dot clear. Now if I run the
code, apparently nothing has happened. But if we now comment these two lines again, and
run it Oh, no. So my name no longer exists? Well, that's
great, because that's exactly what we tried to do by clearing out local storage here on
line 11. So as far as I can see, local storage really seems to do the job. Let's move on
and learn how to use this properly with our my leads array through that it's implemented
into our app gives us that ever so important persistence feature for our leads. Now there
is one issue with storing our leads in local storage as an array. And that's something
we'd be aware about. If we for example, were to head over to Mozilla developer docs to
read a little bit about local storage. Here you can see the window dot local storage page.
The reason it says window here is because local storage actually exists on this window
object. But you can also use the local storage variable directly. And when writing code in
general, I would say that less is more so that if I can write less code, I will do that.
So that's why I'm omitting the window dot syntax. Anyway, here we can read that the
local storage read only property of the window interface allows you to access a storage object
for the documents origin Oh my God, that's just really complicated, in my view, especially
for a beginner. So let's scroll a bit down and read about what it actually does down
in the description. The keys in the value stored with local stores are always in the
UTF 16. The Home Screen format, what the hell does that mean? I think UTF 16 domstring.
That is some hardcore stuff. But we are not going to worry about all that the only thing
that matters is string, we at least know what that is. And as you can see here, as with
objects, integer keys are automatically converted to strings. Okay, so it seems like like actually,
everything that is stored inside of local storage has to be strings. Well, that's a
problem because we were expecting to store this array here. So how do we do this? Well,
to get someone to explain this was in an easier way, I would just google out our problem store
array. In local storage, and look for the first StackOverflow question, how do I store
an array in local storage? Okay, that's our problem as well. And instead of fine reading
the question, I just jumped to the answer immediately because I'm impatient. And there
you can see a very straightforward explanation, local storage, only support strings, use JSON
dot stringify and JSON dot parse. Okay, here we can see some code. And we recognize this
local storage dot set item, and then passing in the key. And then instead of just passing
in the value, which here should be the names array, they are doing JSON dot stringify.
And passing in the names array in that, it seems as if this JSON dot stringify takes
the array and turns it into a string. And likewise, on the other side, when they are
to fetch data from local storage, they use local storage dot get item names, but then
wrapping that entire expression into JSON dot parse. So that seems to go the other way
around from string to array. Okay, so actually, let's just try this. Let's pretend that this
is our array in local storage, we have one lead here. And as we read in local source,
everything is strings. So we have to turn this into a string, and we can use that with
the backticks. Like that. Now, this is a string. And the problem here would be that, let's
say that we fetch this from local storage, and we want to push another leads to the array.
And we try to do that with my leads dot push epically lead.com. From this, if we get an
error, my leads dot push is not a function. That is because the push method doesn't exist
on strings, it only exists as a method you can use on arrays. So what we then have to
do first, here, we've gotten the data from local storage. Now we need to do what our
friend over at StackOverflow did, which was to parse the entire thing. So we can do my
leads, equals JSON dot parse, and then pass in my leads here. Now, after he push, log
out my leads, I guess now we can see now what worked, how about if we want it to go the
other way round, this here, where we're actually stratifying the array so that we can save
it in local storage? Well, this will be this situation here. We
do my leads equals JSON dot stringify. And then passing in my leads, we now run this
code in the console, it kind of looks like every so maybe not the best example. But what
we can do here is we can type of before my leads, then we'll ask JavaScript to tell us
which type is this variable here. If we run this easy, we get string. So by using the
so called JSON methods, mostly stringify. And the parse and passing in our data, we
can flip back and forth between strings and arrays. And also obviously, if we used a JSON
object like this with the curly brackets, it would turn it into a JavaScript object
and the other way around, and that's actually a more common use case. But in our case, we
have an array to work with, and it does the job perfectly well for a race as well. Okay,
now it's your turn to practice. I'm going to turn this back into a string and give you
a set of instructions. Okay, you are going to do these four steps. First, turn the my
leads string into an array, then push a new value to that array. Then turn the array into
a string again. And finally console, log the string using the type of that you just learned
to verify that it's actually a string. So go ahead and give this a shot right now. Okay, hopefully this one's well let's do this.
First, we'll do my leads equals a song based on parse passing in my leads not to turn it
into a proper array again. Now that we have it as an array, we can do my lead stop, push
it to calm Okay, we have to turn it into a string again, we do my leads, reassigning
it to JSON string if I my leads. And finally, console, log out type of my leads from the
code and we get string in our console, just as we wanted. We have gone from string to
array back to string again. Great job. Now you are going to implement the first part
of our local storage feature and that consists of saving The Maya leads array through local
storage. So that should happen here on line 11. Right after you've pushed the new lead
to the My leads array and cleared out the input field, then then we are ready to actually
save it to local storage. And you have to remember to use the JSON dot stringify when
saving it, even though the browser we're using might be kind to us and actually do this for
us. If it notices that we haven't done it. We want to be explicit about this so that
we remind ourselves that we know the difference between working with just plain text or a
proper JavaScript array. So remember to do that. And once you've written your solution,
you should run the code by filling out the input field and hitting the Save input button
because this line at the bottom of the function will also be run, and that heads into local
storage and get the item that is called my leads. So if your implementation has worked,
this console log should log out whatever you've saved to local storage as well, because my
leads is actually the key we want to use in order to save our array. So use this as the
key. So go ahead and do this. And I will, of course, show you the solution when you
return back to this cast. Okay, let's do this. First, we'll do local
storage dot set item. And here, we first need to specify what key we want to save our item
under. And that is, as I said, here, my leads. So we'll do my leads, and then a comma. And
then what we actually want to save. Now you might have been tempted to simply do my leads
like that grabbing the variable called my leads. But as I said, we need to use JSON
stringify to turn this into a text string. So we'll do JSON dot stringify and wrap the
array inside of the parentheses of the stringify method. There we have it, let's run the code.
Try to add a lead, hit Save input. And there we go. As you can see, in the console, we
are indeed logging out something that looks very much like an array with one item of awesome
lead, which is exactly what we wanted. Great job. Let's move on. So now we are able to
set items in local storage, aka we are saving leads to local storage. So that we can, for
example, do awesome leave and epic leave and then see that yes, they are indeed logged
out. Because we have fetched the item from local storage here. And actually, you can
even open up the developer tools here on screen bar, and click down to see w zero.script.com.
And there you will see my leads as the key and the values as well. And the reason it's
c w zero.scrambler.com is because that's actually the domain for this mini browser under the
hood, whatever that screen by magic, don't worry about that right now, just know that
you can access it by choosing that domain. Now, there's one big problem here though,
which is that if we now refresh this page, again, boom, our leads are gone. Or actually,
they're not gone, they still exist down in local storage. However, we haven't written
the code for heading into local storage, fetching out the leads, and then displaying them. When
we are refreshing the entire page, we're actually not doing anything, we're just setting the
my leads array to an empty array. And we're not even triggering the render leads. So there's
multiple things we need to fix up here. But we're going to start small as usual, you are
going to basically just try to get the leads from local storage, and then store that in
a variable, which I would call leads from local storage, and then log out this variable.
So now I'm going to close the console. And before you go, I want to remind you about
the JSON dot parse method that you learned earlier, because you want to use that to parse
the string you get from local storage so that you turn it back into an array, this might
be a little bit difficult, but just give it your best shot and then I will show you how
to do it as well. Okay, hopefully that went well. Let's do this. We're going to do more
or less the exact same thing we're doing here to begin with, which is basically local storage
dot get item passing in my leads, whether we need to parse this, so I'll do JSON dot
parse, and then parentheses around this inner expression right here and then store this
in a variable called leads from local storage like that. Now we can console log out leads
from local storage. We run the code and you can see there we are logging out the array
With the leads that we know that we had here in our local storage, if I now do local storage
doc clear right above this line and run it, we get no. And now you're probably wondering,
Well, what the hell does no mean. And as you learn in the next lesson, no is a so called
falsie value that we developers use to signalize. emptiness. And here, the developers behind
local storage. That is, the people over at Google who have implemented local storage
into Chrome have made it so that it returns null. When we ask for a key that doesn't exist.
And actually, this is the case for all browsers because they have followed the same specification.
However, this means that we'll end up in a situation where this variable leads from local
storage is either No, which as I said is a falsie value, or it is an array, which is
a so called truthy value. So we're in a situation where we have to act upon a variable that
is either truthy or falsy, just not the same as true and false. Meaning we have to dig
deeper into what exactly truthy and falsy means. And we'll do that in the next lesson. Okay, so let's learn about truthy and falsy
values. So let's say that we, for example, have a slot machine up. So we have a constant
credit, that's how many credits you as a player have. And then we need to check if credit
is more than zero, well, then you're allowed to play the slot machine. So we'll log out
let's play with a slot machine emoji. And then else, this means that your credit isn't
over zero. So that means that you have to be at zero, then we'll console log out. Sorry,
you have no credits, like that. Now, if we run this one time, could see sorry, you have
no credits, it's logged out. Because credits was zero, this would evaluate to false credits
is not more than zero, meaning JavaScript would jump to the else clause. Wherever if
we change this to 12, then this expression 12 greater than zero would evaluate to true
and this block of code would be run. Now, JavaScript isn't really that strict about
what you shove into the condition here. Actually, if we only shove them credit like that, and
try to run this again, you can see that we are still logging out let's play. So even
though this would be evaluated to 12, when it's shoved into a conditional statement,
as this JavaScript will then again, translate 12 to true. Likewise, if credits zero, and we run the code, you can
see, sorry, you have no credits is logged out, because this would be translated to zero
first, and then JavaScript will say, Oh, no, that's a falsie value. So I'm going to translate
that out to false. So where you before learned about true and false values, you now have
to understand truthy and falsy values. Let's try another one. For
example, YOLO, just a screen. What do you think that will be? When I run this code?
What will be logged out? Just take a guess. Okay, let's run it, we can see let's play
is log that. In other words, YOLO, or this string, right here is a truthy value, because
JavaScript turns this into true in the condition. And as well if we pass in an array of random
items from the code, that is also a truthy value. Okay, let's try another one. Let's
do an empty string from the code. That's a falsie value, because it got translated into
false, meaning this block of code didn't run JavaScript, jump to the next block the else
clause and blocked out sorry, you have no credits. So let's go back to just adding credits
here so that our a fellow makes sense. And then at this point, you might feel that truthy
and falsy values is really complex, because how will you keep track of all of these truthy
and falsy values? It seems like, there's a ton of things to remember. Luckily, though,
it's not that hard. You essentially have to remember, these six values, they are the full
c values in JavaScript, false, zero, an empty string, no undefined. And this
weird thing right here non short for not a number, and out in the real world inside of
conditionals. In most cases, you'll work with either false null or undefined. So actually,
this non here is rarely ever Use, which is why I'm not going to talk anymore about it.
Null and undefined though, deserves a little bit of time, because a lot of developers are
confused about these two, and they mix them together. Now let's look at the similarities.
First. They're both primitive data types than just like strings, numbers and Boolean. And
they're also both ways to signalize emptiness. However, on high level, the core difference
is that no, is how you as a developer signalize, emptiness, or it's undefined is how JavaScript
signalizes emptiness. So you will use no as a developer, it's useful tool where it's undefined
is something you'll be exposed to, because JavaScript will tell you from time to time
that what you're looking for is undefined. Now let's see this through the lens of an
example. That'll help us see the difference between the two. Like, you'll sometimes see
developers and declare variables and assign them a small, let's say you are creating a
live streaming app, and you have current viewers. And that's set to null meaning that no people
are watching the live streams at the moment. However, a bit later, a few viewers might
pop up when you might want to do viewers equals and then an array of Jane and next, like that,
the reason this can be useful way of describing the situation in terms of how many people
who are watching the stream is because you might want to act upon whether or not there
are people in the stream. So if current viewers and you might want to do something, for example,
notify the live streamers that people are watching. So go ahead and turn on your live
stream. Let's all log we have viewers like that. Now this block of code will only fire
if current viewers has been set to an array. So now can see it'll be logged out. And let's
say you a bit later lose all of yours you set at the mall, run the code, nothing happens,
because no is a falsie value, meaning that this will be false. worse. The array here
is a truthy value. So when current viewers equals that array, except to drew this block
of code is run. Now here you can see that null is a useful way of signalizing emptiness
because an empty array wouldn't do the trick. If we run this code, you can see we are indeed
logging this code because current viewers is an empty array, which then again evaluates
to true. So it's better to use null here is how you as a developer can symbolize
emptiness, and act upon whether or not a variable is empty. Let's now look at undefined and
see how JavaScript uses that to signalize emptiness as well. And we can do that by simply
removing everything except let current viewers, we now create a console log current viewers,
which has been declared but not assigned to a value. When we run this, we'll get undefined
for JavaScript tells us that this variable is undefined or kind of like empty. Likewise,
if this, for example, was an object, and you tried to log out the key that doesn't exist
random key using the dot syntax, you'd also get undefined. JavaScript tried to look for
this, but it was completely empty. Here, if it is an array with one item, and you try
to look for the item at index five, run this again, JavaScript says undefined. So this
way, when you see either null or undefined in your code base, it should provide you with
a hint as to whether this is JavaScript trying to symbolize emptiness, or if there's a developer
who's written that code, and has tried to signalize emptiness. So that was a long walkthrough
of the differences between null and undefined. There's more to it also, but I don't think
we need to dig deeper than this. Let's wrap up this cast. And in the next one, I'm going
to teach you a neat little trick to check if a value is truthy, or falsy, which you
can use whenever you are in doubt. And then I'm going to stress test your truthy and falsy
skills. So let's move on. If you ever wonder whether a value is truthy, or falsy, you can
check it through writing Boolean, open and close parentheses and then pass in whatever
value you want to check inside of those parentheses. Here we'll do Hello, that's a store this in a variable called True or false.
Now console log, true or false. On the code, you can see that we get true meaning that
Hello evaluates to true removing the content of the string running it again, we get false
because as you hopefully remember, an empty string is a falsie value. Now with this in
mind, you are going to do a set of challenges which I said in the previous casts So, here
they are, it's six console logs. And inside of them, we are checking a bunch of values
for their boolean value. So each of these lines will log out either true or false. And
your job is to hear after these two flashes, right, either true or false, depending on
what you think will be logged out. So go ahead and give this a shot right now. Okay, let's do this. So an empty string, as
we remember, that is a falsie value. So this will log false. Here, I'm trying to trick
you because zero is indeed a falsie value. But this is a string, which contains one character,
it's not zero. so this will be true. Here. 100. That's a truthy number. No, hopefully, you remember it, the bad is a faulty
value. So this will be false. And here, I'm also Frank, trickier, zero wrapped inside
of an array, whilst zero is a falsie value. An array is a truthy value. So this will be
true, here, minus 00 is a falsie value. And whether it's minus or plus zero, doesn't change
that. So this should be false. Let's run the code. And we get false, true, true, false,
true, false, correct. Now we'll return back to the Chrome extension. And you'll use these
truthy and falsy skills in order to build a conditional for the leads we have stored
or not stored in local storage. So let's move on. So now that we're able to check if we
have any leads in our local storage, and if so, we parsed those leads so that we get him
as a JavaScript array, we are ready to act upon whatever data we get here. And first
lesson, look at what kind of data we can get. Because there's essentially two situations
we need to account for. One is this one right here, where the my array and local stores
gives us back some data, for example, this array right here, if so, we have something
to work with, and we can render it out instantly. But then there's the other situation, which
is the one right here where actually there's no data in the my leads key in local storage,
and actually the key doesn't even exist. If so, we know that we get back Nall for that
as a falsie value. And this is a truthy value. So then the question is, what are we going
to do in these two cases? Well, if the value is no meaning that there's no leads stored
in local storage, well, we're not going to do anything, because there's no point trying
to render out any leads. If there's no leads that are saved there initially. So then we're
just going to ignore it not do anything. But if we find a couple of leads, if we get an
array back from this expression right here, then we need to first set my leads to whatever
leads, we are returning back, and then call the render leads function, because the render
leads function takes the leads in the my leads array, and renders them up. Because of course,
that's what we want to do, we want to show the user whatever we found in local storage.
So here is the challenge formulated, first check if leads from local storage is truthy,
that's this variable right here. If so, set the mile leads variable, this one up here
to its value. And by that I mean the value of this variable right here, the leads we
have fetched out from local storage, and then call render leads. So this might be a little
bit of a difficult challenge, but give it your best shot. And then I will show you the
solution as well when you return back to the screencast. Okay, hopefully this one's Well, let's do
this, we'll do if leads from local storage, that's actually everything we need to do.
Because this evaluates to either true or false the expression. And if it's a true thing,
this code will be run. If it's a falsie, then JavaScript will just jump over all of these
lines and continue down here on line 16. So inside of here, we are first going to set
my leads to this newly value we've just fetched out my leads equals leads from local storage.
And then we're going to render leads like that. If we run this now, you can see nothing
happens. That's because at this point, local storage is most likely No. Let's just log
it out to verify that. Yes, we're indeed logging out No. What we then can do instead is actually
add awesome lead and epic lead to our list. Now both of these should be saved in local
storage. We should be in this situation right now. So if I refresh Yes, now we have persistent
our leads across refresh, that is so cool. So give yourself a pat on the back, you should
be so proud of yourself reaching this far, you're now working with a small database,
basically. And that's a huge step towards becoming a professional developer. Now, we
need to fix the fact that we can't delete our leads. Because obviously, that's a feature
we need. Let's say that I'm a sales development representative. And I'm gathering leads like
this, I have four leads at this point. And I want to go ahead and contact these people
or maybe move this data over into a spreadsheet, for example, so that I again, can go out to
the world wide web and churn through leads on LinkedIn and save them to my Chrome extension,
well, then I obviously need to get rid of these existing leads, so that I get a clean
slate to start with. But now that's not possible, I can refresh this as many times as I won't,
it'll just continue to store my leads. So we need a delete button, I need something
that looks like this. And that is what you are going to do in this challenge, you are
going to style this delete button. And then later on, we're going to write the code for
its functionality as well. But first, we have to create the button in the HTML. And I'm
just going to do that for you. So like that, delete all. And as you can see, if we render
this out, you can see that it's actually looking pretty good already. It has the default button
styling that we have added in our CSS here. But we want it to be kind of the inverse of
the Save input button, so that you properly see that it's something different. And in
order to target that button, we need to give it an ID of delete dash btn like that. Now,
before you start writing your code inside of the Delete btn selector right here, I am
going to do one change on the button as a whole. Because actually, this button, which
you can see in the slide has a slightly different styling than this one here. And that is that
the border is actually not Mum, it's actually one pixel solid. And then the screen color.
Like here, I can see both buttons got one pixel added to its border. If I remove this,
you'll see that the buttons become slightly smaller, they shrink and slightly like that
with zero. And they come a bit larger if I do one. And let's just try a different color
here, red there, you'll clearly see it with one pixel. And with zero pixels, we want one
pixels of the green color, because that's needed to get this green border around this
delete all button. So now we are ready you are to style a button according to the provided
design. And you're only going to apply the styles inside of this delete btn id selector.
So go ahead and do this. And then of course, I will show you the solution as well, when
you return back to the screencast. Okay, hopefully that went well. Let's start. The first obvious
obvious thing is the background. It should be white, not green. So I'll do background.
White, right. Okay. Now, we also seemingly lost the text. But that's not the case, it's
just white, so it blends in with the background. So we need to change the color as well. And
for that, we're going to use this green color up here and paste it in. And there we go.
As easy as that. With that. Let's move on. Now we are going to make our delete all button
actually work. So you'll do that through a three part challenge. Pretty big one, actually.
But first, I'm going to give you a little mini challenge. And that is this leads from
local storage here. Should that be defined as a lead? Or do you think we should change
it to a const? Just look at what we're doing with it down here on line eight and line nine
where we are using it and take your best guess as to whether we should change it or not.
And the answer is that Yeah, actually, we do want to change this to a const because
we're not reassigning it here. And if you remember from previously, it's a good practice
to if you can use const then use cost because it enforces strictness throughout your code
base when when another developer comes in here or you in two months and looks at this
leads from local storage and see Oh, it's a constant, then I know that this will not
be reassigned further down in the code. So that was just a little digression so that
we got to clean up this little variable inconsistency here. Now let's move on to the major challenge.
As I said, it's three part. First, you're going to grab a hold of the delete button
and stored in a delete btn variable. Then you're going to listen for double clicks on
the delete button. And if you don't know how to listen for double clicks, you should just
Google it. Finally, when The button has been clicked that is double clicked, you should
clear the local storage, you should clear out the Miley's variable, that is this one
up here. And you should also clear out the DOM so that the user doesn't see any more
leads on this unordered list. So a pretty big one, but give this one a shot. And return
back to me when you want to see my solution. Okay, let's do this. I'll start up here, we'll
define a const. With medium like that. You document dot get element by ID passing in
delete btn. status, indeed, we had right here. Then, let's move on, we are going to listen
for double clicks on the delete button. And how do we do that? Well, let's Google it. I think it's a good idea
to Google add event listener and then just double click, because as you know, it's the
Add event listener we are using. By doing this, we get the Mozilla developer docs as
the first result, clicking into that, and I always scroll as fast as I can to the example
I think it's a lot easier to learn from math rather from textual explanations. Here we
can see card dot addEventListener DB l click Hmm, pretty nice. So simply leaks ETL the
event listener, and V bl, click like that. Let's then also do the function. Now, let's
just console log, double click like that. Well run the code. Double click on delete
all and yes, it's worked. If I try a single click, nothing
happens. But double click? Yes. Okay, good. Three, when clicked, clear, local storage,
the my leads variable and the DOM. Okay, let's do this one by one. local storage, if you
remember the way declare that was local storage dot clear. My leads? How do we clear that
one? Well, we actually reassign it by doing my leads, and just setting it to an empty
array, and then finally clearing out the DOM. How do we do that? Well, actually, the trick
is to simply render out leads, which now are just an empty array. So we just trigger the
render leads function, render leads like that. let's rerun this. And now try to double click
on the delete all. Yes. Now we've removed everything in the DOM. And
we have cleared the local storage, our array is empty, we have a working delete button,
we can delete this console log here, great job during this challenge. Let's move on.
Now that we have an app that actually works pretty well, we're going to do something we
haven't done a lot throughout this course, which is to refactor our code, and not only
refactor it based upon a current need, we're going to refactor it based upon a hypothetical
future use case. So for this, we're not going to use the mini browser. So I'm just going
to minimize that one. And actually, I'm also going to take this function render leads,
and move it up here, right below this conditional, because it is the render leads function, we're
mainly going to refactor. And the reason for that is the following. This function now currently
has a very low degree of what we will call reusability. Because here, it is hard coded
that whenever it's called, it's always going to look at the my leads variable, the one
we've created up here, or global variable, and render out whatever exists in that array
at that point in time. Now, let's say that we one time in the future, also have another
array, for example, let all the leads, perhaps just a bunch of slightly unimportant leads
that you've shoved into this array that you don't want to render out at any given time.
But you want to perhaps have the opportunity to bring them up from time to time, if so,
we would struggle to render them out. Because as I said, in our render leads function, we
only care about to the My leads array. So what we can do instead is to make this function
a bit more dynamic, and have it render out whatever array we tell it to render out. And
the way we do that is to pass in a variable as a so called argument, when we call it we
could take my leads here, and then pass it in like this in between the parentheses so
that it would be possible for us to use it inside of the body of our function, but without
referring to my leads. Directly like this. Now, let's just pause here for a minute before
we rewrite the body of the function, just in case, this seems weird, because you might
feel you're walking on thin ice here, but actually, you've been passing in arguments
into functions, when you have called them for quite a while now. Because that is exactly
what you're doing a pair, for example, the get element by ID function, which you are
calling and giving it to the string of infidel, so that this function, when it does its magic,
and walks through the HTML file, in the search of its of its element, knows, when it hits
this point up, here it is, this is the element I'm looking for. Because pear told me, so
when he wrote this cold told me that this is indeed the ID he wants. Haven't we done
that? Well, the function would have been like blind to whatever it was looking for, wouldn't
be able to recognize this element. But we did, of course, give it that value. And that
is also what we're doing here. Now, we're telling render leads that we want you to render
out this data right here, and then make this work, we also have to hear right, something
like, leads inside of the parentheses here as well, the way this works is that when this
function is called, with this data passed in this data, this array will become this
variable here, which is accessible inside of the body of the function. So now, we can
replace my leads with leads here, and we can replace it here.
And here, at this point, the body of this function has no idea and no relation to this
my leads global variable up here, it only cares about what you entered into the function,
when you call it. And now what actually makes sense is to skip the usage of the word leads
in the name of the function, because actually, the function at this point doesn't even know
that it's rendering out leads, it could be rendering out a bunch of names of soccer teams,
or a list of fruits, or whatever it is, it renders out whatever you pass into it. So
actually, what we want to do is remove this leads here and simply call it render. Now,
this, of course, requires us to do the same thing on the delete button. Here, we'll use
the new name, render, and we have just cleared out the my leads array. So it's an empty array.
So what we'll do is simply pass in my leads here as well. And finally, on the input button,
when we add new leads, we have also modified my leads array. So we'll take that and paste
it into the parentheses of the function invocation. And then, of course, use the updated name
as well. So now, we have a function called render, which can take any array you give
it and then render it out. So potentially, you could give it the old leads array as well.
And it's a much more dynamic and reusable function. Let's try this. rerun the code,
save awesome leads, epic lead, it works. And, yes, the delete button also works. And just
as a final notice, it doesn't matter what we call this parameter here could have called
it YOLO. If we wanted, however, that would require us to also change this to YOLO. This
to YOLO and this to YOLO. We run the code lead, it works. And we can delete it, it works
in the exact same way. However, we actually want to use semantically meaningful names.
So let's use leads instead like that. You're probably a little bit confused right now.
That's totally okay. Let's take a closer look at how to use arguments in functions over
the next few casts. Okay, let's return back to the example of greeting our users, which
we've looked at earlier in the course. So scrambled we have this welcome back pair Harold
borgan text which is visible on the dashboard. And here I have the basic setup for such a
feature using a function. Starting from the top of the file, you can see that we are heading
into the DOM and fetching a welcome element. That is the HTML you can see right here, this
paragraph, which is completely empty at the moment. And here in the greet user function,
we take that welcome element, and we set its text content to welcome back pear, Harold
borgan with an emoji at the end. If we run this, nothing happens, of course, because
we also have to call the function greet user like that. Now if we run it, we can see that
it is rendered out on the page. And this is a very typical use case for a function rendering
out a specific thing. However, it's a really bad function because it can only render out
this string right here. It can only run rob my name, which is pretty silly and it should
actually Rather be called something like Greek pear. But that would just be stupid, we're
going to use the Greek user name and rather modify the functions so that it can greet
whoever enters the app. And the way to do that is to add a so called parameter to a
function. And I can do that by writing a variable inside of the parentheses, of the function
declaration. So here, for example, write name like that. Now, it is expected that we are
to use this name variable inside of the body of the function. And indeed, we are going
to do that we are going to replace this with a name like that. So now we are constructing
this string using the first string, then the name variable, and then the final string.
Now, if we run this code, you'll see welcome pack undefined. That is because name is now
undefined. And can you take a guess at Why? Well, it is, because when we call the function,
we haven't passed in any names. And our function expected us to do that. So here in between
the parentheses, we'll simply type a name. Let's type here, for example, run the code.
And now you can see welcome back up here. So here we are passing in a value into the
function when we are invoking it, that value becomes the name variable inside of the body
of the function. And this is then changed to pair on the flight when that is called. So now I have a challenge for you. You are
to give the function a parameter, which you are to call greeting, that replaces the Welcome
back. So it will always greet me, but the greeting itself can be Howdy, or Hello, or
Nice to see you, or basically whatever, because you will define it as a parameter in the function.
And then you of course, will call it with a value so that you verify for yourself that
it actually works. Go ahead and give this a shot. Okay, hopefully, that went well, the
way to do this is by doing a greeting here, and then removing this rather writing, rethink
here and then a plus. Here, when we call it, we can do it and run the code. And then we
can see how the pair Harold borgen. Great job. Let's move on. Okay, so our function
is now pretty dynamic, since it can use whatever greeting value you want, you can kind of set
the tone, however you want when calling the function, but we need to get back the same
type of feature for the name as well. So the way we can do that is by adding a second parameter,
because you can have as many parameters as you want. So actually, here, I can do name,
and then replace this with a name like that. Now if we run this, you will see how the undefined
again, because we have only given this function one argument when we call it, but actually
it expects to both the greeting and the name. So here we have to do comma, and then famous,
for example, we run the code now, you see how many dreams, now we have a really dynamic
function here. So it's a pretty good function in my opinion. But there's one issue which
is not related to parameters, but related to the code quality of the function body.
Because as you can see, while it made sense to use double quotes for strings, when we
started out, at this point, the expression has become a little bit clunky, we have three
plus signs here. And we might even get more of them as we continue on improving this function.
So at this point, it's time to refactor this expression into using template literals. So
I want you to do that now. And then we are ready to add a third parameter to our function.
So go ahead and change this into template literals right now. Okay, hopefully, that
went well, the way to do it would be to add a template literal to begin with. And then
once you end the string, then now we can remove all these clunky plus signs and boats. And
here we have two variables, greeting and name, which we need to escape out from the string.
So we'll do dollar sign, open curly bracket, closing curly bracket, dollar sign open, and
close. Yes, this looks better, much more readable. If we run it again, you see, we get the exact
same result. Great job. And your job now is to add the ability to choose the emoji as
well, meaning you should be able to run the function and pass in a third parameter, which
decides what kind of a Moji that will be rendered to the page. So go ahead and try that right
now. Okay, the way to do it would be the same as
we've done up until now, by adding a third parameter here. And then replacing this hardcode
remotely with lots variable escaped out from the string, of course, Modi like that. And
here, we'll need to also now add an emoji when we are calling the function. Let's try
the fire one, run the code and nice, we now have a super dynamic function that we can
use to create greetings of all sorts. And it's so much better than what we started out
with. Let's move on. Okay, up until now, we've only passed in strings as arguments in our
functions, whoever you can force pass in whatever data type you want, for example, numbers.
And I want you to practice that now. So I'm going to give you a challenge where you are
to use numbers and a function that you have written from scratch. So here, you have to
combine what you've previously learned about functions and arguments. And see if you can
connect the dots together. So you are going to create a function called add, that simply
adds two numbers together and returns the sum. So down here, on line five, and six,
I'm calling this function, and then and then logging it out. I'm doing that two times.
And the first time, the number seven should be logged out. And the second time the number
111 should be logged out, because I've passed in three and four, the first time around,
and nine and 102, the second time around. So these are basically your test cases. So
go ahead and write this function here on line three, it should have two parameters, and
should return the sum of those two parameters. And then afterwards, I will of course, show
you the solution as well. Okay, hopefully, that went well. Let's do this function, ad, open, close parentheses, and then the square
brackets, and inside of the parentheses, we need to define our two parameters. We'll call
the first one, number one. And the second one, number two, I'm here, I'm just going
to return num one plus num two like that. If we now run this, we can see in our console,
we are logging out seven, and 11. Great job. Let's move on. Okay, up until now, you've
heard me say the words parameter when I've talked about defining variables in between
the parentheses when we declare a function. And I've also said arguments when we pass
in values into the function when we invoke the function. And this is probably a little
bit confusing, like, why am I using two different words, they're basically the same thing. And
actually, to be honest, in my experience, most developers mix up the words parameter
and arguments all the time. And that's totally okay. Even I actually, up until this point,
I decided to actually explain the difference in this course, would mix the two up all the
time, meaning mixing up these hair values that you pass in when you call the function
and these variables that you define when you write the original function. So weight works
is that these are parameters. And these are arguments. And in order to remember the difference
between these two, I found a really cool comic on the web, which pictures two people arguing
in a bar, and then a bouncer coming to say, Hey, take your argument outside. And that
gives us the hint, arguments are created on the outside of the function, whereas parameters
then naturally have to be on the inside of the function. So greeting a name, as you know,
are only defined here on the inside of the function battalion. Jas, they come from kind
of the outside of the function, the outer scope, this is perhaps even more clear, if
we had a variable here, which was called pi, and we set it to it like that, and then we
pass in PI here, surely this high variable is on the outside of the function, because
in this case, that is this function lines two to four, this is on line seven, and line
eight, so they are on the outside. Likewise, here num, one, num, two are the parameters,
whereas three and four are the arguments. So with this, I want you to answer these four
questions with either arguments or parameters. So the answer is one or the other. And you
are to write that here after the question mark. So go ahead and do this right now. Okay, hopefully that went well. What are greeting
and name, greeting and name well that is on the inside of the function, that means that
they are per amateurs about how to you and James well, as we've talked about these live
on the outside, when you're outside of the function, you are an argument. So they are
arguments about number one and number two, okay, these are defined in the function declaration
and live in the inside of the function, meaning the parameters three and four, are on the
outside of this function here. So they are arguments like that. So from now on, whenever
you wonder whether you should say, parameter or argument, just think about this epic cartoon
created by type alias, and actually considered clicking on this link, so that you get to
check out the blog post, which is really good. And then to be honest, you will probably meet
a lot of professional developers who can't even remember this difference, but you will.
So far, we've only passed in numbers and strings into functions that we've practiced with in
this little mini section on function parameters. However, you can pass whatever variable you
want, actually, into a function as its parameter. So now I want you to create a function, which
is called get first, and it takes an array as its only parameter. That's why I'm writing
it as arr. And this function, one called, should return the first item in the array.
So I want you to create this function and make it return the first item. And then I
want you to call it passing in an array as an argument so that you verify that it works.
And you can do that by using for example, console log to verify it, I'm not going to
give you any starter code here, you got to write the entire thing, because that helps
you get the muscle memory. So go ahead and give this a shot right now. Okay, hopefully that went well. If not, no
worries, let's do this. We'll do get first like that are and then the body of the function,
then we need to take this our variable and return the first item, we do return our open
and close square brackets and zero inside of it. Now we can do get first open parentheses
and pass in an array. Let's say this was a blackjack games, we're passing in the values
of my cards like that. If we run this, nothing seemingly will happen. Since we've only returned
to this value, we haven't logged it out. Let's actually return it and store that value in
a first card variable and then console log out first card, we run this first card is
console log as 10. And that is indeed correct. Great job. We are back at our lead striker
app. And now you are going to do what I did previously, which was to refactor the render
leads function. So that it takes a parameter which I suggest uses call leads that it uses
instead of the global my leads variable, this one right here. So hopefully you remember
how I did this, or were able to wing it on your own. Anyway, please also remember to
update all of the function invocations across the file as well, it is a good idea to update
the name as well, but it's not strictly needed. So I'll leave it up to you to decide whether
or not you want to do that. Just go ahead and give this a shot right now. Okay, hopefully this went well. Let's do this.
So we are going to create this function so that it rather takes in a parameter here,
which we're calling leads, instead referring to the global my leads variable, so then we
simply need to replace my leads with what we've called our parameter like this in these
three places. And that's it. I also want to remove leads from the name and then go up
here, change the name and also pass in the my leads variable. Do the same thing here.
And we've cleared out the my leads variable as in my leads, which now is just an empty
array. And finally down here, pass in my leads like that. Let's run this to verify that it
works. Save input, delete all Yes. Great job. Let's move on. In this challenge, we are going
to set the stage for the Save tab button. I'm going to write the HTML for you first
and then you are going to take over and do the JavaScript part of it. So a button like
that it should be called save tab. run this. We can see that we get to the Save tab button
and let's give it an ID of bash medium. Like that, now, you are first going to grab the
Save tab button and then store it in a top btn variable. And then you are going to hook
up an event listener with this button so that you listen for clicks. And when it's clicked,
you are to log out my LinkedIn URL to the console. And the way you grab ahold of that
LinkedIn URL is through navigating into this times array, it actually has an object as
its only item. And that object has a key value pair of URL and the actual string value of
the URL to my LinkedIn profile. So this might sound a little bit weird, but like, why am
I forcing you to do all this complex stuff of navigating into this array and into this
object and fetching out this value right here? Well, you'll understand this, when we implement
this with the chrome API that actually gives us access to the current tab or on at any
given point, because then we actually have to do such a navigation. So I'm just prepping
you for that. So you have to remember how to work with arrays and objects, that's great
to get some practice on. If you struggle, I will, of course, show you the solution as
well afterwards. So go ahead now and just give this your best shot. Okay, hopefully
this went well, let's do this, we'll create a const tombigbee sub btn and use document
dot get element by ID, passing in tab dash btn. As that is the ID, we gave it over in
the HTML Yes. Down here, we need to listen for button clicks on the car btn will do add
event listener, first argument is clicked. Second is a function that will be run when
the button is clicked. And here, let's console log out just this entire expression, when
you are to navigate into complex expressions like this, so often a good idea to just take
one step at a time and log out the results. Let's run this, hit the Save top and bring
up the console. Okay, we can see now that we have our URL wrapped inside of both square
brackets and curly brackets. One thing we at least need to do is navigate into the first
item of this array right here. And how do we navigate into the first item, which also
happens to be the only item? Well, we simply do square brackets zero for the zeroeth index.
Let's run this it save time. And there we can see in our console, we're now just logging
out an object. So this is an object with a key URL and the value which points to my LinkedIn
profile. How do we get ahold of that value? Well, we use the dot notation dot URL like
that. From the code again, it saved up and there we go, we have logged out my LinkedIn
URL. Great job, let's move on. Next step is to actually save the URL instead of just logging
it out. Because obviously, this doesn't do the trick for our app, we need to save it
to local storage, we need to add it to the My leads array. And we also need to trigger
a render so that the fictional leads here actually will be rendered on the page when
the user hits the tab button. So to achieve this, you basically need to do more or less
the same thing that you're doing inside of the input button. So hopefully, you've got
this. If not, no worries, I will of course, show you the solution when you return back
to this screencast. Okay, let's do this. So the first thing I
want to do is push it to the My leads array. So we'll do my leads dot push, and then pass
in this expression right here, like that. Let's comment out this one for now. Next up,
we need to save the Maya leads array to local storage. Luckily, though, we know how to do
this, that's the exact same line as we have down here. local storage dot set item, the
my leads, which is the key should be set to stringified version of the my leads array.
So let's just remember how this looks and rewrite it up here. Want to rewrite it because
it's a little bit of a complex expression. So it's good to get that practice, local storage
set item, which item Well, it's the my leads key, which is what it's called here, we are
going to set it to the My leads value. However, we need to stringify this value first. So
we'll do JSON dot string if I open parentheses, close parentheses, and a lot of spaces here
so that you understand what happens. This is the array and this is the stringified version
of that array. So the array turned into a string like this, I think okay, looking pretty
good. Now First thing we need to do is actually trigger a rerender. Because we have pushed
something to the My leads rate. Now we want to render it out with the render function
and pass in my leads as the argument so that we actually get to see it on our page. I'll
run this code, bring up the mini browser and hit the Save tab. And there you go, we got
our URL render to the page, let's combine it with a lead as well, awesome lead. Yeah,
there we go and delete all Oh, nice, it works. Really good job. So we now have a working
dummy version of our tab button. However, it's kind of useless. Because if I hit the
Save tab here, once, twice, three times, you can see we're just rendering out our hard
coded tab URL, which we have here. What we of course, rather want to do as the following,
we want to be able to open up our Chrome extension on any URL. And then when we hit the Save
tab button, the extension should head over to the address bar here, grab a hold of this
URL, and then boom, save it in our list of leads. So my question for you here is where
in our code that is on which line, should we go ahead and try to talk with the chrome
API to ask it for the current tab URL, just take a guess at where in this file, we need
to do that? Well, the place we want to do it is right here, when the user has clicked
on the tab button, and this function has been triggered. Here on line 20, we want to grab
the URL of the current tab, basically what we are doing here, but we want to do it in
the real world, not just using the made up hard coded array I've written up here on line
14. So then the question is all how do we ask the Chrome browser for this URL. And yet
again, we will resort to Google will simply write Chrome extension get current tab, that gives
us a bunch of results. And on first place, you can see the developer chrome.com. So the
documentation, if we head into that, you will see Chrome, dots, tabs, okay, description,
use the chrome dots tabs API to interact with the browser's tab system. Hmm. Sounds about
right. If we scroll a bit down, we'll see manifest. So it turns out that we have to
do some changes on our manifest file. Namely, we have to add this permissions and then fill
in taps. Okay, that's fine, but not really what we're looking for, we're looking for
the JavaScript code, in order to actually grab ahold of the tap URL itself. If we continue
scrolling down, we get to this really discouraging list of a bunch of methods of this API. And
this is so typical, when you're searching through documentation, it's very often difficult
to find the answer as a beginner. So actually, what I would do is go back to the results
we got on google.com. Because there we can find a Stack Overflow question that looks
much more humanly understandable. How can I get the current tab URL for a Chrome extension?
Okay, let's click into that one, we can see there's a person that has a problem that looks
like ours. And that person is even provided some code of how they're trying to solve this
today, Chrome dot tabs dot get selected. Let's scroll a bit down and find an answer because
that's normally where we find a piece of code we can use. so here we can see just an FYI,
for your info for people from Google. The method the original poster uses is deprecated.
Okay, to get the tab, the user is viewing and only in the window, they are viewing us
this chrome dot tabs that query, okay, and then we pass it in an object with some data.
And we get this function with tabs and a lot of code. But actually, it looks very promising.
So what I'll do then, is what all developers do almost every single day, which is to copy
code directly from Stack Overflow, so I'll copy this and just paste it in here. Because
this is where we want to talk with the chrome API. I'm gonna remove this comment. Now we
suddenly have this hairy, strange looking code, which we haven't written, it's not comfortable.
And we can also see that it's not following our conventions for writing code. For example,
it uses semi colons, which we don't like. Like that. And it also uses the var keyword,
which we don't use either. It's the old way of writing variables in JavaScript, we want
to replace that with let or const. Now I'm just going to use let, as I'm not really sure
what the point with these variables is, at this point, I just want to clean that up and
storing them as select variables will definitely work. So let's just do that. However, now
that we at least have the code according to our conventions, it's time to break this down
and really understand it, and we'll do that in the next cast. Okay, now that we have this little snippet
of code copied from Stack Overflow, it would be really tempting to actually try to run
it and just console log out tabs at this point, for example, just to figure out what's going
on here after this function is being triggered, it actually, if we try to do that, from this
cold hit the Save tab, hmm, we'll see that we get an error cannot read property query
of undefined. That's because chrome dot tabs, that's a so called API Application Programming
Interface. Sounds really scary. I know. Don't worry about that. Now. Well, I wanted to say
that is that this is an API that is only available to us, when we're running the code in the
context of a Chrome extension like this, you can see here, now, we are running the code
in the context of this scrim bar mini browser here, and we don't have access to the chrome
dot tabs, meaning it's undefined as our error message is saying, because it's trying to
read the property query of something that is undefined. So we actually just have to
try to make sense of this code and try to configure it how we think it should be, and
then deploy it to see if it works out in the wild. So what I'm going to do, I'll delete
this console log tabs. And actually, I want to delete everything inside of this function,
because we are going to figure out what we will do inside of this function on our own
by looking back at Stack Overflow. And also, I actually want to comment out these lines
of code, because while it's okay to copy it, to get it into the code base, I want to write
it with you to break it down step by step so that you understand it properly. So with
this in the background, let's rewrite it and see if we can make sense of it. So the first
thing we write is Chrome, which is a variable that we will have access to when we are running
the Chrome extension. And that is an object and that has eight tabs key and the tabs that
is an object as well. And that object has a query method like that. So here, we're kind
of saying, hey, Chrome, I want to grab ahold of your tabs, or more specifically, I want
to query you for some of the tabs. Well, then which tabs is the next question? And we'll
specify that inside of the query using an object begin with? I'm going to say, Well,
I want the active tab I'm specifying active has to be true.
And which tab is that? Well, if we look back at our slide here, you can see that in this
situation, we have one browser window that has three tabs, but it's the LinkedIn tab
that is the active one. So it will give us this tab. However, here, we can also say that
we ought to specify current window to be true as well, which is a little bit weird. What
does that mean? Well, imagine this case, if you actually had another browser window in
the background. Well, the chrome API would know about this. So naturally, you'd have
to specify Well, which one of the two windows are you looking for. And in this case, the
active window is the one in the front right here. And that is where the LinkedIn tab is
located, where we have our Chrome extension open. Also, we have to specify well, current
window, so we need that to be true as well. So here we are calling the query method and
passing in an object that describes which of the tabs we want. And then as we did up
here, where we start with a specification, and then write a function, as the second argument,
will do the exact same thing in the query function as well. We'll write function like
that. And this function will be triggered when Chrome has found the tab we've told chrome
to look for. And when chrome triggers this function, it'll give us a tabs variable like
this. It's a parameter in this function. So now, we would get access to the tabs. And
this console log would work if we were running this in the context of a Chrome extension.
Let's now bring down the console. break this up a little bit? Because the question is here,
what do we want to do inside of this function? Well, it's through this tabs keyword here
that we will actually get a hold of the URL, the string in the address bar. So it's inside
of here that we actually have to push to our my leads array, save to local storage and
call the render function. So I'm actually going to copy this code and paste it in here,
like that. And now the question is, well, what does this tabs variable include, how
do we navigate to the URL value inside of this variable? Well, it just so happens to
be that it's constructed in this exact way. And how did I know that? Well, because here
on StackOverflow on our question, we could see that on the question below that a person
got it to work by doing var tab equals tabs, zero Which is exactly what we're doing here.
And then, on the next line, it did tab dot URL, which essentially is our dot URL here.
So it turns out that this is the way to get ahold of the URL. But at this point, there's
a little problem. Since we have defined tabs here, and also up here, these two variables
will be in conflict with each other. And obviously, we don't need this hard coded variable anymore.
We want to use whatever value we get directly from Chrome. So we can keep this and just
leave this how it is. Now, let's clean up this a little bit. And then finally, head
over to manifest dot Jason because we saw in the Chrome extensions documentation that
we had to add the following to our manifest file. So permissions, and then that is an
array. And here we specify tabs. So now we are telling chrome that we want to be able
to work with the tabs in the Chrome extension, otherwise, this chrome tabs simply wouldn't
work. So in the next class, we'll go ahead and deploy this so that we finally get to
try our entire application out in the wild. So let's deploy the final version of our app.
First, you of course, have to download the zip from this scrim. And you can do that by
clicking on the Settings icon in the bottom right corner, and then download as a zip,
which we did the last time around as well. And then make sure that you take these files
and update the lead tracker folder that we also created in a previous cast. Or if you
have been working locally alongside me, you of course, can skip this step. But what's important is that the same folder gets
the new updated files, because then we head over to the chrome slash extensions page.
There, we can see our lead tracker from previously, I'm going to hit detail so that we open up
the page for our extension, and then you can hit update. By doing that, Chrome will grab
ahold of the new files and update your extension. Once that's done, we can open up a new tab,
for example, and head over to a lead we want to track here I've opened up scribus CTOs
get a profile that's sindri. Let's say we want to track this URL as a lead. And then
I'll hit the Chrome extension button. I'll choose my lead tracker. And here, I can try
save tab and boom, our Chrome extension, headed over to a tab, grab the URL and displayed
it for us. That's awesome. We can also try our input field by just passing in a random
lead, hit the Save input. And there we go. It was placed here below the URL to Syndra
skitter profile. So so far, so good. Let's open up a whole new tab now. For example,
the answer LinkedIn profile, you probably recognize Leanne, from the scrim community
as she's our community manager, let's open up the Chrome extension again, and try the
Save tab button. Yes, it worked really good. Now, the final button to try is the delete
all. And I'll hit that. And there you go, we have deleted all of our leads, this is
so cool, we've now created a real world product that can give value to sales development representatives,
or basically any person collecting leads online, which is an activity that people in almost
all companies do. So we have really created something of value that you can share with
the world. So your JavaScript skills are starting to become dangerous. congratula, congratulations,
you have reached the end of the section and actually built your own browser extension.
How cool is that you should be gutted and proud of yourself for achieving that. And
just enjoy the fact that you've learned all of these awesome concepts that we now are
going to recap. So what did we learn? Well, we started out with a const variable that
is a critical part of JavaScript. And as you can see, once we learned it, we started using
it much more than we used let for all of these DOM elements that we stored in variables,
we use const, as we will not going to reassign these. And speaking of DOM, we learned a lot
of new things about the document object model. First of all, mostly add event listener down
here at line 14, we hooked up an event listener with the time button, for example, this gave
us the benefit of not having to write the event listeners in our HTML, we controlled
everything in the JavaScript file. And that also we learned about inner HTML, down here
at line 33. We had to use this because the dot text content property didn't do the trick
when we want to render out list items like this. And finally, we also learned input value,
which is another part of working with a DOM. And that was down here when we fetched out
the value which the user had entered into the input field. Another thing we did is take
one more step into the world. Have a function. Namely, we learned about parameters, which
is what we defined here, we defined a leads parameter in the render function. And that
gave us the ability to use this variable inside the body of the function. And also, it required
us to pass in the argument of my leads when we invoked this function. This is a crucial
concept to understand if you are to make functions really reusable. So I'm really happy that
we went through this. Next up, a super cool thing we also learned
was template strings. Because that gave us the ability to write strings on multiple lines,
which looks much better, it's easier for humans to parse. And also, we could use this dollar
sign and square brackets in order to escape out of the string, instead of having to use
these plus signs, which quickly became unmaintainable and confusing to work with. And then a super
cool thing we learned was local storage here, we saved things in local storage, so that
we could work across page refresh. This is kind of your first exposure to a database,
a very simple database, of course, but still very much the same concept. That forced us
also to learn about JSON, which is a very common way of storing data in web development,
you will forced to deal with this, since you had to turn our array into a JSON array using
JSON dot stringify. And also, we had to use JSON dot parse to go the other way around
when we fetched a string from local storage. And that string just happened to be a JSON
array. And we could parse it and turn it into a JavaScript array using the JSON dot parse,
don't worry, if you are confused about JSON, parse and JSON stringify. It's totally okay
to search for which one does what every single time you do it, I've done it again and again
and again. But JSON is core. And one testament of that is the fact that you were exposed
to JSON also in another way, namely, with the manifest dot JSON file, here, we have
to configure our app. And I'm actually glad that the Chrome extension required this because
you will see JSON in many different scenarios as you work as a web developer. Finally, one
of the last things we looked into was objects in a race, namely, this tabs array here, where
you actually had an array where it's first an only item was an object. So you had to
first fetch out the zeroeth index, and then do dot URL to fetch out the URL value of that
object. And this is very common objects shoved inside of a race. So it hopefully shouldn't
scare you that much the next time you come across that. So look at this list, it is really
comprehensive. Now let's do a little thought experiment, which might help you feel less
overwhelmed of all the things you don't know anything about in web development and all
these fancy words. Because let's say that you for two weeks ago, I asked a developer,
like how do you create a Chrome extension, and then the developer arrogantly replied
to you, well, it's not hard, you just add an event listener to a button, then fetch
out the input dot value, take that value stored in an object and convert it to a JSON using
JSON dot stringify, shoving it into local storage, no big deal, you can just fetch it
out later and use JSON dot parse in order to get it back into a JavaScript array and
then render it out in the function, shove it in as a parameter and just use a template
string and innerHTML to displayed on the screen. I mean, both be yield, right? I mean, imagine
getting such a reply, you'd probably feel that you would never ever learn all of this,
because there's so many concepts you didn't understand. But actually, that reply from
the developer is actually the exact thing we have done, and you have gone through it.
So even though in and of themselves, these names sound scary, you know that if you follow
the right course, you can learn them. And you don't have to be afraid of any of the
concepts you have yet to learn. Because whilst they sound super fancy from the outside, like
JSON, actually, they're not that complicated when you look into them. So try to just have
that confidence in yourself that you know, you can learn complicated three letter acronyms
that there are nothing to be afraid of, because that'll calm you down and serve you well as
you progress on this journey into web development. With that, let's actually put your skills
to the test. Now, because we need some more repetition on these things, you need tons
of repetition, these things take a lot of time to really get into your muscle memory.
And we'll start with that in the next section where you will do some quick challenges back
to back. Let's move on. In this challenge, we are going to do some let and const repetitions
because I've created this fictional game here, which has a player and opponent the name of
the game, the points variable and the has one variable after it's been set up, the game
is played down here at line nine and 10, the player gets some point and the has one variable
is flipped. And then based upon this, we log out who the winner is in this conditional
statement down here. Now if you try to run this code, you'll see that it actually doesn't
work because I've mixed up a little bit in terms of using let and const. So you need
to fix that. You need to go Through all variables and decide if they should be let or const.
And then finally, I want you to change the console logs here from using double quotes
to using template strings. So go ahead and do this right now. Okay, hopefully this went well, let's go through
this. Now what I want to start with is actually by looking at which variables that are reassigned,
and that is actually just the two ones down here points and has one, there's no reassignment
below, and neither above, that's just the initial assignments. So that means that the
points and has one are the ones that must be let variables because remember, let variables
can be reassigned. const cannot. So we'll let and let these two need to be. So that
means that these three variables pointing to the same value throughout our entire program,
it will work perfectly fine with using let and if you prefer to that that's also okay.
But it is a good practice to use const when you can to enforce a bit more strictness in
the code and to hint to people who are potentially reading your code down the line that these
variables won't be reassigned. So actually, I'm going to do that and use const for these
three variables, now we can run the code. And yeah, we can see that it actually works.
Paragraph 200 points and one the amazing fighter again, that comes from this string right here,
which we want to turn into a template string. And the way we've got to do that is now wrap
the entire tire expression in backticks. And here, we're starting off with a JavaScript
variable. So we'll escape out of the string like that. Remove all of these plus and quotes,
get again, dollar sign curly brackets. And then we also need the scaping here as well. Let's run the code works just as it did previously.
But now we have this much more neatly packed expression, doing the same here that that,
like that. And that's it great job doing this challenge. Let's move on. In this challenge,
you are going to create a function that takes a single parameter, that should be an array,
and then it logs out all the items of the array to the console. And I've created this
My Courses array here so that you can test your function, go ahead and write this function
starting here on line seven, and then return back to me when you want to see my solution. Okay, let's do this. We'll do a function,
I'll call it log items like that. I'll name the parameter R. And then inside of the function,
I need to write my for loop for i equals zero, i is less than r dot length, and i plus plus.
And in the body of the for loop, we'll simply do console dot log R, I like that. Let's try
to run the code, log items passing in my courses. And we get to learn CSS animations, UI design
fundamentals and intro to clean code logged to the console. And these are all courses
that you can take in the future when your web development skills are a little bit further
down the line and you're ready to truly level up your design skills and your software craftsmanship.
But enough of that for now, let's just move on. Okay, now we are going to verify that
you actually know how to use local storage. So you're going to do three things. First,
save a value to local storage. It could be any value, simple string and array that doesn't
matter. Just choose whatever you want, and give it whatever key you want as well. Then
I want you to delete that code and refresh the page. So you start with a clean slate
again, because this highlights the power of local storage, the fact that you can come
back fetch values from local storage and a context which is completely unrelated to the
time when you saved to local storage. So your third step is to fetch the value from local
storage and log it out. So go ahead and give this a shot right now. Okay, let's do this. First, we're going to
do local storage dot set item. Open and close parentheses. And let's do my credit. This
could, for example, be in an e commerce shop where you gifted credits to people who came
to your website on a certain day and save that in their local storage. And maybe you
got 100 credits. This time, I'll run the code seemingly and nothing happens. But let's hope
it works. Because now I'm going to delete this. And also rerun the code. Again, I'm
coming back on a later day. And now I want to do local storage dot get item, my credits
like that. Let's store that in a variable. Mike credits, local search and then console,
log out my credits as well. running the code. And yes, we are logging out 100, meaning that
our local storage implementation works. So give yourself a pat on the back end, let's
move on. In this challenge, we are going to repeat add eventlistener and how to fetch
out values from objects that live inside of a race. So to three part challenge, first,
you're to fetch the button from the DOM and store it in a variable. The button I'm talking
about is this one right here, you can see it says log Jane's score, it's defined here
in the HTML. So maybe you have to modify that as well to give it an ID, I don't know. And
then once you have that button stored in a variable you are to use add event listener
to listen for button clicks. And when the button is clicked, you are to log out Jane's
score, and you got to do it via the data array. So you got to head into data, find Jane's
object and log out to the value of her score. So go ahead and give this your best shot right
now. Okay, let's do this. So first, we are to fetch
the button. And as we saw, the button didn't have any IDs. So it will be hard to grab it
out. give it an ID call it drain dash btn. Like that. And then I'll do const Jane btn
equals document dot get element by ID passing in Jane dash btn. Okay, so far, so good. Now
we need to use the Jane button to add an event listener onto it. What kind of events are
we listening for? Well, it's click event. So that's the first argument and the second
one is the function we want to trigger when the button is clicked. Let's verify that this
works. clicked. I'll run the code. Click the button. And yes, indeed it works. Now we have
to head into data and data is an array. So let's actually log it out first. Okay, so
we got an array with two objects. How do we get the first object of those two? Well, we
know that we can use the square bracket syntax and put in the index of the item we're looking
for. So I'll put in zero, run the code, click the button. Yes, we're only logging out James
objects, how do we get the value of 52. But we need to use the dot notation and use dot
key or dot score. In our case, we run the code, log and boom, we are logging out Jane's
score. So great job getting this far. Let's move on. Okay, now I have a really cool challenge
for you because you are going to create a sentence generator. So it's this function
right here. It's called a generate sentence. And it takes two parameters desc and R. What's
that? Well, it is a description and an array, and it should return a string. Actually, it's
a full sentence based upon the description you pass in and the array you pass in. And
it's best understood through the lens of a couple of examples. If you pass in largest
countries, as the description and the array China, India, USA as the array that is the
second parameter, then function should return. The three largest countries are China, India,
USA. Another example if you pass in best fruits as the description and apples bananas as the
array, it should return. The two best fruits are apples bananas, so we actually have to
construct the string, fetch out each of the items and also the length of the array. So
a little bit tricky, but give it your best shot, use a for loop and also a template string
to solve this, and if you're stuck or want to see my solution just returned back to the
screencast and I will of course, show you how to do it. Okay, then let's do this. I'm going to first
Start by creating this string right here. So let base string and I'm going to call it,
we use a template string and the. And then here, we can't hard code the number as its
dynamic based upon how big the array is. Because we're going to do our dot length. And then
there's a space and then you other sign and curly brackets. And here we are to fill in
the description, and then our, and the space. Now we have the bass string, what remains
is simply adding each of the items to the end of this soldier for let i equals zero,
i is less than our dot length incrementing upwards. And that will be base screen plus
equals our men using our iterator value, saddle, fetch out the specific item. Also remembering
to add a comma after each of the items. Now let's try this right sentence. Let's do highest
mountains, do Mount Everest, and kaitou will store the result of this in a sentence. And
of course, then hills will need to return the bass string, like that. And then finally,
console, log out the sentence. Okay, not bad, we got the two highest mountains
aren't Mount Everest, comma k two, comma. Okay, two things to fix here. First, we need
a space after the comma like that. Good. Secondly, we don't want a comma after the final item
in the array. How do we fix that? What we need to do is inside of the for loop, check
if we are at the last item in the array. And what is the index of the last item in the
array? Well, it is one less than r dot length. Let's do outside of the for loop promised
last index equals r dot length minus one here, we'll do if i equals last index, then we are
going to do like that, if else we are going to do like that. So what are we doing here,
in this situation where I am passing in highest mountains and these two mountains, the first
time of the iteration i equals zero, and last index equals one. So going through this for
loop checks, S II equaled last index is zero equals one No, so we're not doing this, we're
instead jumping to this point where we are adding the comma, but then the next time around
both last index, and i equals to one. So JavaScript will run this piece of code instead. Let's
try it to verify that it works. Yes, we've got it. So this was a challenging one, and
required you to think a little bit out of the box. But that's how it is as a developer,
so I hope it didn't scare you too much. If it did, just watch it over again. Try it again.
Now that you've seen the solution, and that I will see you in the next cast. In this challenge,
you are going to imagine that you are working for about the hippest company I've ever seen
this one right here, the Brooklyn agency who currently consists of these super hip people
right here, your job for this agency is to make their code a little bit more dynamic,
because now you can see that they have simply hard coded out the three team images inside
of this container. But that isn't a particularly good solution cost when they get a new employee,
they would have to update the HTML. So it's actually much better to do this using JavaScript
and create a function that renders out the three team images because that sets the stage
for easily connecting this data with a database so that you can just update the database in
order to change team if new people join or someone quits. So that is your challenge,
creating a function that renders the three team images. And this function should be using
a for loop, template strings plus equals and dot inner HTML. In order to solve the problem.
Here I have provided you with an array that contains the paths to all of the images, you
can see images slash hip one dot jpg, and hip two and hip three. And they are located
over here in the images folder. And this is actually a very common situation where you
get an array of paths which point to the data you need. So we could imagine that this for
example, had come from the database when you render the page or something like that, right
now, though, it's just hard coded into our JavaScript file. There is a little bit of
CSS here as well. But But this challenge is not about CSS, it's about JavaScript. So we're
just going to ignore that. Just make sure that the images use this class of team IMG,
and you'll be just fine. So I'm going to comment out all of these images. Now we can see we
cleared out to the container. And I'll leave the table to you go ahead and solve this challenge.
Okay, hopefully this went well. Now, let's do it together, I'll start by grabbing the
div with the ID of container because we know we need that one. Container equals document,
get element by ID container like that. And then the function. I'll call it render images
like that. And here, we need a for loop, since we are going to loop through this array. So
I'll do for let i equals zero, I should be less than the length of the images array, like that. And we'll increment upwards. In
here, we can use dot innerHTML directly, let's do that first and then refactor it a little
bit after we've gotten it to work. So I'll do container dot inner HTML plus equals, at
each step in the iteration, we need to add to the current inner HTML knobs just to clear
it out using equals arrow mg. Class of table the class was team dash
IMG. Okay, we'll do team last IMD. And the source should be each of these items right here, we'll use
dollar sign curly brackets to escape out of the string and use imds passing in the current
index, which starts at zero and add to meaning 012 perfectly suitable to use in order to
fetch up items from this array, tossing the tag. Now the final step is to make sure that
we run the function, which will do my render in progress like that will run the code and
boom, there we go, we have rendered the images out. Brilliant. Now, let's refactor this code
a little bit. Because Because there are two things I would fix up here, the first thing
we're going to fix is the dot inner HTML in the inside of the for loop, because here we
are interacting with the DOM three times one for each iteration of the loop. And that has
a cost manipulating the DOM has a performance cost, it takes a little bit of time that we'd
like to avoid if possible. Now, it doesn't really matter when we're only rendering out
three items. So we as humans won't be able to notice the difference anyway. However,
it's a good practice to do it the most performant way just to know how it's done, because it
comes today, when you need to render out tons of things and manipulate the DOM quite a lot.
So and then it actually might matter. So let's fix this, what we'll do is we'll simply create
a variable up here, for example, images on set back to an empty string, then instead
of manipulating the DOM three times down here, we'll simply concatenate this string onto
this string. So we'll replace this entire thing with imgs. Dom loss equals this expression
right here. And now after this for loop has completed, this variable contains all the
three images. And it's time to do container dot inner HTML and set that equal to imds
bomb like that. If we'll run the code and see that it works in the exact same way, just
as we expected. So no visible change for us as humans, but we know that the performance
under the hood is better, since we're not doing Dom manipulations again, and again,
we're only doing it once. Okay, the final thing which is an auth attribute, because
that is for accessibility purposes, so that people with for example, screen readers can
understand what the images contain. and here we can do employee and the company like that.
Now, we have solved this challenge, and we've made it even better than the previous solution,
since we now also use an alt tag for accessibility purposes. So great job. So you have reached
the end of this course. It's very well done. You should truly be proud of yourself. Now.
Give yourself a pat on the back and just feel great about yourself because not many people
get to the finish line they give up, but you're not a quitter. Even though this course is
finished, you should by no means stop learning. So the real question is What now? What should
you learn next. And the most important thing is that you continue building more stuff.
That's how you learn. If you just build enough stuff, everything else will fall in place.
But of course, let's be a bit more specific, there are still a lot of basic JavaScript
concepts that we haven't gone through. And it's a great idea to continue expanding upon
your basic JavaScript skills. And then when you've done that, you can move more into iOS
six and beyond aka modern JavaScript. iOS six is short. For ACMA script, six, that was
a legendary update to the JavaScript language in 2015. It's actually already five years
old. But many of the modern patterns in JavaScript come from this update. And actually, you've
learned several of them already, I just didn't bother telling you that they were part of
the ESX specification. So you are totally ready to continue learning more about modern
JavaScript. Another thing you definitely should learn is API's and Asynchronous JavaScript,
because that opens up the world to you, you'll be able to have your applications talk with
external services, third party API's, bring in data from wherever you want. And then of
course, there is server side JavaScript, so that you can build full blown apps from start
to finish. But this probably looks a little bit overwhelming. But don't worry, I have
the solution for you, here at screen. But we have something called the front end developer
career path. It's our flagship, it's the course we put the most effort into by far. And it'll
take you to a higher level as a front end developer. So looking at the contents here,
it goes all the way from learning basic HTML and CSS to getting hired. And actually, you can jump in here in Module
Three, because the course you just took is a part of the career path as well. So if you
like our style of teaching, with a lot of projects and challenges back to back, you
can just jump into module three and continue on in the same pace. So I hope I will see
you there and if not, best of luck with your continued JavaScript journey.