Full Stack Web Development for Beginners- Part 3: Javascript and API'S | Chris Dixon | Skillshare

Playback Speed

  • 0.5x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 2x

Full Stack Web Development for Beginners- Part 3: Javascript and API'S

teacher avatar Chris Dixon, Web Developer & Online Teacher

Watch this class and thousands more

Get unlimited access to every class
Taught by industry leaders & working professionals
Topics include illustration, design, photography, and more

Watch this class and thousands more

Get unlimited access to every class
Taught by industry leaders & working professionals
Topics include illustration, design, photography, and more

Lessons in This Class

    • 1.

      Welcome to the course!


    • 2.

      Download starter files


    • 3.

      Variables, strings and numbers


    • 4.

      Javascript arithmetic and operators


    • 5.

      Alert, prompt and confirm


    • 6.

      If/else statements and comparison


    • 7.

      Nesting if else statements


    • 8.

      Else if and logical operators


    • 9.

      The ternary operator


    • 10.

      The switch statement


    • 11.

      Time to practice: The dragon slayer game


    • 12.

      DOM Manipulation


    • 13.

      Adding and removing elements with Javascript


    • 14.

      Time to practice: adding elements with Javascript


    • 15.

      Javascript functions


    • 16.

      Function arguments


    • 17.

      Scope and hoisting


    • 18.

      Arrow functions


    • 19.

      Javascript events


    • 20.

      The event object


    • 21.

      External Javascript


    • 22.

      Time to practice: pixel to em converter


    • 23.

      Solution: pixel to em converter


    • 24.

      Javascript arrays


    • 25.

      Array methods


    • 26.

      Looping through arrays: forEach


    • 27.

      Looping through arrays: map


    • 28.

      Time to practice: arrays


    • 29.

      Solution- arrays


    • 30.

      For loop


    • 31.

      While loop


    • 32.



    • 33.

      Looping through objects


    • 34.

      Object constructor function


    • 35.

      Const and let


    • 36.

      Generating a random shape


    • 37.

      Repeating with setInterval


    • 38.

      Template literals


    • 39.

      Comparing objects and scoring


    • 40.

      Introduction to regular expressions


    • 41.

      RegEx find and replace project


    • 42.

      HTTP, request and response


    • 43.

      What is an API?


    • 44.

      Fetching data and query strings


    • 45.

      Async code and promises


    • 46.

      Map through results


    • 47.

      Creating our search query


    • 48.

      Improving our search


    • 49.

      Audio previews, capture and bubbling


    • 50.

      Thank you


    • 51.

      Follow me on Skillshare!


  • --
  • Beginner level
  • Intermediate level
  • Advanced level
  • All levels

Community Generated

The level is determined by a majority opinion of students who have reviewed this class. The teacher's recommendation is shown until at least 5 student responses are collected.





About This Class

Welcome to Full Stack Web Development for Beginners!

This course is designed to teach beginners everything they need to know to build full stack websites and applications!

This is part three of this huge course, teaching you all about Javascript, API'S and fetching data.

We begin with Javascript: Basics and control flow where you will learn:

  • Variables, string and numbers
  • Arithmetic and operators
  • Alert, prompt and confirm
  • if else statements and comparison operators
  • Nesting and logical operators
  • Ternaty operator
  • Switch statement
  • Dragon Slayer project!

We then move onto Javascript: DOM Manipulation, functions and events, learning about:

  • DOM Manipulation
  • Adding and removing elements using Javascript
  • Functions and arguments
  • Scope and hoisting
  • Arrow functions 
  • Events
  • Pixel to em converter project!

After this we learn about Javascript: Loops, Arrays and objects:

You will learn about:

  • Arrays and array methods
  • For each
  • Map
  • For loop
  • While loop
  • Objects and looping through objects
  • Object constructor function

Then we cover Javascript: Shape matcher game and RegEx which will cover:

  • HTTP, request and response
  • API'S
  • Fetching data and query strings
  • Async code and promises
  • Creating searches and searech queries
  • Event capture and bubbling
  • Song finder application!

This third part of the course covers all of the Javascript fundamentals you need to go on to building full stack websites.

So, enjoy this class and check out the rest of the parts as they become available!

Meet Your Teacher

Teacher Profile Image

Chris Dixon

Web Developer & Online Teacher

Top Teacher

Hello, My name is Chris and I am a Web Developer from the UK. I am an experienced trainer leading web development bootcamps and also teaching online courses.

My main areas of interest are Vue.js, WordPress, Shopify, Javascript, eCommerce, and business. I am passionate about what I do and about teaching others. 

Whatever your reason for learning to build websites you have made an excellent career choice.

My personal motivation was to become my own boss and have more freedom and flexibility in my life. I also enjoy the technical challenge it provides and the way it constantly evolves. I built my first website back in 1999 and I have watched the web evolve into what it is today.

I try to make my courses enjoyable and try to remember what it was like wh... See full profile

Level: Beginner

Class Ratings

Expectations Met?
  • 0%
  • Yes
  • 0%
  • Somewhat
  • 0%
  • Not really
  • 0%

Why Join Skillshare?

Take award-winning Skillshare Original Classes

Each class has short lessons, hands-on projects

Your membership supports Skillshare teachers

Learn From Anywhere

Take classes on the go with the Skillshare app. Stream or download to watch on the plane, the subway, or wherever you learn best.


1. Welcome to the course!: Welcome to full stack web development for beginners. This course is designed to take you from a beginner to a web developer, capable of not only building front end user interfaces of a website, but also design and build the back end to interact with too. So who am I? My name is Chris and I will be your instructor for this course. I'm a web developer and also the producer of lots of tutorials teaching thousands of students the skills they need to build websites and applications. This course is the third part in the full series, where we will continue to build on everything from the first two parts of this course. This course is all about JavaScript, APIs, and working with external data sources. We begin by looking at JavaScript basics and flow control. This will give you an introduction to the basics of the JavaScript programming language, including rounding things off with a Dragon Slayer project. Then we continue our JavaScript journey by looking at DOM manipulation, functions and events, and then finishing off the section with another mini project to give you some more practice. We then move on to loops, arrays, objects, and regular expressions. Don't worry if you are unsure of what all this means is yet. We will cover everything you need to know, and then build a fun shape matching game. See how it all fits together. We finish of this course by building a song find application. This is where things really began to get interesting as we cover APIs and fetching data from external sources. Here will connect to the iTunes library. We search for some data which we can go ahead and use in our projects. We also even look at some next generation JavaScript features from ES6 and beyond. All while explaining things in a straightforward, simple to understand way, which even beginners will understand. Along with reinforcing things with some fun yet challenging projects along the way. Hope you're all excited to learn about JavaScript and APIs in the third part of this course. 2. Download starter files: Welcome back guys. So as you already know, this is the third part in the series. It's not essential that the first two parts are completed before continuing with this course, you can just Zoom straight in if you just want to learn about JavaScript and APIs. However, if you have not completed the early sections, something you will need to progress with this course is the starter files for the song find application. If you go to the class and click on your project is here. Later on in the course when we begin to work with APIs, will have the song finder.zip, HTML and CSS, or dictated from the earlier sections of the course. If you've not already completed these, just simply download this HTML and CSS data. Then you can continue with this cause as normal. But if you take any earlier parts or not, you will also need the JavaScript starter files. These will include all HTML, and CSS to get us started with learning JavaScript. This we'll say was creating the JavaScript skeleton structures or each individual lesson. So we can dive straight in to learn in our JavaScripts. So go ahead and download the files which you need. Then let's move on to learning all about JavaScripts. 3. Variables, strings and numbers: We're going to kick off this section by looking at some of the most commonly used and also some of the simplest things JavaScript has to offer. The first concept is called data types. Data types are pretty simple. As it sounds, is a type of data which we're using. To begin, I've opened up the JavaScript starter files on number 1, which is variables, strings, and numbers. Then open up the index page, both in a text editor and also over inside the browser. In this video, we're going to look at two of these data types, and these are strings and numbers. A string is just some text, such as a name, and the number is, as you've guessed, a number which is positive or negative, such as a user's age. Also, we need a way to store these values too. This is where variables come in. We're going to go over to Chrome and open up the console, would right-click and then Inspect. Then if we go to this console tab, which is just here, this is a console where we can run some JavaScript. As always, if you're using a different browser, all major browsers have a console tool. You can usually find this console from the menu, often under the developer tools. We've already seen the Elements tab and also took a brief look at the Network tab too. This time now we are going to be using this console. To begin, we create a variable by using the var keyword. Let's just scroll in so we can see this a little bit better. Type in the var keyword. A variable is simply a place to store our data, such as a string or a number. We then give this variable a name. If we wanted to store a user's name, we could simply store the name like this. So var name equals "Chris". This equal symbol assign this value to this variable name of Chris. Then we'll end this with a semicolon. Strings needs to be surrounded in quotes. This can be either single quotes, which is just like this, or double quotes like we've used here then hit "Enter". To call this in the console would just type the name of our variable. So if we type in name, we then get returned the value of Chris. We see some arrows on the left-hand side. The rights arrow is the inputs, which you put in. So we've added the name of Chris and then return back towards we have the value of Chris. If we wanted to change the value of this variable, we can do what is called reassignments, we'll just call it a variable name. Just like this without the var keyword and set it to a new value with equals symbol. We can add a new name such as Chris Dixon, and then a semicolon at the end and hit "Enter". Now we can return back towards the value of Chris Dixon. Again, if you just call name, hit "Enter", we'll get is finally returned once more. We can create as many variables as we need to, such as our age too. Again, using the var keyword, we set the name of age and set this to a value of 34. When working with numbers, we don't surround the value in quotes just like we did with the string. We just simply type the number like this then hit "Enter". If we call our age variable by typing in age, we then get returned the value of 34. Sometimes you see undefined too, just like we've seen here, such as when we set a variable. This is just because nothing is returned. In this case, we are just simply setting or assigning this variable. We'll have our name and age variable declared. But how can we now use this? Well, we could do something like adding them to a sentence. If we declare a new variable called joined, we can set this equal to a string. So "My name is" then add a space. Then we can add a plus symbol to add. If it's to the end of this, I'm going to add our variable of name. So this will be "my name is" and then Chris. Then add a plus symbol. To add a second string, we can add "and I am" then a space, and then add our age variable onto the end. So this should print out, "My name is" Chris, "and I am" 34. Joining strings and variables like this with the plus symbol is also called concatenation or concat for short. But this is just a fancy term for joining these together. Then hit "Enter" and we can type in joined, which are variable name. Now there's our string, which we expected. JavaScript is also the default scripting language for all major browsers. So this is why all works fine inside the console. But more realistically, we want to add to the code over into our project. If we go over to our starter files, again, in our first one, which is variables, strings, and numbers, we can get to work out in this inside here. You don't need to use the starter files if you prefer. But would you say was typing all the html structure we need each time. It will also be handy for future reference too. JavaScript can be added even the head or the body section. It's often preferred to add it to the bottom of the body section just before the closing tag. This means you below did last and not block the rest of the html from loading. The JavaScript is placed inside of script tags. Let's open up the opening and closing script tag. Then we can go ahead with adding our code inside, just like we did inside the console. So just like we did before, we can add our variable of name equals Chris. To display this in the console, we can do a console.log. Then inside the bracket we can add our variable name. So save that, clear the console and reload. There's our value of Chris. We can then reassign this name just like we did inside the console. This time without the variable and then change this to be my full name. Again, with the console log the same name variable, reload, and there's our reassign name. Let's do the age next. So var age equals 34. We can also do our same string that we did inside the console of joined. We can set this equal to "My name is" add a space. Then we can add our variable name, so this will be "My name is Chris". Then the string of "and I am" space. Then add on the end, the age variable with the semicolon at the end. We can console.log our new string of joined. Over to the console, reload, and now there we go, there's our string, which includes our variables of our name and age. We said earlier that we can use double or single quotes when working with strings. There is a case when we need to be careful. If we change our quotes to be single, so it's single at the start and then the end of this string, and then also replace these two here. So now all the strings are single, save and then refresh. We see this still works perfectly fine. The problem arises when we want to use one of the same quotes in our text. If you go for, "I'm", instead of "I am", just like that, we can see that we have a blue letter here to indicate a problem. If we save and then refresh, we'll get a syntax error. This should because our quotations are no longer in pairs and things are a little bit mixed up. Fixing this is pretty straight forward. All we need to do is surround the section in the opposite type of quotes. So here, rather than having the free single quotes, let's change these around the ones to be double. Just like that. We could even just change this section here, or we can change all of these single ones to be doubles, except the one that we want here. Either way it will work fine. Save and then reload. Now our string work is perfectly fine with the apostrophe here. So this is just something to be aware of when using quotations. Now we'll move on to the next video where we'll take a look at JavaScript arithmetic and operators. 4. Javascript arithmetic and operators: In the last video, we were introduced numbers in JavaScript by store in our age into a variable. There is so much more we can do with these numbers though. Let's head over to the console and see this in action. If we click on this symbol here and clear the console, we can now start to take a look at numbers and arithmetic. Let's start with some basic arithmetic, such as subtraction, multiplication, addition, and division. So inside here, we can simply say it 10, take away five, and then returned, we get the value of five. We can go ahead and do 34. A multiplication is the start symbol. First of all, multiply by 7, and that's a value of 238. Addition is the plus symbol which you've seen before. So 12 add 6 is 18. If we want to divide in JavaScript, it's the forward slash. Three divided by three gives us a value of one. Let's try another. 12 divided by 4, which is 3. We also have modulus, which is a percent symbol. Let's do 12 percent and then three. Modulus is the remainder which is leftover after dividing. Three goes into 12 equally. There's nothing left over. The same if we do 12 and then four. Four goes into 12, 3 times with nothing left over. The value is 0. However, if we change to be 13, and then free, free will go into 13, 4 times making 12. With one leftover. This is why we get the value of one just here. All of these additions, subtractions, multiplications, divisions, and also modulus, a role, what we called arithmetic operators. The AMA operators two in JavaScript. We'll cover these two as we go through this course. These operators can also be used for values stored in variables too. Let's go over to our starter file into number two, which is arithmetic and operators. Let's close this down. Open up our second index page, and also open this up in the browser. I'm just going to copy the path from here and then paste this in to the browser. First let's look at some arithmetic operators inside of our code editor. So just here you can see all the operators which will have inside of a comment. Let's assign 0s this from variables. Variable, so let's say left school at the age of 16. Then we could says our age. My age is 34. Then we can do some calculations to work out how many years since we left school. Let's create a new variable called years since school. Then we can set this to our age. My age is 34. Take away the number of years since we left school, which is stored inside of this variable. This will translate to 34, takeaway 16. Let's check this out with a console log. Just like we did before to a console.log and then we can pass in our variable of years since school. Now the console should do this calculation photos. So refresh. We've got a spelling mistake there. So console.log refresh. So its number 18. Another thing which can trip people up is what is called operator precedence. This is just a fancy name for the order in which things happen. If we create a variable which stores the value of free numbers, just like this. Let's scroll down on, we'll add a comment. So order of operation. Let's draw a number such as 10 plus 10 multiplied by 2. Then is to a second console log. We can log to the console the value of number. Save that, reload and you get the value of 30. If we go back and look at our number, we may expect the calculation to be run from left to right. Ten plus 10 is 20 multiplied by two is 40. In fact, what happens is a multiplication happens first. Ten multiplied by 2 is 20, and then the 10 is added on, giving us a value of 30. This is the value which you see over in the console just here. This is because multiplication and also division have a higher precedence than subtraction or addition. If we wanted changes. So the 10 plus 10 happens first. We can wrap these inside of brackets, also called parentheses. Just like this. These brackets, will make sure that this calculation is performed first. This will be 20 multiplied by two given a value of 40. Let's check this out in a console by refreshing. There's a value of 40. It's worth noting too, that if all of the operators have equal precedence, then the calculation is performed from left to right. This will be the case if all operators were addition or subtraction. We said earlier these additions, multiplications and so on. Who called operators? There is also two more operators available tools called increment and decrement. Let's give this a go. If now common salaries console log with the two forward slashes. Also this one here. To give us a clear console. Below this, we want to create a new section, and this is for increment and decrement. We now know that is number of variable is a value of 40. If we're to go ahead and add number plus, plus, just like this, this would increment the value by one each time. If we save this and go over to the console with a console log of the number. This should now increment the value of 40 to be 41. If we were to go ahead and increment this again, we have number plus, plus. This should now give us a value of 42. This is something we'll see quite often in JavaScript, particularly when using loops. Let's now take a look at decrements, which as you may have guessed, will reduce the value by one each time. I'm going to do this with the negative symbols, just like that and reload. Now our initial value of 40 is now reduced to 39.This is a common thing to do for increased in a place called, for example, or increase in the number of items in the shopping basket. This is something really useful to know when using JavaScript. 5. Alert, prompt and confirm: We've already looked at using the console log in this section. This is useful for printing out things and debugging. During development, It's not intended as a way to communicate with uses of our websites or apps. However, there are some ways, multiple, more precise, some more methods we can use to communicate with the user. The first of these is an alert. An alert is used to pop up an alert box to the user. Alerts are like a pop-up box with some information and an okay button to click on to close this popup. At its most basic, we can simply output something to the user. Lets go over to our scripts inside of our starter file. Let's go to number three, alerts, prompts and confirm. Now open this up and then go to copy the path and then paste is inside the browser or you can simply double-click on the index file inside the folder. Down under the alert common tier, which is going to output a alert Popup and then inside here we can do anything we want such as a calculation. Ten modulus and then three gives a save and open up this index page in the browser. Refresh. and there's our Alert box on the screen with the value of one. We can use this to add some tax also instead of a calculation. Remember the text strings have the quotations. So let's say hello, refresh. As our text just here, this alert can even contain variables too such as our name example from before. We had a variable of name equals Chris. We could go ahead and add this to the end of our string. Hello plus our variable name. Save that and there we'll go says hello Chris, inside the alert. If we go ahead and add even more text to our alert, let's add some more text just after this. Let's say please login to continue, save that and reload. By default. All this stays on the one single line. We can break this onto a new line using a backslash and then an N. Inside of our string here, let's add the backslash and the N. This backslash followed by an N, may look a little unusual, but we'll cover what this is and also some similar ones later when we look at regular expressions. For now let's give that save, reload and now is a line break just after this N. The next one I want to show you is prompt. This will pop up on prompt the user for some input. Let's go on, comment these two out with forward slashes and then go down to this prom section. Let's begin with a simple prompts which is the name of prompts and then the brackets just after. Inside here we can add a text string so hello, what is your name? With a question mark, index page and this is how a prompt looks by default. We get a text, which we did just here and then we get an input section where the user can type in some information. This can even be canceled or click on okay. If we enter our name such as Chris inside here, and then press 'okay', nothing appears to happen. This is because we need a way to store the user's input. We already know we can do this by using a variable. Let's set this prompts to equal to a variable. Let's say var name equals prompts and then to see this in action, we can do a console log and then log the value of our name just to recap, we're prompting the user to input their name, will install all these inputs inside of a variable called name, and then displaying this inside the console. Let's save that and try this out. Say Chris, okay, right-click and inspect. Open up the console and there's our value of Chris. Let's try one more. Just type in anything inside here and there's the value stored inside this name variable. This prompt if returns the value entered by the user, like we just seen or we can select console. We click console button here, we then get the value of null returned. You will often come across both null and undefined. They both generally mean something is missing. Both null and undefined also considered data types too, just like number and string which you've already seen. Let's go over to our text editor and create an alert. Let's welcome the new user with the textile welcome space as our variable name and then add a string at the very end with an exclamation mark. If we save that, reload, we can add our name, hit "Okay" and there's our text string of welcome, Chris, with the exclamation at the end. If we reload the browser and instead hit "Cancel", we'll get the word welcome null. Null refers to a blank object reference. It may not make too much sense at the moment because we've not looked to what objects are yet. But it generally means something is missing. Basically, prompt returns even nothing. All the value which is typed in, undefined is a little bit more generic. An example of undefined is when a variable is empty. If we go ahead and create a new variable, let's say new name and then we don't set a value to this. If we alert the value of new name and then save that, refresh, says our initial alerts, let's cancel list and then we get our second alert which say is undefined and this is the value of our undefined variable here. Next we want to take a look at some fairly similar to prompt. Let's comment out these three lines here. If using Visual Studio Code command and forward slash will comment out all lines together. Now let's go down to confirm. Just under here, we can take a look at how a confirm is used. Just like the first two, we type in the name and then the brackets just afterwards. Lets begin by adding in a text string. You must be over 16 enter, let's say, please confirm and then obviously browser close it down from before, reload. That's the text that we see here. We also have a cancel and an okay button. Let's click on the cancel and also okay. Nothing appears to happen when we click on these buttons. Since confirm has no input field, it will return true. If the user clicks okay, all falls is the cancel button is selected. We can again see this by setting this to a variable. Let's say var age equals confirm. Then a console log, which passes in our age variable. Then this check this out. Open up the cancel Click on the console. Let's reload. If we click on okay, we'll get the value of true then if we click on cancel, we get the value of false. This true or false value is also another important JavaScript dates type which is called Boolean. Boolean to simply a true or false value. Once we get these true or false values, we need a way to do something with them. For example, if the users over 16, we can let them view the page or if the user is logged in, we can let them see the admin section to help decide what to do in these cases, we have conditional statements, and this is what we'll begin to look at next. 6. If/else statements and comparison: In the last video, we mentioned Boolean values which are true or false. We also need a way to actually perform an action based on if a value is true or false. To do this, we have conditional statements. For example, if a player's health is zero or less, the player will lose life. If a player collect 100 coins, then we can add an extra life. Or if the current time is the morning, we could add a good morning message. If it was in the afternoon, we could change the message to be Good afternoon. Basically, these conditional statements allow us to decide what we want our code to do under different circumstances. A common type of conditional statement is If else. Let's begin with the If section. This basically says if something is true, then run this code. I want to start a file. Let's open up number 4, which is if else and comparison. Then I'm going to open this up inside the browser. Then down to our script section, we can begin to create an if statement. We add the If keyword followed by the brackets or parentheses. Then we add a set of curly braces, where we can add our code that we want to run. Let's say we want to add an alert for our message. We need to add a condition where one is alert to run. Inside these brackets here we add our condition. We say if 10 is greater than 5, then run this alert. Lets add some texts saying 10 is greater than 5. If this is true, this alert will be run. If this wasn't true, then we wouldn't get anything happening at all. Save that, reload and there's our alert saying 10 is greater than 5. This greater than symbol is a comparison operator. There is lots more we can use, such as the less than symbol. Now 10 is not less than 5, so this will be false. Meaning if we go to the browser and refresh, the statement is now false, so we won't see the alert. This is because as we mentioned before, the code will only run if the condition is true. We can also combine these greater than and less than symbols with the equals operator too. For example, if we change this to be 10. If we were to say if 10 is greater than 10, then do this alert. Refresh. We don't see the alert because 10 is not greater than 10. However, if we want to run a check to see if 10 is equal to or greater than, we can combine them just like this. Greater than or equal to. Now our condition should now be true. Then we see the alert. This also works with less than too, as you would expect. If 10 is less than or equal to, then run the alert. This may be confusing at first because we've already used this equals symbol to assign a value to a variable. Before we were doing things such as var x equals 5. Here we're assigning the value of 5 to this x with the equals symbol. Instead when comparing, we use the double equals. We can say if x is equal to 10, then alert the value of true. Save that and refresh. Of course we don't get the alert popping up because x is not equal to 10. We can also add an exclamation mark to do the opposite. An exclamation and then equals. If x is not equal to 10, we should now get the alert popping up. Let's try something else. If we add a number, so we already have the value of x equal 5. If you add a second variable of y, and this time if we set the number inside a quotations just like this, this will be now considered a string because it's inside a quotations. We can check this out if we do a console log for each variable. Let's do a console log just below. We can say type of and then x. Save that. If we open up the console, we should now see what type of data is contained inside of x. We see the x is a number which we'd expect because we've declared that just here. However, if we go ahead and change this to be y, refresh. Now we see the data type is string because this is added inside the quotations. With this knowledge, let's see how this affects our comparison. Let's go ahead and compare the value of y, which is a string to 5. I'll save. This is a string and this is number. In theory, they shouldn't work. Refresh. We still see the pop-up. This is evaluating to true even though it's comparing a number to a string. This is because the double equals will only check the value rather than the data-type if we want this comparison to be even more strict and also check if the value as well as the date type is equal. We can go ahead and change this to be triple equals. Save that, reload. Now we don't see the pop-up because the datatype is not equal. Let's try this with x and x is a number. We're comparing if x is equal to 5, both in value and also datatype. Is of course, it should be true. We see the pop-up or true. This works because x is equal type and value to 5. However, we could also add an exclamation mark and the two equals, and this will do exactly the opposite. This will only run the alert if x is not equal to and value to 5. If we save and reload, we don't see the alert anymore. This is how we can use comparison operators, and they're really useful when combined with if statements. As we've just seen, is if statement will run if some code is true. But what if we want an alternative to run if some code is not true? For this, we need to add a second condition called else. Let's delete this example from before and create a new variable called hungry, and initially set this to be true. Then we can say if hungry, then inside the quotations we can alert, 'get some food!'. Just like that. If we just add the variable name like this, this will check if the variable is true. Then if it is, it will run some code. Let's save, refresh, and there's our text of get some food. However, if we wanted an alternative, we can also add else. The second block of code will run an alert if the condition is false. This time let's say, maybe later. If we change hungry to be false, this if statement is now false. Therefore, this code won't run. But instead the else statement will run alerting, maybe later. Let's try this in a browser. Refresh. There is our text of 'maybe later'. Let's try this once more by changing this back to true. Now we get, get some food. These if else statements really are a fundamental part of JavaScript and also programming in general. If you're still a little unsure, I would recommend going back through this video to better understand how they work. Although you will get lots more practice for this section. Next, we're going to take things even further by nesting these statements together. 7. Nesting if else statements: Let's head over to our starter files and into our nesting conditional statements section. Here in our last example was a simple if-else to check if the condition is true. So we check if the variable of "hungry" was set to true. If it was, we alerted the text on "Get some food". Otherwise, we'll get the text of "Maybe later". Sometimes we may want to check if more than one condition is true before running our code. For this, we can nest our if-else statements. To see this in action, I'm going to add a second variable. So let's add a second variable of "craving", and I want to set this to "Pizza". Then inside of this first "if" section, I'm going to nest in a second "if" statements. Let's make some space to make this more clear, so we'll say if "craving" is equal to "Pizza", then we can add our block of code to say alert, "Gimme pizza", and we can also remove this alert from here too. So first we check in if the condition is true by checking if the person is hungry. If it's true, it will then also do a second check to see if the craving is equal to pizza, and then it will say "Gimme pizza". Else, we'll get the text of "Maybe later". Let's save that and open this up in the browser and refresh and there's a text of "Gimme pizza". But what if the first condition was true, if hungry but you aren't craving pizza? So let's change this variable to something else, such as, "Chinese". Save that and then refresh. So we don't see any alerts. This is because although hungry is set to true, craving is no longer set to "pizza". Therefore, this alert won't run. For this case, we can also provide a "else" statement, which is also nested inside of here. So "else", and then inside this block, we can put a alert with the text of "Lets get some food". Remember if you wanted to add an apostrophe in like this, this single quotation is the same as the two outers, so we'd need to change this to be double quotations for this to work. Give that a save, and then if we go over to the browser and then reload, we get the text of, "Let's get some food". This is because this "if" statement is originally true, so therefore it will move on to the second one here. We're not craving pizza, so we don't get this alert here. Any overvalue will cause the "else" statement to run and then print out the text of, "Let's get some food", and as expected, if we change "hungry" to be false, this "if" statement won't run at all. Instead, the "else" statement will run and we'll get a text of "Maybe later". So this is how we can nest if-else statements inside of others. We can go even further and nest inside of this "if" statement too, but generally we don't want to go too deep because this makes our code more complex and unreadable, and there's often more elegant solutions to this. This is how we can nest our conditional statements, and next up we'll take a look at else-if. 8. Else if and logical operators: We've learned that if statements check if a condition is true, then else catches all of the cases. There is a first case we can use called else if. We use else if to check a new condition, if the first condition is false. We can use it like this. So inside of our nested if else statement, I'm going to add an else if statement. So just after this opening, set of curly bases, let's add else if, and then open and close a new set of curly braces, pushing the last else statement to the end. Inside of here, we can add some more brackets to check if a condition is true. So let's say if craving is equal to Chinese. So again, we're checking if the variable is equal to hungry. So let's set this to true. If it is, then moves onto this nested block here. So first of all, it checks if craving is equal to pizza, then it will run this alert here. If not, the second condition of else if, will then run, and this time we can do an alert. So let's say this time give me Chinese, just like that. If pizza or Chinese is not the value of craving, this else statement will run at the end, saying, "let's get some food." So save that. So now our craving is Chinese. We should now see the text of give me Chinese. Let's try a few more options. If we change this to pizza, we get pizza, and if we change this to be something different, let's say chicken, refresh. We have a fallback saying, "let's get some food." Also just to be clear, we have this else if block, nested inside these if statements. But it worked perfectly fine to if not nested. Before we finish off this video, I want to show you a few logical operators which you'll find useful. Logical operators may sound complex, but they are simply and or not. So let's comment out this example and take a look at these common sign all the code from before, leaving in the two variables. So let's say if hungry, then and with the two ampersands, craving is pizza. Then we can add our alert from before saying, "give me pizza." So now we'll check in if two statements are true. So we're checking if hungry is true and also if craving is equal to pizza. Let's change this to pizza and see what happens. Refresh. There is our alert. If we close this down and change either one of these to be false, we don't see the alert pop up. Let's try the other way around. Let's change this to be chicken. Again, both of these conditions need to be true for this code to run. If we only want one of these conditions to be true, so for example, if we're hungry or craving is on food, then we can run this code. So rather than both of these conditions needing to be true, we can run this code if only one evaluates the few. We can do this with the or operator, which is the two pipes, just like that. Now we only have one of these conditions evaluated to true, which is hungry. So save, refresh, and now the alert works. So if you look at and all, the last one I want to show you is the not operator. This is the exclamation mark which we looked at earlier. We looked at this using the if statement to check if something is not equal. So let's take this all section off, there and here, even hungry, then we can add an exclamation mark inside here. So if not hungry or if this means false, then we'll get the alert. So first of all, let's save and then refresh. We don't see anything. However, if we change this to be false and then run the code, we now see the alert. So this basically does the opposite, so here we're saying if not hungry, which is false, then run this code inside of here. So this is it now for if else and also else if along with logical operators. I hope that makes sense and not too overwhelming. Remember, a lot of this just takes practice, and we'll get a lot more as you progress through this course. 9. The ternary operator: Another type of conditional statement is called the ternary operator, so make sure you're in number seven, which is E ternary operator starter file. Then we can get to work in the script section below. The ternary operator is often used as a shorter alternative to the if else statements. It's also a one-line statement, so it can look a little simpler to. We begin by adding a condition we want to check, such as a calculation. We say ten is greater than five. The condition is then followed by the question mark, then we declare what we want to happen if the result is true or false. The first statement is true, separated by a colon, and the second one is false. What we're saying here is if ten is greater than five, the first one is printed text of true, the second one is simply printed text of false. If we save this in and open up this file in the browser, refresh, we don't see anything happen at first. This is because we need to output the answer, such as a console log. Before this lets add a console.log and then inside the bracket we can add this full ternary operator. Now if we save, refresh and then open up the console, click on the console tab, and then we've got the text of true, because ten is greater than five. If we change this to be ten is less than five, we then get the second option of false. Let's try this and that falls inside the browser. Later, we'll also look at some ways to display things on a web-page rather than in the console or using alerts. We can also stall this results in a variable too. Let's go back over and add our variable of hungry on small and search value of true. I should move this console log and then we can say, var, should I eat, then we can set this to our ternary operator. The condition we want to check is if hungry. If this value is true, where the question mark, and then add our two options. If it's true, we'll say, yes, let's eat, separated by a colon. If it's false, we'll say not just yet, add a semicolon at the end of there and then we can do a console log. Then log the results of should I eat. Just a recap, we check in this variable here, if it's true or false. If it's true, we'll print in the text of Yes, let's eat. If this were set to be false, we'll then get the second value of not just yet. This result is installed inside a variable called should I eat and this is a value which will display in, inside the console. After the console now, this is set to true, so we get, yes, let's eat. If this was false, not just yet. There is lots more uses for this tool, such as constructing a text string with outcome. If we were to go ahead and say variable is logged in, and we'll set this initially to be a value of false. Then we can go ahead and add a text string of hello with space and then inside the brackets we can add our ternary operator. First of all, we're going to check our condition of login, the question mark, and then our two options. First of all, if this is true, we can then say welcome back. Separated by a colon, we add our false condition. We can say please log into your account and a semicolon at the very end. Now we need a way to display this to the user so we can surround this whole section inside of an alert. Then the brackets are the very start and then it closes alert off right at the very end with a closing brackets. There we go. Let's make sure we have the two brackets at the end, one for the alert and the second one for this logged in section. Give that save, reload. First of all, we've got the text saying, "hello, please log into your account" because we're not logged in. However, if we set this to be a value of true, therefore we're logged in, reload and we'll get the message of Hello welcome back. This ternary operator is really simple to use and also a good alternative to the if-else statement. It's also a little bit more compact on McCann add this all on one line to not only shot in our code, but also make it more readable. 10. The switch statement: Welcome back. For this video, head over to section 8 of our starter files, which is for the switch statement. This is the final type of conditional statements which we're going to cover. In a way, switch does a similar job to the If/else statements, we've already looked at. But the difference is what it can check against as many conditions as we want. Then we add a break statement to break out with the switch once a match is found. Let's give this a try in our switch statement section of the starter code. Down in between this scripts. Let's begin again with the variable. I'm going to set this feed food. This can be any food we wants. Let's start with eggs. We then create a switch statement. The syntax is similar to the if statements. Inside of the brackets, we add the condition that we want to test against. We want to check the food variable. Inside the switch statement we can add various cases to check if they match this food variable. First of all, let's add a case. We'll say pizza. This checks if pizza matches this variable. If it does, we adds a colon and then we could declare on the next line what we want to do. Let's simply do a console.log. Then we'll say pizza is awesome. Just like that. Then we can add the break keywords. We add break to break out with the switch statements, if this is a match. If it's not, it then moves on to the next case. Let's add a new case here. Then we can check a second condition. Lets say eggs. If this is a match, we then want to do a console.log to display the message of, "Eggs are awesome." Then we're at the break keyword again just afterwards. Let's add one more case. This time we'll add bacon, colon and then a console.log. Lets say, "Bacon is awesome." Once more break out with the statements. That's our switch statements altogether there. Just a recap. We're creating a variable called eggs. We are then checking for matches inside a switch statements. If the case of pizza is a match, we then prints out the text our pizza is awesome. If it is, with then break out with a statement and we don't check any the extra cases below. If it's not a match, which isn't in this case, then it moves down to eggs and then displays the text of eggs are awesome. But this time because it's a match, we will break out of the switch statement. Therefore, it won't even check this next one. Let's give that save and reload the browser, open up the console, and now we'll go. Eggs is a match, therefore we get the text of eggs are awesome. What do we do if none of these cases are a match? For this, we add a default which acts as a fallback. Right at the very bottom, I'm going to add default. Then just after this we can add a console.log. Then for the text, let's say, "I love." Then add a space. Then we can add to the name of our food. With a semicolon at the end. Save that and then reload the browser. We still get a text of eggs are awesome because we have a match. However, if we go up and change this food to be anything else, such as cheese. Which won't match any of these three cases. Therefore, the default will kick in. Reload. There we'll go. We've got a text of, I love. Then we pass in the variable of food, which is cheese. Note in this default case we've left out break keyword, because it's at the end of the switch statement. We can add this default anywhere we want, but remember to also use a break if it's not at the very end. We can also change things around a little to. If we wanted to same outcome for a multiple cases, we can just combine them like this. Let's say after pizza, we can add a second case. Let's go for pasta, again with the colon afterwards. Now if the case of food matches pizza or pasta. We can then say, "I love Italian." So save. Let's keep this as cheese for now. We'll get the fall back and if we change this to be pasta. Reload. I love Italian. Then pizza and we still get, I love Italian. With switch statements we can also go on with as many cases as we want. Now it's time to move on to building a little game to put the things we've learned in this section into practice. 11. Time to practice: The dragon slayer game: We're now going to take a little time out from learning about conditional statements to put them into practice in a fun game called, the dragon slayer. They will be pretty simple but it will get us thinking about what we want to do next, based on the condition. When we first finish the page and this is the finished projects, we first asked our name. We can then enter our name and then click okay. Then we'll move on to our next screen where we're asked if we would like to play with our name inside the string. If we cancel, we get a textile, maybe next time. However, if we reload the game at our name, click okay, and then we say, would you like to play and click on okay. We then move on to being asked if who'd like to bow the dragon. Again if we cancel, we'll get a message of come back when you brave enough. However, if we go through and play the game at our name, would you like to play? Yes. Would you like to battle a dragon? Click okay. We then have a random chance of where will be the dragon. This time we've defeated the dragon because we compare this to a random number which determines if we win or loose. There's a 50-50 chance, what this message will be. Let's give this one more go. If we refresh at our name and then click through, this time it says we've lost. You can give this a go if you feel comfortable doing so, and I would really encourage you to do this, if not just to get some more practice. The only thing we have not yet covered is generating random numbers, but you can easily look the slope if you want to. Otherwise, I'm going to go ahead and build this now. Let's close this off, and then go to the starter files for the dragon slayer game. Down in the script, I'm going to begin by creating a variable called random, and this is only section which we haven't yet covered. To generate a random number, we use math dot random, and then the brackets just like this, and then let's do a console log for the word random. Save and then reload, and in fact is when you go to our project, open up the console, and there's our random number. If we keep refreshing, we get different values each time. A random number in java script by default is between zero or one. Zero being included, but one not been included, so this will end up with the highest value of 0.999. If you keep refreshing, we don't see any values higher than one. To make this easy for us, we're going to generate a random number between zero and 99. To do this, we can first multiply the random number by 100, and this will give us a number if we refresh, which is between zero and 99, but with lots of different decimal places. If we want this to be a whole number, we can either round this number up or down. We can run the number down with math dot floor, or if we want to round the number up, we can say math dot ceil, which is short for ceiling, and then surrounds the rest of our code inside the brackets. Now if we save, and then reload, we get a random number which is rounded. Now we've taken care of this random number, and the way we're going to use this is we're going to check, if this number is less than 50, if it is, we'll say you defeated the dragon, if the random number is over 50, will say you've lost. Let's get back to work with this game. We can remove the console.log, and then we are going to set a second variable of name, and this name is going to be the value passed in by the user inside of a prompts. What is your name? This will add a prompt to the user asking for the name which we can type in, and this value is stored inside this variable. Next often want to create a new variable called play, and this is for our second screen, which is going to be a confirm. Inside the confirm we can say hello, add a space and then add the user's name. This is a screen which you seen inside the final version. First of all, we get what's your name? When you type in your name, we can say, okay, and this section here is the one which restoring inside a play. So hello name, and then the text string of, would you like to play?; Now we need to do some conditional checks. First of all, we're going to check if the user has selected play. If play is true, then we want to run some code. If the user has chosen to play the game, would then want to create a new confirm, and this time we're going to ask the question of, would you like to battle a dragon?; If we go to the finished version, just here, let's reload, what's your name? Then we have the section would you like to play? If okay, this is a section which you just created saying, would you like to battle a dragon? We need to store this inside a variable. I'm going to call mine battle, and change them. Now we have a true or false value inside this variable called battle. If the user wants to go ahead and play, we can then create a new if statements, and this time nested inside a play. We'll say if battle is true, then inside here we want a battle, or if the users clicked on cancel battle will be false, and then we need to provide else statements, so we'll say not battling. First of all, let's deal with the else statement. If the user has chose not to battle, will simply do an alert, and so alert can say 'comeback when you are brave enough'. Let's first give us a test in the browser or to our projects. Let's refresh. What's your name? Type this in and we'll say, 'hello Chris, would you like to play?' This is this section here, saying would you like to play? If play is true, we then asked, 'would you like to ball the dragon', which you see here? Remember we've not set a condition, if this is true yet, we've only set condition if the user clicks cancel. If the user cancels, we should get this message here. Let's try this, and there we get 'come back when you brave enough'. Now we need to handle the condition, if the user clicks on "okay". Let's add a condition is the user decides to battle. Before we set up these random number between zero and 99, and stored it in a variable called random, each time we run a random, we can then use the ternary operator to check if this is greater than 50, if it is, we can then say, 'you defeated the dragon!; 'if this number is less than 50'. We can then say you lost. Save that, and let's give this a go. Type anything into there, 'would like to play'? Yes. 'Would you like to battle?' Okay, and we don't see any results on the screen. This is because we've created our ternary operator but, we've not displayed the results on the screen. Let's set the result to be a variable called results, and set this to our ternary operator. Then just after this, we can do a console.log with the value of results, and in fact we'll change this be an alert just like the rest. Save, and then over to the browser, 'what's your name?'.' Would like to play?'Yes, 'would like to battle?' Okay. So we lost that time, let's try again. 'Would you like to play?' Yes, and this time we defeated the dragon, because the random number must be in over 50, good. Those who've handled most of the used cases here, is the used ones to play, is the used ones to battle. The last case to handle, is if the user doesn't want to play at all. If we refresh the browser, this time if we type our name in, and click on okay. We then want to handle the case if the user doesn't want to play, currently inside the here we're checking if the user wants to play, and if they do, we then run this code. Instead, if the user clicks on cancel, would then want to alert message saying 'maybe next time'. We can do this as an else statements at the very bottom, so else, we'll do an alert of 'maybe next time'. Save that and give us a go. 'What's your name?' Click okay. 'Would you like to play?' This time we'll click cancel, and the message of maybe next time. Great everything is now working, and hope you enjoy playing this game. Don't worry if it was something which you couldn't quite manage, there's quite a lot taken there and each step just take a little bit of thinking about to decide what we're going to do next. Hoping all are looking forward to the next section and I'll see you there. 12. DOM Manipulation: Welcome back. This video is where JavaScript begins to get really interesting by manipulating the DOM. The DOM stands for the Document Object Model and is a tree-like representation of our web documents. It is an interface to allow programming languages to access and update the content and structure. Here we see the same structure as our web pages. From the top, we have the document. Inside there is a root HTML element. Under this we have the familiar head and body. Then followed by our elements, texts and attributes, for example. The great thing about it is that it can connect two languages, such as JavaScript, so we can change things. This opens up many possibilities, such as the ability to access elements, to change the content, add attributes and styles, or even create and delete elements too. It may sound complex, but it is pretty easy to get started with. One of the easiest ways of manipulating the DOM is to grab an element on our page and change it. For example selecting the p elements and then changing the text. Let's head over to our JavaScript starter and open up the DOM manipulation section. Let's head over to our JavaScript starter files and go to our number 10, which is DOM manipulation. Inside here we first need some HTML to go ahead and change. Inside the body let's open and close the p elements and then add some text inside of hello. Then we'll open up the span elements and then add the text of user. This will display on the screen the text of hello user. We then need to add an ID to this span element, so we can grab it using JavaScript. Let's call this ID the username. Now if we scroll down to our script section, which is just below here, we can start with what is called, get element by ID. This is pre self-descriptive, this grabs an element by the ID, such as username. First we grab the document. This is the document object, which is basically our web page. Remember, the DOM stands for Document Object Model. Our tree-like structure is a model of our web page. Then after selecting this documents, we can then narrow this down. In this case, we're going to select an ID on the document, we'll get elements by ID. Inside the brackets we can then add the name of the ID which we would select. In our case it is username. Add a semicolon at the end. Notice when typing get elements by ID, we have an uppercase letter for every word after get. This is referred to as camel casing and it makes it more readable because we can better see the start of each word. If we save that and go over to the browser, we see that nothing will change. This is because we've selected the element we want, but we've not yet done anything with it. We can change the contents by setting the inner HTML. Just before the semicolon, we add a.innerHTML. Now we can set this to be a value such as a string. Let's say Chris, hold to the browser, reload and now we see the text of, hello Chris. As well as using a text string for our innerHTML, we can also use a variable too. Select set a variable for our name. Var name equals a string of Chris. Then rather than our string just here, we can pass in our variable name of the browser and reload and we still see that our text of, hello Chris, is now on the screen, but this time using a variable. We can also change the style too by changing any of the CSS values. Just below this, we can access the same elements, with document.getElementByID. Again, we want to select the username, the capital N for name and then instead of selecting the inner HTML, this time we can set the style and let's say the dark color to be equal to a value of red. This will change the text color of our text inside of the span. Save, refresh and there's our red color for the word Chris. We can use any CSS property we want inside it here. The only difference is we need to camel case any CSS properties which have multiple words, such as background color and font size. Over in CSS, we would normally do something like this. Would say font size using a hyphen or a dash but instead, when using JavaScript, we need to refer to this camel casing, which we see just here. Rather than a dash, we use a capital letter, such as this. Then let's set the text to be a value of 24 pixels. Let's see this in the browser and there we go. Now our text of Chris is a larger font. We can also use a class in place of this ID. Let's go up to our p element and then add a class of, hello. Then we can use document.getElementByClassName. Let's add a new section of getElementByClassName. This works in a similar way to above. First we select the document and then narrow it down by using the class name. Get elements by class name. Pass in the name of our class, which was hello, which matches this section just here. Then a semicolon at the end. Notice here when using the class name, we add an s onto the end of elements. This is because we may have multiple classes on our page. For example, we could have a second set of p elements. If we go ahead and add a second set just here, and then add the same class of hello. Now we'll add some text of welcome back. Now if we had more than one class selected, like we do just here, how do I know which one we're changing? Well, let's assign this to a variable and then display it to the console. Let's say variable of test equals our first class. Then into a console log inside the browser with the value of test. Over to the browser, right-click and inspect. Inside of the console we see a HTML collection with two items inside the brackets. This is like an array which we'll cover soon. These two items, our two elements with the class of hello. If you click on this arrow here, we can also open this up and find out more about the contents. We see the first p elements with the class of hello has a index position of zero. Then our second one has an index position of one. We can access these two elements by these index position. Inside the console, if we say test, which is the name of our variable and then inside the square brackets, we can access each of these elements by the index number. Beginning with zero, hit Enter, and there's our first p elements, which contains our texts of hello Chris. Then we can access our second value with test1, hit Enter. This is our second element with the text of welcome back. This position number can also be used inside of our selector. Over in our code, we're going to grab all the elements with the class name of hello. Then inside the square brackets, we can narrow this down to our first one, which is position zero. We can do anything which we've previously seen. Chart set in the style.color to be a value of purple. Save and then reload. So first element is now purple. And of course we can change this to be one, and this will now make the welcome buck text purple instead. Next we have getElementsByTagName. As the name suggests, we can select all the elements on a page by the tag, such as our p element for text or IMG for the image tag. Down at the very bottom, let's add a comment of getElementsByTagName. Again, this has a S2 because you can select more than one element. After here we use the document.getElementsByTagName, which is just here, the brackets and then inside the quotations we can add the elements we want to select, let's crop all p elements, and once more, because we have more than one set of p elements, we need to grab these by the index number. The first one is position zero, we can set the inner HTML and let's set this string value of changed. If we save that and then reload, we've now changed our p elements at index position zero. The next tool we're going to look at based on the querySelector. This is just like the selector we use in CSS. Let's see this with an empty image, so up to the HTML after our two p elements, let's add the IMG elements. If we give that save, that was the browser, you see we don't see any image on the screen because we have not yet set a source attributes. Let's add the source attributes using JavaScript. First, we can grab this image using querySelector, so a comment of querySelector. Then we use document.querySelector and then pass in the name of IMG. This is the same way as we would select our image in CSS. We can also select it with the ID and class name to, and we'll take a look at that in just a moment. Using querySelector, we still have access to the inner HTML and also adding styles too. But for this example, I'm going to show you something new, and this is how to add an attribute. The attribute we're going to add is the image source and we do this by using.setAttribute, inside the brackets, we go ahead and add two values. First is the name of the attribute we want to add, which is source, and then separated by a comma, and then the name of image dot.JPEG, you can use any image of your choice. But I've added an image into the starter file, which is just here. I'll close this down, give that save, and then reload the browser. There's an image which is now on the screen. If we open up the developer tools with right-click and inspect and then go to elements. We can see inside of the developer tools, we have our body section, we have our p with the text of changed, our second p element, we welcome back, and also our image with the source of image.JPEG. The end result is exactly the same as if we would type this in HTML, but we've added this by using JavaScript. We mentioned that when using queryselector, we can select any element in the same way as we normally would in CSS. As well as the tag name such as image, we can also select this image with a class or ID. If we add an ID to this image of image and then scroll down, just like when using CSS, we need to use the hash as the selector and then the ID name, now save and then reload. We can see this still works, but this time using the ID. The same for the class, it will change the image tab, a class of image. This time just like when selecting this in CSS, we need to use a dot as a prefix, and this should still work inside the browser. Finally, something similar to this is querySelectorAll; querySelector which we've just looked at, only selects the first matching elements on the page, querySelectorAll on the other hand will return a list of all the matching elements. We can see this by adding a second image into our HTML. Copy this section here and paste it in below using the same class name. If we save that and then refresh, we still see this only one image on the screen this is because querySelector will only select the first elements on the page. However, if we go ahead and add querySelectorAll which looks like this and then do document.querySelectorAll, this will go ahead and return a list of both of our images. First let's tag the class of image, and then after this we add the square brackets, then we can pass in our index number. Just like before, the index number of zero is the first image on our page. If I could just comment out this querySelector. Now we've selected our first image, we can then use setAttributes like we just looked at, then pass now first value which is the source, and the second one which is image.JPEG so this will select the first value, even as with one image on the screen. However, if we want to add the image in twice, we could copy this line of code here, and then paste it in one more time. But this time, select the index value of one and now we have two images on the screen. Selecting two elements like this would be better done with the loop, but we'll get into loops soon in this course. Understanding how to manipulate the DOM is something really important to know, and this is where JavaScript really begins to get interesting. Now we know how to select elements, it's now time to move on. Next we'll be learning all about how to add and remove elements using JavaScript. 13. Adding and removing elements with Javascript: We have just looked at how we can use JavaScript to manipulate elements in our DOM, such as changing the text, adding attributes, and setting styles. We're going to cover how to actually create new elements, and also how to remove them too. Let's head over to our starter files. We're going to begin in number 11, which is adding and removing elements with JavaScript and also have this open inside the browser. We can see in our starter files we have an unordered list, with the two ListItems of apples and pears, which we have just here. Let's begin down in the script section. We're going to look at what is called a document.write. Document.write is a way of setting a text string to a page. Document.write, and then inside of the brackets we can add a text string, such as document write text. If we save that and reload the browser, we now have this text appearing alongside our unordered list. Document.write is for adding a simple text string to a page. This is commonly used for testing purposes, but it can cause problems if used incorrectly. For example, if you go to google.com, and then open up the Console, you right-click and Inspect. Inside here if we do a document.write, and then pass in a text string, such as hello, hit Enter, and we see the Google homepage has been replaced with our document write. A document write will override all of the existing content, if the page is already loaded. We need to be really careful when using this. You'll see at the top of the start template, we have our unordered list, which is just here. This is a list we can work with by adding and removing some ListItems, using JavaScript. If we want to create a new element on the page using JavaScript, we can use the createElement method. Let's remove this document.write, and then inside here we can do the document.createElement. Let's create a variable to store the scene called ListItem, and set this to document.createElement. Just like this. Again, using the camel casing, just like we've seen before. Inside the parentheses, we can pass in as a string, the name of the elements we want to create, such as a ListItem. Any element tag name can be added to, such as a div or p element. Creating this won't do anything on its own, because although we've created it, there is still no text inside the elements. We can add text using the CreateText.Method. Let's just add some comments, create element. Then after here we're going to create the TextNode. We can also store this inside of a variable called itemText. This equal to document.createTextNode. Then inside the bracket, you can pass in the text string we want to add. Sticking with the fruits, I'm going to add the value of bananas. If we save that and then reload the browser, I go to our index page, we still don't see any extra items on the screen, because although we have our elements which we created here, and also our text which we have here, we have not yet added this text to the contents of these elements. We can do this with the appendChild method. Let's add text to element. First of all, let's grab our ListItem, which is just here. We say ListItem.appendChild. The child we want to append is this item text just here. Add these inside the bracket and then save, and then reload. We still don't see the elements on the screen. Let's see what's going on with the console log. That's console log, the value of our ListItem. Over to the console, right-click Inspect. We see that we have our element created. We've got our opening and closing ListItem, and then the text of bananas as the child. The final step is to again use appendChild, to add this new item to this existing list, which is just here. This existing list has an ID of list. First let's grab this and store it inside a variable. Down at the bottom, let's select the parent list. Install this inside a variable called list. We know how to do this, it's document.getElementById. The Id we gave this is List. Then we shall add a semicolon at the end, to store this inside this variable. we have the parent list, and we have the child we want to add. We can go ahead and add these now. Add new ListItem to list. We do this, we list.appendChild, which we've seen before, and the item we want to add is the ListItem. Add a semicolon at the end. We load the browser and there we go, there is our bananas as a new ListItem. Just to recap what we're doing here, we're grabbing the full list, and storing it inside a variable. We then add in to this list, the child, which is this new ListItem. You may be wondering why do all of this, instead of just typing in a new ListItem look inside the HTML. Well, there is a lot of cases where we want to do this with JavaScript. In a to do app for example, each time the user types in a new to do item, this could be added to the list, just like we've done here. Or for example, in another course which I have, we build a music player application, where we construct a list of songs. Moving on, as well as adding items to our list, we can also replace any existing items which we already have. For example, if we wanted to replace these pears ListItem, with something else, we could also do this too. First, let's create a new ListItem called grapes. So let's create grapes ListItem. We do this just like before, we can create a new variable called new ListItem, and then set this to be document.createElement, the element we want to create is a ListItem. Then just like we've seen before, we can also create our TextNode. Let's say newItemText. This is just exactly the same as what we did before, when we created a ListItem. Then our TextNode, bananas. But this time we're going to be creating grapes. This is equal to document.createTextNode, text of grapes, semicolon at the end. Then we need to add this text to this item. We say newListItem and then append the child of new item text. Just like that. I've got a newListItem here, which we access in here. We'll then add in the child, which is a new item text, which is the TextNode of grapes. we have this newListItem. We can use this to replace any of the ListItems we already have. As we mentioned before, I want to be selecting pears, which is the index position of one. Down at the bottom, let's create a variable called item to replace, and then document.querySelectorAll. We're going to grab the ListItems. Then the item we want is our index position 1. we have our item that we want to add in and also the item we want to replace. We can now go ahead and use replace child to complete this. Just after here, let's select our list.replaceChild. ReplaceChild takes in two values, the first one is going to be our new ListItem, which is a new item. Then separated by a comma, we add in the item we want to replace, which we stored in this variable here. Add the same as our second value, save that, and then reload. Good to know our second item is now grapes, rather than what we had originally, which is pears. Finally, if we wanted to completely remove an element, rather than replace it with something else, we can also use the removeChild method. This is pretty straightforward to do. Let's go back into our script. Let's say, remove an item. Let's grab our list. Then we use.removeChild. Inside the brackets, all we need to do is add the child we want to remove. If we wanted to remove our grapes, which is stored in newListItem, we just add this in as a value, save, and then reload. The value of grapes has been removed from our list. When removing these items, we always need to specify the pattern first, which is our list here. Then remove one of the child items, just like this, rather than accessing the elements to remove directly. We now know how to add, remove, and update elements using JavaScript. Now let's move on to the next video. 14. Time to practice: adding elements with Javascript: We've covered some ways to add, update, and remove elements from the DOM. The best way for all this to stick is to get some practice on your own without following along with me. In this challenge, I would like you to go ahead and create some elements using JavaScript. It doesn't need to be too complex. Just something like you see here is fine. With some text at the top of the page followed by an image. These can be placed inside a container and then add to the image and the text as child items. Also, you will need to add the image sauce and all the attributes to using Java Scripts. Recovered has to do this in a DOM manipulation video. If you go over to the starter file on the Number 12, time to practice. Inside here you'll find some basic code to get you started. All we need to do is create a JavaScript version of this HTML code we see here. Good luck with this. Once you are done, we'll move on to JavaScript functions. 15. Javascript functions: We're now going to look at using JavaScript functions. Functions are really important and they assume FIN, which you use a lot when working with JavaScript or programming in general. A function is a block or a snippet of code, which we can call when required. You can think of it as a task or a set of tasks which are contained inside this function. We can then call this function each time we want to run the code within. These functions are also reusable. We have some code you want to repeat multiple times, we can package a code into a function. Let's get started of in our functions starter file, which you've opened up the sidebar is number 13. Then down to our scripts we have empty script to get started with. We define a function with the function keyword, followed by the name we want to give it, such as hi. This name is completely up to us, but try to choose something descriptive. Then we add to the brackets afterwards, which are also known as parentheses. Then we add a set of curly braces afterwards, and I want to hit enter. Then within these curly braces, we can add the code which you want to run, one we call a function. For a simple example, we can just add alert. Then inside of here, just some text off hi from function. We can add as many lines of code as we want inside this function, although it's often good to not overload the function and just keep it to warn related task. This section here won't do anything as of yet, as we've only declared this function. This is why it's sometimes referred to as a function declaration, or a function definition. To actually run this code, we want to call this by the function name of hi, followed by the parentheses and the semicolon. This is often called invoking a function. Now if we save and then open this in the browser, we now get our code run from inside, which is our alert of hi from function. We can also call this function as many times as we want by repeating the same function code. If we copy this and paste it in below, we should now see the alert problem twice. Says our first one, click okay, and then our second alert just afterwards. This function can contain any codes which we like. If we went up to the top and added a empty div. All the fact will go for the p elements and we'll keep this empty, first add an id of texts. We could use this function to go ahead and change the inner HTML of our text elements here. Down inside the function body, we know how to do this with a document dot get element by id. The id is text, which we have here. Then we can set the inner HTML of all p elements to be a text string of texts from function with a semicolon at the end. Now if we remove one of these function calls, save, and then over in the browser we get our alert, and then our text from function. This type of function is called a name function, simply because we add a name just like we have done here. There is also an anonymous function too. This is where we don't give the functional name, instead we can assign this function to a variable. We can remove the name and just keeping these parentheses just after the function, and then we can add a variable. Let's call this the anonymous function, and set the value equal to this function here. We can then call it by its name of anonymous function, so replace hi with this, followed by the parentheses, reload and their is our alert and also the texts from function is still working. Both ways will do a similar thing by running the code inside of these braces just here. There is a difference though, and we'll look at what this is seen when we look at hoisting but for now let's move on to the next video, a look at function arguments. 16. Function arguments: If we head over to the start file for this video, which is function arguments, inside here we have our p elements from the last video, with the idea of text. Then a simple named function, which is going to set the inner HTML, to be textual function. So in the last video, we've seen some basic function uses. But functions can become even more useful, if we pass in some data. We can pass in this data when calling the function, by adding some values, inside of these brackets here. These values are passed to the function are called arguments, so if we wants to pass in a name, we could do it just like this. Now the function has access to these arguments, by passing the name we want to reference it by, inside of these function parenthesis. So that's add Name inside a here, and this name here, acts like a variable. We can references inside the function, the name give this data inside is a here is called a parameter. Now we can use this name inside of our function, in any way which you choose. So for example, we can use it to set the inner HTML rather than texts from function, I should say hi, and then other variable name at the end. If we save that, we now have the value of hi Chris, and Chris been the arguments which are passed in. We can pass in multiple arguments too, for example, if the job of this function was to do a calculation, such as multiplying two numbers. Let's change this to be multiply, and also the function call. Let's say we wanted to pass in two numbers, rather than a string. Let's go for 23, and 15. We can then name our parameters inside here. Let's go for number one, and number two. Then we can update our p elements here, with the values of number 1 multiplied by number 2. So give that a save, and then out to the browser. We now get the value of 345. If we were to make a mistake, such as only passing in one of these arguments, let's say 23, reload. We get the value of not a number, because the function is still trying to multiply our two values together. However, if we only pass in one value, and we only need one value inside here, reload, we still get the value of 23. However though we don't have our second value passed in, which is number 2. So instead if whose output, the value of number 2, save this, reload, we'll get the value of undefined. So it won't cause any major problems, such as our website crushing. It just means a function can't do its job without all the data in which needs. Alternatively, we can also use the return keyword, to return the value after the calculation. This may be useful if you want to store a value, for example, in a variable, for future use. So first, let's go back over to our function, and add in our second arguments. Then instead of updating the DOM without get element ById, wouldn't comment this out. Instead we can return the calculation of number 1 multiplied by number 2 semicolon at the end. Now if we give that a save and then reload the browser, we see the DOM has not been updated. Instead now this value is being returned. We can store it inside a variable for future use. We can do this down at the bottom, by art in a variable called sum, and certainly is to our function call. Then we can check this is working, by doing a console log, and login the value of some, add variable of sum inside here, open up the console and there's our return value of 345. Now have this stored inside available, and it's now up to us what we want to do, which is return value. Adding arguments is a great way to extend the capability of a function. Next up, we will look at two important JavaScript concepts called Scope and hoisting. 17. Scope and hoisting: We're going to now look at two important things to understand when using JavaScript, and this is called scope and hoisting. Begin with scope and allow this relates to our variables. We now looking at these terms because they have a lot to do with function's. Scope basically determines where we have access to our variables. First, let's go to our starter project and into the scope and hoisting section. Down in here we have a multiply function, which we seen before. Multiplying the values in number one and number two. Also just like the last video, we have our empty p elements to display the results in the browser. So this time rather than passing number one and number two as argument to the function, we can go ahead and declare these variables. Let's say var num one is equal to five, and then var num two is equal to 10, if we save that. Now these two values should be multiplied, which we have here and then displayed in our p elements. Reload. There's our value of 50 on the screen. This is working okay because the variables which we declared have been declared outside a dysfunction body. This means these variables are global, all have global scope. Global variables can be accessed anywhere in our code. For example, our variable is being accessed here inside of the function. But we can also access it outside of the function too which we could see with a console log. They were console log outside the function body the value of one of these variables. Save that and then reload. We ca see that not only do you have access to the variables inside the function, we can also access these outside the function too, which we say here with the console log. However, if we grab these two variables here and then cut them out, and then instead paste them inside of our function body. Gives us save, reload. So we now see that our variables can be accessed inside the function. But we see our console log is thrown and error. This is because we've moved these two variables in side of this function body. This means they now have local scope rather than global. Local scope means these variables can only be accessed locally inside the function which there were declared. This is why I will get element by ID is updating. Both our console log, which is outside the function, is now thrown and error. We can prove this by moving this console log to be inside of the function. Let's move this inside of the curly braces of the function. Then over to the browser. Now the console log also has access to this local variables too. So this is how scope works, it's all about where we declare all variables. So remember, declaring them outside of a function will mean they are global and can be accessed anywhere. Variables declared inside a function only have local scope and can only be accessed within the function. Next we have another one of these words which you will hear about called hoisting. Hoisting basically means that JavaScript will move or hoist your variables and functions to the top of the current scope. They're not physically moved to the top, though it's actually stored in memory, so that can be used at anytime in the script. This causes some behavior which we may not expect. Let's go to our example from before and take a look at this in more detail. So over to our function. So first of all, we declare our function just here and then below this will go ahead and call our function to run it. We would expect this function to work because the browser knows we declared this function first and then it called the below. Our code is read from top to bottom. But what if we called the function first before we declared it. So if a mood multiply, should open the top, therefore calling the function before we actually declare it. Let's save that and see what happens. We still see things working because as we said before, functions are variables stored in memory. So when this function is called just here, the browser or the interpreter already knows it exists. When we looked at functions a few videos ago, we looked at two different types. These type which you see here, which is a named function, and also an anonymous function which does not have a name. Remember, it looks like this. So if we remove the name and then install it inside a variable called anonymous function and set this equal to all function just here. If we call this function down at the bottom. So change multiplied to be anonymous function. Then move this down to the bottom. Save and then reload. We see that everything still works perfectly fine. We also mentioned when looking at anonymous functions a few videos ago, that there is a difference between anonymous functions and named functions. While the difference weird anonymous functions is when called in first, it will result in an error. So if move this anonymous function call back up to the top of the browser and reload. We now see an error in the console and niche is no longer working. So this is a difference between the two function types. Anonymous functions are not hoisted, or stored in memory, but they are named function declarations, which we seen first hoisted. Hoisting also happens with variables too. Let's take a look at this, if we comment out this function, remembering Visual Studio code, this is command or control with a forward slash. Then if we declare a variable of x to be 10. Then the second variable of y to be equal to five. Then let's alert these two values of x and y. So let's add x and y and separate these with a string. Let's that's add a pipe symbol inside here. If we save that and then reload the browser, we now get our alert of 10 and then five. So this is the behavior which we would expect. We've declared a variable of x and y, and then alerted these to the screen. So this is all expected behavior. But what would happen instead if we moved the alert above our variable of y, let's save this and check this out on the browser. Reload, and we'll get the value of 10, then y is undefined. So we said before the variables are hoisted. So we would expect the values of x and y are both stored in memory and available when we call this alert. But this is not happening. So there is one thing to be aware of though. Although these variables are stored in memory, only the decoration, such as the variable of x and the variable y, is stored in memory rather than the actual value which we assigned to it of five and also 10. So to see this more clearly, let's go into our example. This first variable is the initialization, this means we declare a variable of x and assign the value of 10 to this variable. A declaration, on the other hand, is when we just declare a variable name without assigning a value, such as this here so this is the declaration. So now we know the difference between the initialization and the declaration. Why would this matter to our code? Well, when any of these variables are hoisted, even the ones where we set an initial value like this, only the declaration is stored in memory. This is why our variable of y, which will have here, is shown up as undefined. The variable of y is actually hoisted or stored in memory. So the browser is aware they exists, but it's not aware of the initial value which we set to five. Hence why we get the value of undefined. So this may all seem a little complex if this is new to you, but this is how the code is read. So it's really important to understand to avoid any bugs or expected behavior. One of the things to take away from this is to always declare your variables at the top of the scope. Meaning if the variables are local, which we had inside the function here, place them at the top of the function body, or if we want our variables to be global, we should set them at the top of our scripts. So let's move our x and y right up to the top of the scripts, let's add this above our alerts from before. We can also set this to be our value of five, gives us save and refresh. Now we don't have a problem because our variables are now set at the top of the current scope. So should even set these at the very top or at least above the code which you going to access them in our case, the alert. This will ensure our code is wrote in a similar way in which it's read and possibly avoiding any unexpected behavior. 18. Arrow functions: Like most programming languages, JavaScript evolves over time, and this can change or add new features and syntax. JavaScript is based on a scripting language called ECMA Scripts, which aims to standardize the implementation of JavaScript. This is why you will often hear versions of JavaScript being referred to as things such as ES5, ES6 or ES7, for example. ES5 or ECMA script version five is a version which is currently fully implemented in all browsers without the need for any tools. To confuse things even further, you will also hear them referred to as the year of each release. ES6 came out in 2015, so you may also hear this called ES 2015. As we go through this course, we'll use modern features or syntax from the ES6 specification and above. This just means a more modern way of writing JavaScript or a newer feature. Starting, in this video we will look at the ES6 arrow function. An arrow function is a way of writing a function, which you've already seen, but with a shorter, cleaner syntax. If we go to the starter files into the arrow functions section, if we scroll down, we'll see the values of number one and number two multiplied inside of an anonymous function, which we see just here. An ES6 arrow function allows us to run the same code inside of these curly braces, but using a shorter syntax. So we can still keep our variable of anonymous function, but rather than having the word function, we can just use the parentheses like this, and then the equals and greater than symbol, and all the rest of the code inside the curly braces just stays the same. If we save this and then reload, we still see the value of 50 in the browser. You may often hear this called a fat arrow function too, because of how the syntax looks with this equal symbol and the right angle brackets. These brackets or parentheses which we have here, can still take in any parameters and arguments, like we've already seen. So if we delete our two variables up here and instead pass these in as arguments. So let's add an num, one, and then num, two. We can then pass in these values as arguments when we call the function. So 5 and 10, save, and then over to the browser. This still works exactly the same as before. If we do only have one argument to pass in, we can show on this syntax even further by completely removing the parentheses. So if we only wanted to pass in one number, such as five, two of our second parameter here. We can also remove the brackets or the parentheses and just leave our parameter name inside of here and then to avoid any errors, we'll just remove this number two from here, reload the browser, and now we'll get the value of five. So this is now a shorter, cleaner syntax, and this is how we'll write functions for a lot of the rest of the code during this course. So this is all great and working fine now, and this is how we can use an ES6 arrow function. 19. Javascript events: Now it's time to look at another important part of building websites, and this is JavaScript events. Events are triggered in many ways, when a button is clicked, this can trigger an event, when a mouse hovers over an elements, this can trigger an event too, even when the page first loads, this can trigger an onload event. We can then decide what we want to do when these events happens. For example, we could run a function when a button is clicked, or we could change the color of an element when a mouse hovers over it. Here on the W3 Schools website under the HTML DOM events, there's a huge list of events we can listen for, if we were to scroll down. First of all, we have the mouse events, so we have onclick, we have ondouble-click, onmouseleave, onmouseenter, onmouseover, out, and up. Further down we also have keyboard events which are triggered when various keys are pressed. For example, we can trigger an event when the keyboard button is pressed up or down and there's pretty much every kind of event to cover us for pretty much anything which can happen on a web page, including forms here, we can decide what we want to do with things such as onchange, onsearch, or onsubmit, which is what to do when the form has been submitted. There's also drag events, clipboard events, and so many more. We're going to be using some of these during this video and this gives us so many options which we can respond to inside of our code. If we head over to the starter files, we can go ahead and take a look at some examples. Go over to the JavaScript events file, and then let's get started inside of our example. Here we have some simple text inside of a P element and then inside the script, we've got a arrow function. Inside here, we just changed the style of the font size to be 34 pixels and then run this function. We'll go to the browser and reload. This is the text which we have after the style has been applied. Currently we're calling our function inside of the script, which is just here. If you wanted this function to only run when something happens, such as a user moving the mouse over the text, we can add this function called into an event. Inside the P element just here inside the open inside we're going to add onmouseover, and this is the name of one of the events which we've seen before and then we can set this equal to the name of our function, which is changeFontSize and then add the premises just afterwards. This will then run this function every time the mouse is over this text. Then let's comment out this function call right to the bottom, save and then over to the browser, stares our standard size text and now if you hover over with the mouse, we now see the text has been increased to 34 pixels. We can choose any event we want to trigger this function such as onclick. Let's change onmouseover to be onclick, reload the browser, and then if you click the text, the function is now called. Things such as onclick and mouse events are really common and we'll see them a lot. There is also some uncommon ones which you can see from the list before, such as if the user tries to copy something from the page. Let's add oncopy, and then we can comment this out, and then do something to show us an alert, and a message of stop copying my stuff, just like that and then save. Now if we right-click and then copy, we now see the message appearing on the screen. Slash remove this alert from here and reinstate this. We can even run some code when the page has finished loading with onload. We can do this inside of the body. Let's go inside the opening tag and then add onload. here rather than calling the function, I'm just going to apply some JavaScript to run. Let's copy this document.getElementById, just up to there and then we can paste in our JavaScript inside the quotations. We're grabbing this text element. Then let's change the inner HTML to be our text string of changed. Now we save that. Now as soon as the page has loaded, this will override the text to be changed. This method of handling events within a HTML elements, like we've done with these two examples, is called inline event handlers, although this code will work, it is considered bad practice to do things like this. It is better to keep the HTML and JavaScript separate, even placing the JavaScript into a separate file and this is what we'll look at soon in this course. let's go ahead and remove the event handlers from the HTML. First, the ones from the body section, especially everything from inside here and also the oncopy one from here, then we can get to work moving all these into our scripts section. Let's start by accessing all P elements here and store it inside a variable. Let's say, var textElement and set is to, document.querySelector. I'm going to select our P elements with the P tag. We can then attach an event listener to this text element. Add, texteElement and then.addEventListener. Inside the brackets, this event listener takes in two values. First is the type of events we want to listen for. Let's say click. This name is generally like the ones we've looked at before without the word on before it, so rather than onclick, which we used before, we just use click. Also onmouseover would just be mouseover. The second value or the second parameter separated by comma, is the function which we want to run. Let's add our anonymous function into here, the parentheses and then open and close the curly braces. Put a semicolon at the end. Inside this function body, we can then run some code. Let's copy this section from before and in fact, we can remove this function, we don't need this anymore. Let's remove all this. Then inside this anonymous function we can then paste this in, and remember this is the one which changes the font size to be 34 pixels. Give that a save and then reload, there's our text. Once we click this, it now increases to 34 pixels. remember this is an anonymous function because we cannot give this function a name, it's simply runs when the event is triggered. This can also be shortened using the arrow function syntax, which is looked up. If we remove the function keyword and then add the arrow just afterwards, which is equals and then the greatest symbol. Check this is working okay by clicking the text. Using this add event listener would also be useful if you wanted to listen to all P elements on a page rather than just one. To do this, we will would need to loop through all of them and we'll cover looping in the next section, or if we wanted to give this function a name so we could reuse elsewhere, we can cut out from here and create a separate function, that's because it's a little bit smaller, so it all fits on one line. Then I'm going to go ahead and copy from this closing brace here right to the start of this function parentheses. In fact, we'll cut these other place then above this we can create our function. Give this a name of, var changeFontSize, just like this. Then we can set this equal to the function which was copied and space this out a little bit. Now we have our separate function which is now self-contained and stored in the value of change font size. Now instead of having this as the second argument, we can now just paste in this variable name and the code should work exactly the same. Refresh, click on the text and the function still works. Even though we've now placed it into its own variable, this also means now different parts of our code can still run this function by accessing this name here. Notice when we called the function just here, we didn't add the premises just afterwards, like this. This is because our [inaudible] will run the function straight away. It won't wait for the event handler first. Let's just add these in, save, and refresh and we can see the text is immediately 34 pixels even before we've clicked on the smaller text. Let's remove these now from this example and say this. This is it, now for our first look of events, they're really useful and something which we'll use a lot when working with JavaScript. We'll continue looking at events in the next video, where we'll look at the eventobject. 20. The event object: You should now have a grasp of what events are, and what we can do with them. There is also some additional information which is passed to the event handler, which is called the event object. This information is all about the events such as: what type of event it was, what element was triggered, and lots more information which we'll now look at. If we go over to our starter files for the events objects, inside of here we've got our texts and pretty much the same example from the last video. We have a EventListener which once clicked, we'll then change the FontSize by running this function here. So inside the parentheses for this function, which is this section here, we can add a parameter just like this. This can be any name of your chosen but it's often called event or e for short, because it contains the information passed to it about our events. You can think of this as a variable which holds this information, but what information is passed to it? Well, let's go inside our function and do a console log. We can take a look. Console.log the value of e. Save this and then open up these in the browser. Right-click and Inspect, and then go into our Console. With this now open if we trigger this function by clicking on our text, we'd now see some information inside the Console. Let's open this up and see what it contains. if we scroll down, we can see there's a huge amount of information which is passed to the event handler. Mostly you will never really use, but we can see some information about the events. We see it's a MouseEvents. We see at what position on the screen the MouseEvent was triggered with the x and y coordinates. We'll take a look at these x and y positions in just a moment. For now if we scroll even further down to the target which is just here, we can see there's a reference to the object which dispatched the events. In our case, it's the p elements with the id of text. We can see this better if we go over to the browser. Rather than just logging e, we can select "e.target" refresh, trigger our events. There is our events target, which is the p elements with the id of texts. We can use any piece of this information inside of our code. For example, if we go back to Console, login the full events and refresh. We mentioned before that we have some mouse positions, which is clientX and clientY. This is the x and y position of where we clicked on this text. We can now go ahead and track the mouse position over our elements by using these clients: X and Y. Back over to our function. Let's changed this document.getElementById from changing the style. Instead, we can change the innerHTML of the p elements to be equal to the event which you access with e.clientX, which is the x-value of the mouse. Then let's add a break element to add the y-value on a separate line, and we'll access y with e.clientY. We add a semicolon at the end. If we go down below our function to the EventListener, rather than listening for a click events, we can listen for the mouseover events. This will cause the events to be fired each time the mouse moves over the p elements, which will then display the values of x and y. Save that and then go to the browser, we can in fact close the Console down. Then each time we move the mouse over the p elements, we can see the x and y coordinates are updated each time. This is how we can use the event objects to get some extra information about the event. As you can see, there's lots of information passed to us which we have access to. Next, we'll look at how we can make our code more readable and organized by moving our JavaScript into separate files. 21. External Javascript: All there in the JavaScript starter files, there's a folder, if you go inside the menu called external JavaScript. If you open up this index dot HTML page, it's the same code which we ended the last video on. What we'll be doing in this video is taking the JavaScript out of this HTML file and placing it into its own separate file. Like what we did earlier with CSS. First we need to go over to our project folder and create a file to add this to with the dot js extension. Inside of this external JavaScript file, click on the new file icon, and we can call this anything we want. I want to call this scripts dot js. Then we need to cut the contents of the script for index dot HTML and then paste it into this new file. Back over to the index and then scroll down to our scripts section. Let's make this a little bit smaller just for now and then if we cut all the contents of our scripts leaving in these two tags in place. Paste this back into our scripts dot js file and give that a save. Good. The JavaScript is now in its separate file, for things to work. We still need to link this file in the index page using the source attribute. Back over to the index. Let's just move the script tags together. Then let's go ahead and add the source attributes. This is going to be a relative path to our scripts dot js file, the script file, and also this index page are in the same folder level. We can just simply add scripts dot js. If we save this and then go to the browser, reload, and now our code still works. Each time we move over, dp elements would now get an updated x and y value for the mouse. A lot of the advantages of external JavaScript files is similar to external CSS files. First, we have the separate HTML, CSS and JavaScript, making our code more organized, readable, and maintainable. Also having separate JavaScript in its own file will enable us to use it in multiple HTML files. If we just leave the JavaScript in the script files as we had before, it can only be used in this one single file. We can also add multiple JavaScript files to HTML page two all we need to do is add more script tags with the source attribute for each file. Next, we're going to put what we've learned in this section into practice by building a calculator to convert pixel values to em. 22. Time to practice: pixel to em converter: Now is your chance to put into practice what we've learned so far in this course. We are going to be creating a calculator which converts pixel values to be em. Remember, em is a relative size, which is based on the parent container. For example, in pixels, if the parent container was 20 pixels and we want to detect inside to be 18 pixels, we can click convert and then when it set the value to be 0.9 em's. Everything which you need to build this calculator, you've learned so far in this course. It shouldn't throw up any surprises and if we go over to the starter files, and if we go over to 20, which is the pixel to em calculator and if you go to the script.js, we have the calculation at the top. To get the em size, we divide the required pixel size by the parent pixel size and this is the conversion you will need to make this work. Also, if we go over to the index page, you're already provided all the styles and the mark-up that you'll need to get started. Everything you need to do will be inside of the JavaScript file. We can go ahead and focus on adding the JavaScript. May look a little complex, but all we need to do, is to get this calculation, grab the values for all parents, and also the required size, and perform this calculation when this button is clicked. Good luck with this, give this a good go, and I'll see you in the next video where we'll go through my solution. 23. Solution: pixel to em converter: Welcome back. I hope you managed to get your calculator to work, or at least give it a good go. I'm now going to go ahead and show you how I did my version. It maybe a different approach to how you did yours, but as long as it's working, it's fine. There is usually more than one way to do things. All the CSS and HTML, as you can see here, has been taken care of for us in the starter files. All we need to do is go over to the script.js and start to work inside of here. Let's go ahead and create a function to perform this calculation. I'm going to call mine calculate, and set this to ar function. Inside of here I'm going to begin by grabbing the values of the parents and required. That's this box here and this one here, and then store then them in side of variables. The variable of parent value. Distribute documents.getElementsById and the Id we want to grab. If we take a look at the index page, there's this parent input here with the Id if parents. Then the second input has han Id of required and we'll use this in just a moment. Let's add parents inside here. We can then grab the value with dots value, and then we could do the same for the required value. Required var is equal to documents.getElementByID. Remember the Id we looked at before was required, and then again we can grab the value with dot value. Now we're grabbing the two values of the two input fields. The third variable I want to create is for the output, and this is the result which you see here. This is the p element which is going to obtain the results each time we perform the calculation. Let's crop this with the Id of results and then store it inside a variable. Var results equals document.getsElementById, and the elements will have results, and we can just store this for now. Now we want to perform this calculation. Each time the user clicks on this convert button, if we go back to the index of html, this button is just here. We can grab this button with a query selector and then add an event listener for each click, to then go ahead and perform this calculation. The button will be installed inside a variable called btn, and then document.querySelector. Grab our button and then press btn and we can go ahead and add the EventListener. Inside the brackets, we can add two values. The first one is click and this is the type of event you want to listen out for. Once the button is being clicked, we then want to go ahead and run this function here. Let's add this in as our second value to check this is working okay, we can then do a console log inside the function, and then we can log our two values of the parent value and the required value. Status. Check these row, okay, so parentValue and then empty space, and then the required value. Save that onto the browser, and then open up the console. We'll just click on Convert first, and we shouldn't see anything inside the console because we're outputting the values of these two inputs. Let's add some fit inside here, 20 and 16 converts, and so there we go. There's our two values inside of there. The simple way to go ahead and update this result here is just to grab this result variable here and set the innerHTML to be the results of this calculation here, which is a requiredValue divided by the parentValue. Let's give this a go. If we say results dot innerHTML is equal to the requiredvalue divided by the parentValue of the browser, and that's values into here converts and we'll get the value of 0.6 it will set these to both 20, we should get the value of 1 M. This is a straightforward way of doing things. However, if we refresh and only add one value in place click converts, we see we get the message of Infinity, or if we just click on Convert without any values in place, we'll get not a number. We want to protect against any empty fields resulting in these areas. We can do this by adding a if else statements inside of this calculation. Below this we can say if we can add an exclamation mark and then parentValue. If the parentValue is empty, and remember the pipe is for all or the required value is empty. So each one of these fields is empty, would then want to create an alert to the user just with a simple message of 'please fill in all fields.' Just like that, and then we can also add an else statement. So this else statement will run if all fields have been answered. If this is the case, we want to grab this results. HTML and go ahead and run this code and let's give us a go in the browser. Now if click on converts, you'll see the message of 'please fill in all fields'. Let's just try one of these. Will still get the same message, and then if we try the calculation, everything seems to work in fine. Okay, so this is how I completed this project. Remember if yours looks a little bit different, as long as it's working, everything is fine. This is now the end of the section all about DOM (Document Object Model) manipulations, functions, and events. If some things are still confusing to you, don't worry too much. Everyone learns at different paces and there is a lot to take in here if you are new to this. Remember though a lot of what we've learned in this section will be repeated many more times as you progress through this course. You'll still get plenty more practice or using these techniques. I will see you now in the next section where we'll cover loops, arrays, and objects. 24. Javascript arrays: Let's kick off this new section by looking at JavaScript arrays. We've already had plenty of practice writing variables which as we know store a single value. Arrays also store values too, just like a variable, but we can add more than one. Over to the arrays starter file, which is just here. We can start an array just like a normal variable. Down to the script, we can use the var keyword and then set a name, which you want to set for our array. Just like a variable, we can also set our values, but we can set more than one separated by commas inside the square brackets. Let's say a cut, a comma, a string of dog, a comma and let's go for a tiger with a semicolon at the end. Now let's output this with an alert. Let's say alert. Inside this alert, we can alert our array of animals. Let's say our alert inside the browser reload. There's our three items which are inside of our array. Or we can output this to an element, just like we've already seen. If we go over to our HTML, let's create a div with an ID equal to animals, who can just leave the contents empty for now and then go down to our script. Then we can grab this with get element by ID. The ID was animals and then we can set the inner HTML like we seen in plenty times previously and set this to our animals array. Save, close this down in and refresh and now we'll see our array on the screen. We've only used strings inside this array, but we can also contain any other data type, such as numbers or Booleans. These going exactly the same, separated by a comma. We add our numbers, rather quotations, and we can also set our Boolean values of true or false. Save that, and we also see these outputted as expected. Display in our animals array, just like this, we'll display all items inside of our array. But if we just wanted to select a particular one, we could reference it by its position in the array. Just like we've looked at previously, we can select an index number with the square brackets and then add our index volume. Remember arrays, just like we've looked at earlier, begin at position zero. Save that and now we should get the first phoneme of cut, and of course we can change this to be any number. If we wanted Tiger would go zero, one, and then two. Set this to be two, and there's tiger inside the browser. This is similar to what we looked at earlier when we looked at query select all and added these square brackets after it. Along with accessing the values of an array. We can also use the [inaudible] property to see how many values it contains. Over to our script, leave the square brackets. Then we can say animals.length, and our array has five different values. We should see the value of five inside the browser. Good. This is how we can use JavaScript arrays. We will continue with arrays in the next video, where we will look at some built-in array methods. 25. Array methods: In our starter file for this video, which is number 22, array methods, we have a similar looking array of animals to the last video, which is just here. We then display them in a div with the id of animals who brought this up to get elements by ID is down at the very bottom this time, which you can see here. This is because before we can get to display this Array, there is some built-in methods we can use called Array Methods. There's quite a lot of these methods we can use. Here we're going to look at some of the most common ones. Include how to add and remove values from an array using JavaScript, starting with shift. If we scroll up to the first comment which is just hear, shift will remove the first element from our array, which in our case is cat. All we need to do is access the Array by its name and then say dot shift. It is simple as that, now if we open up this Array Methods inside the browser, we now see our first value of cat is now removed. This is our new Array return back towards, now we only have our four values. We can also store this removed item in a variable if we wanted to. All we need to do is assign a variable such as animal1 and set this equal to our values of animals.shift. Then we can check this out inside the console. So console log, and that's outputs the value of animal one, save, inspect inside the console. There as as expected, we have our first value of cats. Instead, if we wanted to add items to the beginning of the Array, we can use unshift to add as many items as we want. Slides comments out these two lines here, and then move down to unshift. Here we can start with the animals array, just like before, and then select the unshift method. Again followed by the brackets and a semicolon, and then as a string, I'm going to add some new animals, such as leopard, separated by a comma, a second value of bird. Let's see if our Leopard and bird is now inside the browser. That goes now got leopard and bird pushed to the start of our Array. This new array is returned to us with these new editions, the shift and unshift, a like a pair. They both modify the beginning of an array. The next tool, which is called Push and Pop, modify the end of an Array. Let's start with push, which will add one or more values to the end of this array. Let's comment out this line here. Move down to push. Starting with our animals Array, we can use the dot push method. Then inside here we can add some more values. Let's add our leopard and then our bird. This time to the end of an Array, refresh, so there's our first five items from before, and then our last two pushed to the end of the Array. Next up we have pop, which is pretty straightforward. We'll call the pop method to remove the last item of the Array. Comment out this line here and down to the pop section here, this is pretty simple, this is just like when we use animals.shift, but this time we use animals.pop. We don't add any values inside the brackets because we're simply removing the last item, save this, reload, and our last value is removed from the original Array. These four methods are great but they are limited to only working with the beginning or the end of an Array. To remove or to add items in different positions, we can use the splice method. Make sure all the methods we have just looked at are commented out, and we returned to the original Array with our five items, then we can call animals.splice. Just here, you see splice method came with the brackets and the semicolon. To begin removing items, we need to add in two values inside these brackets or parentheses. Let's say we wanted to remove this tiger, which is just here. Remember, Arrays begin at position zero, meaning the tiger would be at index position two. Our first value is two, so make sure this is spelled correctly. Splice just like that. Then we add our first position, which is two. If you just have one value like this, all Items after number two will also be deleted. Just like that. Everything from tiger onward is removed, or we can add a second value, which is a number of items to remove. Setting needs to be one, we will only remove our tiger volume, leaving our giraffe and lion on the end. This is how we can remove items. But if instead we wanted to replace this item, so if we wanted to replace the lion, we can just add in some values after this. Separated by a comma, let's replace a lion with a fish. Reload, and there we go. We still have our original cat, dog, giraffe, lion, both fish now replaces our value of tiger. We can also add multiple items in two, all we need to do is separate these by a comma. Let's go for a monkey this time, refresh, and there's our access to items in the middle. Let's wrap this video up with one more, which is how to reverse the Array, which returned in reverse order. All we need to do is go down to a reverse section and select the animals.reverse brackets and semicolon. Remember from before our lion is at the end and the cat is at the beginning. If we refresh, this is now swapped over. There is also some more Array Methods too which can do various things, and we'll cover more of these soon. If you interested in a full list, just head over to Google and then do a search for Mozilla Array Methods. It's answer, and it should be the first result which props up. Select this, and then we can scroll down to the method section, which is quite a bit down. Let's keep going, there's our properties which we looked at Array.length. Here is our methods too, feel free to take look through all these different methods and find out how they work. We've looked at some of these so far, so just, splice, shift, unshift, push and reverse. This is it now for this video, and I will see you next time. 26. Looping through arrays: forEach: In the next few videos, we're going to be focusing on looping. Looping makes repeating tasks really easy. In this video, we'll be looking at the for each loop. The forEach loop will run a function for each item in the array. First, let's go over to our starter files, so let's head over to number 23. Looping through arrays closes down. Here we have a basic starter with our empty div and then our animals' array. First of all, let's take a look at the problem, if we wanted to do anything with these array items, we would need to select each item individually. Let's do a console log, let's log to the console the value of animals. I was square brackets to select our index number of zero if we wanted the cats. Then let's say toUppercase, followed by the brackets and a semicolon at the end [inaudible] is a JavaScript method to transform a string to uppercase or capital letters to lowercase is also available to. Now if we wanted to select our second item two, we'll copy this and paste satisfy the worn. Then we'll need to do this forEach item inside the array. This would take up a lot of time and a lot of repetitive code. Let's go to the browser and into the console refresh. The Nasa will uppercase cat and dog so, of course this would take a lot of repetition to do this for our full array. Imagine if we had hundreds of values in the array that we need to be a lot of repetitive code and this is not great. This is where the for each loop comes in. ForEach, we'll run a function forEach array element, to say it was a lot of repetition. Let's go over to our code remove the console logs, and see how this looks. First we select our animals array, and then we use dot forEach. This is also communicates with a capital E. Bracket semicolon will then pass in a function which you want to run forEach array element inside of these brackets or parentheses. Let's create a standard function, the brackets and then a set of curly braces. It's enter and then inside of these curly braces we can run our function code. Would then pass in the name of our choice, which you want to give to each individual array elements. Let's call each individual item simply animal now if we want to do something with each array value, we can use this animal variable. Let's say alert our animal, semicolon refresh the browser. There's cats, dog, it's okay again, tiger and this is now looping through each item in the array. This animal variable can also be used in any way. We could add some extra text. Let's say a string of animal, animal type closest string and then add our variable onto the end. Refresh the browser and now see animal type of cat, dog, tiger, giraffe and lion. Or even going back to our uppercase example, we could use the animal variable and then say animal dot toUppercase. Brackets afterwards refresh now see our uppercase values inside the alerts. We can push all these new items as uppercase to a new array two. First, let's create a new empty array so just stuffed animals that say var upperCaseNames. We don't need to add any values we can simply just add the square brackets to create an empty array. We know how to push items to an array, we use the dot push method, which we looked at in the last video. Down inside our loop, instead of our alert, we can say upperCaseNames, which is our empty array just here. They'll push. Then inside the bracket, the animal wants push installed inside this animal variable. Animal, and let's set these to be uppercase so toUpperCase the parentheses. This time rather than outputs an east the console. Let's do our familiar getElementById, which is this animal's div here. Then we can push our new array to this div. Let's say document dot getsElementsById. All animal's ID, we can set the dot HTML to be equal to our new array of upperCaseNames. Scroll across what a semicolon at the end of the browser. There's a new array of uppercase values. Another feature of forEach is the ability to access each item by deposition or the index number. First, we add a second variable name of our choice inside the function. I want to call mine index so separated by comma, the variable name of index. Then we can use this index in side of our function so let's output the index before the animal name and join us on save and then refresh. Now we have the index position as well as the value so zero, one, two, three, and four. We can construct this new array item in any way we want. For example, if you wanted to add a space between the index and animal name, we can do that with a string, let's say index plus and you could have space or even a dash. Then also joined on our animal on the end refresh and there we go. Finally, index numbers bigger than zero so if we wanted this to start a one, we could just simply add plus one onto the end, let's say index plus one. There we go so now our index number starts from one, which is probably more realistic when outputting to the user. Now let's move on to look at a novel way of looping through arrays and this is called map. 27. Looping through arrays: map: Let's begin by going over to our empty starter, which this time is number 24. This was a pretty similar example to what we looked at in the last video. We have our div, which is empty, then we have our animals array. Also we have a second array, which is our animals set to upperCase, which is created using this forEach loop. Now we're going to look at another way of looping through arrays, which is called map. First, I want to quickly show you something which will help you see the difference between map and forEach. If we go ahead and remove the upperCaseName array and place, assign the result of the forEach to a variable. Let's say var upperCaseNames and set this to be our animals.forEach. Now let's simplify this example by removing the index number. Remove the second value from inside here, remove the contents from this function. Then we can simplify this function by simply returning the animals array.toUpperCase. Just like that. Now all we're doing is looping through our original array, running a function which will return our animals in upperCase, and then store them inside this variable. This returns diamond ends the execution of the function and then returns the new value. Now we scroll across, we can see this upperCaseNames here, which has been up on to the screen. Now refer to this variable just here. If we save this and then reload the browser, we get the value of undefined. Just hold onto this for now and we'll talk about this more in a moment. However, if we change the forEach, this time to be map, so remove the forEach keyword from here, change this to be.map. This time if we refresh, we now see the values of our array in upperCase. This is a key difference between forEach a map, only using map will return a new array. Basically, forEach will loop all of the items and do something with them, such as making them upperCase and pushing them to a new array, or even a database. Map will also loop over the items and do something with them, but it also returns a new array with the transformed items, which will have access to by storing them inside of this variable. Just as a final thought, we could also make this function shorter by using the esc auto function. Just after.map, we can remove this function keyword here and keep our animal and use the arrow. Just like that. Refresh and our array still works. Also remember, if we only have one parameter, which we have here, we can even remove the parentheses and make it even shorter. Reload the browser and everything still works fine. I hope this makes sense for law of purposes, map and forEach are interchangeable. You will need to use map when you want a new array returned. 28. Time to practice: arrays: Before we move on to looking at more types of loops, I think we should take a breather and make sure we understand what we've covered so far with arrays and also looping through them. Over in the Stata files, so open up the sidebar and go to number 25 which is time to practice and then let's open this up. Let's copy the path and then open this up inside of the browser. Over in the Stata file, I've added some instructions for a little challenge to give you some more practice. We have a empty DIV with the ID of characters and I've also provided an array of cartoon character names which I would like you to sort into alphabetical order and then store inside of a new array. There is also a little hint at the top here inside the comments. We can you use the dot sort method to sort the array, then the second part is to use the dot map to loop through this new array and add the text of name before each character. They'll look just like the comments here. The text of name and then the string of Bugs Bunny from the array, and then name Duffy Duck, and so on for each item inside of this array. Then finally I'll put these values inside of this empty DIV at the top. This is a great chance to reinforce what we've covered so far but if you are struggling to get this to work don't worry, we'll cover the solution in the next video. 29. Solution- arrays: Welcome back. I hope this challenge was something you were able to complete on your own. If not, I'm going to go through one way of doing this. Let's go over to our starters and let's scroll down to our script. Let's go for number 1 first, which is to arrange elements into alphabetical order, and then store inside a new variable. Let's go down and use this dot sort method here. Let's say characters, which is our original name.sort. Then we need to store this inside of a new variable, so that's assign, the variable name of sort is characters. The name is up to you. Let's try this out over in the browser. Factors to a console.log for our sorted characters array. Refresh. Open up the console. Open up the array, and there's our array, Which would return now in alphabetical order. We can go ahead and remove this console log and then move on to number 2. We need to return a new array with each elements having the name prefix. We need to add this string of name before the outputs of each value. To do this, I'm going to use the map function, which we looked at recently. Let's access our sorted characters, which is our array of our character names in alphabetical order. Then we can call.map. Then we can pass in a function. I'm going to use the ES6 arrow function and creates a variable called character for each item inside the array. Creates our arrow function, and inside of our function, and we're going to return, first of all, the string. The text of name, which you have here, let's say name, a colon, then the name of our individual character, which is stored inside this variable. Okay. Now, because we're returning the string, we now need to store this inside the variable. So we'll say var and let say sort names and set this to our function. So now we have these stored inside a variable. We can now all put these the browser using this idea of characters. Let's grab this empty div with a document.getElementByID, which has the ID of characters. Set the dot innerHTML, to be equal to this variable here, of sortNames, semicolon at the ends. Close the console, and there we go. Now, there's all our strings of Name: Bugs Bunny, Name: Daffy Duck, Jessica Rabbit and Roger Rabbit. We now have the name prefix as a string, and these are also in alphabetical order. If you manage to do this, great. If not, just consider it a learning experience. Next up, we're going to take a look at another type of loop, which is the for loop. 30. For loop: In the next few videos, we're going to look at some different types of loops. The loops we have previously looked at are intended to be used with arrays. However, the For and while loop, which we're going to look at is a bit more general purpose and not exclusive to arrays. Let's say we wanted to grab one of these characters and add it to the unordered list. Let's go to data. Have our empty or unordered list here. Our array of characters, just like before. If we wanted to add these characters to this empty UL. To do this, we need to loop through each item inside this array at li tags and then place them inside unordered list. First, we can create an empty variable to store these character names with the li tags. Let's say on the characters, create a variable called item and set this to be a empty string. If we were to do this manually without using a loop, we need to do something like this. We'll grab our empty item, which is this variable here, and then use plus equals. Plus equals will add the value on the right to this item on the left. Let's say characters, which is our array here, and then position zero. This would assign our Roger Rabbit value, which is just here, to our variable of item. We could then add this onto a new line by adding a break tag and then a semicolon at the end. If we copy this and add the same three more times. Again, manually we need to do one, two and three. Then we'll add these items to this unordered list with a document.getElementByID. Want to lacked the idea of characters and then set the inner HTML to be equal to our item. If we say this and then reload the browser, good. Our array items are now on the page but this way is not ideal because you may have hundreds of items inside the array. This would mean a lot of repetition. Would need to repeat these lines multiple times for each item in the array. This is a problem in which a loop could solve for us. We create a for loop just like this. Let's add the for keyword, the parentheses, and then open and close the curly braces inside of these parentheses here. The for loop takes in three statements. First is what is called the initializer. Let's say it's our initial value of i to be equal to zero with the semicolon at the end. Here we can set a variable with our initial value is common to see this variable called i, which stands for increment. This is because this is incremented with each loop after the semicolon. Second is the condition. The loop will continue as long as this condition is true. We want keep looping for the length of the characters inside of this array. We can say while i is less than the characters dot length, semicolon at the end. Third, we say how we want to increase the value of i with each loop. If we say i++, this will increase the value by one each time. The first loop, i begins at the value of zero. Then after the second loop i will be one the third loop i will be two, and so on. Then just like a function, we can add the code we want to run between the curly braces. This code is repeated for each loop, or in our case, it will be repeated for each item inside the array. If this is confusing, let's console log the value of i to see what's going on. Console log the value of i, open to the browser. Open up our console. Okay, we've got zero, one, two and three. Remember we initialized i to be zero. This is the starting value. We then have four items inside the array. There are four different values here. These four values of zero through to three should also look familiar. It's the same as what we did right at the start. We have our values of zero through to three as our index positions inside the square brackets. Rather than having these four lines of code, we can simply copy one of these lines. Instead of the console log, we can now add it inside of our for loop. Delete these four lines, we don't need this anymore. We're going to be using this with our loop now. Then the hard coded value of zero can now be replaced with the value of i, which as we know, is zero, one, two and three and so on. Now if we save this and then reload, we still have the same four names up on the screen here but this time we're using the for loop with a lot less code. This is good because this will be repeated for as long as we have items in the array. For example, if we were to go and add any new value on here, so that should say, "Hello," inside there. This will also be added to the end of the array. I'll just remove these for now. Since the characters container is a unordered list, which is just here, we can improve this loop by surrounding each item inside of the list item tags. Just before characters. Let's other string of li the plus symbol. Then right at the very end, change our break tag to be our closing list item. give that a save, reload, now we see this is a list item because we have the bullets on the left-hand side. If we also right-click and inspect, Click on the inspector and choose any one of these list items. We can now see on the screen we have our unordered list and then next inside we have our four list items, just like standard HTML. If you remember back in the DOM manipulation video, we looked at query selector all. If we go back into our starter files. If you scroll up to number 10, which is DOM manipulation, let's quickly open up the index page. Down at the very bottom we had query, select all, where we selected our two images by the index position. Remember we said we can access all our images by this index number but this is also not ideal because we're repeating code. Rather than duplicating code like this, these are the things which a for loop would be useful for. If we close this down and then go back to our for loop starter file, which is down here, I've provided two different images inside this folder. We can go ahead and add these in now. Close the sidebar. If we go to our unordered lists at the top inside the HTML, let's add an image. First of all with the source of bugs bunny, which has the dot PNG extension. Then our second image, this time with the source of daffy duck.PNG. Close this off. Now I have our two images. I'm going to go ahead and store these reference inside a variable called images. Down to our script. Lets go right down to the very bottom and let's select a variable called images. Set these to be document.query, select all, and then grab all the images with the IMG tag. Then we can use the loop again, do anything we want with these images. I'm going to grab the name of each of these image files on the screen. Just below our images variable. Let's create a new for-loop. Construct this just like we did before. Then we can add our three values. First of all, let's set our initializer, i is going to be equal to zero; we're going to run this loop while i is less than images, which is our variable here.length. This will be two elements long because you have two different image elements on the screen. This will run twice the semicolon at the end. Then we're going to increment this one on each loop. Now let's check out the outputs with a console log. The value we want to display is the images. Our images variable here, inside the square brackets, we can add i. This will access the first image on the first loop. Then on the second loop we will access the second image because i will be equal to one. First let's check this out in the browser. Head over to the console. There's our two images which we just lived through. If you wanted to grab the name of the source, we could use the.getattributes. Then inside the brackets, the attribute we want to grab is the source. Now back over to the browser. We now get the source attribute name for each image. Again, if had lots of different images, loop would be really useful for something like this. Loops can really save us a lot of time when performing repetitive tasks. This is how a for loop works. Next we will look at the while loop. 31. While loop: Inside of our while loop starts the file. We have the same example which we looked at in the last video with the for loop. We have our images. We have an unordered list, we have a character's array and then we're pushing our characters into this empty div. Then we have our two images just below. This for loop which we looked at before, will continue to run as long as this condition is true, which is just here. So while Larry's items inside the array, this will keep running. A while loop, which we're going to look at now, does a similar job. But this time a while loop runs, while a condition evaluates to true. We can modify this to be a wild loop by changing the fall to be while. We can also remove the first and also the third statement from the brackets. So remove this data and i plus, plus. This is because a wild loop only receives the condition inside of here, and it will keep running while this condition is true. We still need to initialize the first value of i, and we can do this outside of the loop. So just above the loop, let's say var i is equal to zero. Finally, we can increment i on each loop, right at the very bottom, select say i plus, plus, and give us save. So to recap, this loop will begin at zero, which you suggest here. It will then add the first array item, which is this first line here. And then after it's done, AC will then increment i to be one. This will also continue to run until the value of i is no longer less than the length of the array. So if we do that, say we should still have our four names on the screen from our array. But this time using the while loop. Having the i plus, plus writes at the very end is really important. If we forget increases on each loop, i will always be less than the length of the array, meaning the condition will always be true and this will result in an infinite loop. This will cause the browser to crush. So if we were to remove this and then save, refresh, we can see that the browser is struggling to load. We can still see the spinning in the corner and also we have the option to stop loading the page and the browser will crush. However, a lot of modern browsers will also detect that this is the case and will stop running after a period of time, which you can see here. So now let's just add this back end solos no more problems, and then reload and our looped items are back on the screen. Before we wrap this video up, let's take a look at one more example. So let's go down to the very bottom and let's creates more variables for some numbers. Let's say x is equal to five and Y is equals 10. Then create our while loop, just like we did before and then we can create our condition. So let say if the value of x is less than y, then we can run our loop. So let's do a console.log the value of x, and then we create increment x by one each time. So while the value of x is less than y, we can output it to the console and then incremented by one each time. So save this over to the console. Refresh and there we go. That's values of five right through to nine. If we wanted this to go all the way to 10, just like the value of y. We could set this to be less than or equal to and this will now go up to 10. So this is how we use a while loop in JavaScript, and in the next video we're going to move on to looking at JavaScript objects. 32. Objects: Welcome back guys. We're now going to look at JavaScript objects. Objects are the collection of properties which have a name and a value pair. For example, just like in real life, a computer is an object. A computer can have many properties for example, a property name of manufacturer, and a value of Apple, a property name of monitor size and a value of 22 inch, or sticking with our characters from before, a character could be an object too, with a property name of first name, and a value of Mickey, or a property name of color, and the value of red. These are all just names and values which are much together which construct a object. Let's create an object over in the object's starts a file, which is just an empty script tag. First, we define new objects with the new keyword, so new objects, followed by the brackets, and the semicolon. We can then assign this new object to a variable and let's set this to the name of character. If we now go over to the console, so right-click and inspect, open this up, and then we can do a console log with the value of character, save that and then reload. We see a set of curly braces. This is just an empty object because we've not yet added any properties. If we go back over to our project, we can now add these in. We can do these by selecting our character and then let's say dot first name and set this equal to Bugs. Then we can say character dot last name equal to Bunny, then character, and let's say we had an image, so dot image equal to a string of bugs-bunny dot png. We'll do one more, we'll say Character dot color is equal to grew, so here we've given the character objects, the properties of first name, last name, image and color and then we're assigning these values on the right-hand side. If we save that and then go back over to the console, let's see what effect this has. We now see some content inside of our curly braces, so our object now has some properties. We can say our first name of Bugs, our last name of Bunny and so on. These are name value pairs, so first name of Bugs is a name value pair, last name of Bunny is a name value pair too. We can access any of these properties directly with the name, just like this. Let's go over to our console log and just below it we can add a second console log. If we wanted to access our characters color, we could select the full character and then say dot color, refresh this and there's our value of , which is this property just here. Access our values just like this with the dot is called the dot notation. There is also a second way of accessing these properties, this is the brackets notation. This time instead of accessing the properties with the dots, we can do a console log and instead use these square braces. Let's select the character objects, the square brackets and then we can access our color, semicolon at the end, refresh and there's our two values of gray. First with the dot notation and then second with the brackets. Another way to create an object is called object literal and rather than declaring a empty objects, which we add just here and then adding properties to it with these four lines, we can do it all at once. Let's comment out this first method here and then just below this. We can create our object and store it inside available. Let's say var character and set this to all objects, rather than having an empty object, we can now assign our name value pairs, so let's say our first name, the colon. Our first name is Bugs, separated by a comma, we can add our second one of last name, and this is Bunny. Again our image, so Bugs-Bunny dot png and finally the color. These previous values which we've looked at, are just simple strings. These can also be any data type which we've already covered, such as an array. We can add multiple values for the color, so let's say we have a color value of gray and then separated by comma, also white too. If we save this and in fact we'll remove these console logs, just leaving our character. Over to the console, there's our name-value pairs, just like before, but this time our color is an Array with two separate values. If you click on this arrow here, we can then open this up and then expand the color. The index position of zero is gray and the index of one is white. We can even add functions to our objects, so just after the color, we can add a comma and then let's set a function which will create a string which concatenates our first name and last name. Let's say our full name is equal to a function and then create a function just like we've seen previously. Inside the function body, we can do a Alert and inside the alert, let's create string saying my full name is, a space and then can add our properties. Let's say this dot first name, then add a empty string for the space and then on the end we'll say this dot last name, semicolon at the end. There's a couple of things to note here, first of all, when we add a function as a property of an object, this is called a Method and also we've have used this keyword to access our properties. When a function is called as a method of an object, the value of this is set to these current objects. Therefore we can access any of these properties on this object by using this dot and then the name of our property. If you give this a save and go over to the browser, you can see our method of full name is here plus if you want to actually run this method and display the alert, we need to execute it within the parentheses. Back to our console log and say character dot full name, the parenthesis just after and now if we save and then call this, we'll now see our method run and the alert is in the browser and the string of My full name is Bugs-Bunny, closes down. This is now for our first look at objects, they're really useful for grouping together information about almost any type of item. Next, we'll stick with the topic of Objects and look at how we can loop through them. 33. Looping through objects: Just like when we were working with arrays, if you have lots of properties on an object, we may want to loop through them. This is more efficient and less code than selecting each property separately. Inside of our starter file, which is looping through objects, we have a character object just here, which you can loop through. I'm going to create an empty variable to start with, the store the results. Let's say Var results and satisfy me an empty string. This is going to store the results of each object property which will loop through as a string. The loop we're used to loop through object is called the for in loop and it looks like this. We start off with a standard looking for loop just like before. Then we go off to the premises and set our variable of i, but this time say in character. Character is the name of our object which is here. Now inside the loop body we can do some console logs. Let's start with a console.log for the value of i and see what we get. Let's open this up inside the console. Right-click inspect and now we can see we get the values of firstName, lastName, image in color. This is because the value of i is the key. This is basically the values on the left-hand side of our properties. If we wanted to access the values on the right-hand side of our properties, we could then do a second console log. This time instead of i, we do the character (i); semicolon at the end, refresh. We can see each pair is now on the screen. FirstName of bugs, lastName of bunny. If we wanted to see these better, we could do a third console log and just add something to separate these values, such as some dashes and there we go. There's our properties. Okay. Good, so now we have access to all of these properties and also the names and values individually. We can now go ahead and construct our results and creates a string to display on the screen. Let's go down to our for loop and below these console logs. It's construct our string. We can access these result variable add this with plus equals. First of all, let's set the value of i, which is our property names such as firstName and lastName, add today's a string with a colon in between and space. Then just after this, we can add our property name such as bugs and bunny. Just like we're seeing with this console log here. Let's add character i and then add these onto their own separate line with a break tag. We've created a result which is a string of all of our characters properties with the names and values. We can now open this the browser inside an empty div. Let's go up to the body section, create a div and add id of outputs is going to be the location where we're outputs, our results string and then go down to the bottom outside of the for loop. Let's do a document.getElementById, we want to grab the outputs, which is our empty div and then set the innerHTML to be equal to our result variable. If we save this and then over to our browser, reload, we now see the string we've created with the property name value followed by a break tag. This is a string which we created just here. This is repeated for each item inside of our objects because we've added this to a for in loop. This is how we can loop through objects and it's really convenient, especially when objects become really large. In the next video, we're going to continue to look at objects and how to build them using the constructor function. 34. Object constructor function: We've already looked at a few ways to create objects. These are fine if we just want to create a single object, like we've done previously. However, if we want to create multiple objects with the same properties, there is another way using a constructor, rather than constructing a object and adding names and values, we can use the constructor function to basically create a blueprint, or a template for each object. This will allow us to then create multiple objects using the same structure. For example, if I had multiple characters that would usually contain the same properties, such as a name and a color. Let's give this a go over, and I'll start a file for object constructor function. Down in our scripts, the constructor function is created just like a normal function which we looked at. We use the function keyword and then set a name, such as character. Constructor functions usually have an uppercase first letter, just like we see here. So we can distinguish them from regular functions. We'll come back to this in just a moment. But first we can create a new object based on this constructor function by using the new keyword. Just below this, let's use the new keyword, we say, new character. This character here, must match the name of our function just above. Then inside the brackets we can add some values which we want to use in objects. So the first name, let's say Mickey, separated by a comma, a second value of Mouse, for the second name. We can then add an array of colors. Mickey Mouse, we can use red, we can also say yellow, and also black too. Make this a little bit smaller. Just after the array, we can add a comma, and then we can add a name for our image. Let's say mickey-mouse.png, and then add a semicolon at the end. Now we've created this new character. We can now assign it to a variable called mickey. Great. We've constructed a new character, we've passed in some values inside the parentheses, but how do pass them in? The answer is the same as a regular function. We can pass them in as arguments. Inside the constructor, we can say first, last, color, and image, which is in the same order as you created down here. Down here we have our values for the first name, last name, color, and image. But these are not yet linked to our names above. We can do this inside of the function body. First of all, let's say this dot first name equals first. This may look a little strange at first, but what we're doing for the first value is we're passing in a string of Mickey, which is stored in this first variable. Then will set in the first name to be Mickey. Also in JavaScript, this keyword can be a little complicated to understand. When used in this way, the keyword of this refers to these objects. We can see this by doing a console.log and login the value of this, and then go to our console. We can see that this keyword is referring to our character with the firstName of Mickey. Here we can also see our property with the name value pass, which we've have already added. However, if we go ahead and move our console.log to be outside of the current object, just like this. Now we go back over to our browser. We now see we don't get our object returned, instead, that this keyword now refers to the window objects. This window object represents the browser's window. Any global functions, objects and variables which will create, will then become parts of this window. If we go ahead and clear the console and type in window, hit ''Enter'', we now get our window returned, and if we open this up, we can also see the properties on this window objects. Inside here we can see our character function, which is just here. Also remember, we created a variable called Mickey. This will also be stalled on the global object too. If we scroll down, here's our variable of Mickey. Inside the console can have access to any of these by their name. Let's say window.mickey. Hit ''Enter'', and there's our character with the first name of Mickey. We also have access to a lot more properties of the browser, such as window.innerWidth. Hit ''Enter''. We can see in pixels the inner width of the browser. Let's now go back over to our constructor. First we can remove this console.log, and then we can add the rest of our property names. Second of all, we have this.lastName, and this is equal to last. This dark color is equal to color. Then finally we have this.image is equal to image. Now let's see what Mickey looks like inside the browser, with a console.log. That's with console.log with the value of our variable, which is Mickey, refresh. There's our character objects, with our first name of Mickey, last name of Mouse. We have a color array with free different values, and then our image at the very end, because Mickey now has all the names and values added to the object. These properties can also be accessed individually. For example, if we wanted to select the first color, we could say mickey.color, and then access the index position of 0. Refresh, and there is our first value in the array of red. Now, this blueprints or this constructor which we have here, it now sets up. We can go ahead and create multiple objects based of these templates, just like we did with Mickey. Just below Mickey here, we can create a new variable, and this time we can call it daffy. This is also a new character object. Then inside we can pass in our values, the first name of Daffy, the second name of Duck, and then our array of colors. Now let's set the colors inside here to be black, and then orange. A comma just after our array. This is going to be for our image, which is daffy-duck.png, a semicolon at the ends. Then let's do one more, so let's say variable of bugs is equal to a new character, at our values. The first one is string of Bugs, the last name of Bunny. Our array with our colors of gray, and also white. A comma again, just after the array, and the final image of bugs-bunny.png. Let's just zoom-out and check this all out. That's all looking fine. Now if we console.log any of these extra values, so console.log. Then we can do something such as bugs, which is our third object just here. Target the last name, which should output to the console the value of Bunny, save and refresh, and there we go. There's Bunny inside of the console. Good, this all looks like it's working fine, and this is the object constructor function, which is a really useful way of creating multiple objects with the same structure. 35. Const and let: Welcome back to this brand new section. We'll be reinforcing what you've already learned along with learning some new stuff such as const and let, template literals, setting intervals, and regular expressions. We're now going to put our skills into practice by building a phone game. I've already added the HTML and CSS into the starter file, so we can focus on getting this game working using JavaScript. In this game, all we need to do is click on the "Match" button when two random shapes are the same size and color. This is the finished version in front of us here. All we need to do is click on the "Play" button, and this will trigger an array of objects which are randomly selected. In this game, all we need do is click on the "Match" button when the two random shapes are the same size and color. Although it looks simple, there is a big going on behind the scenes, and we'll get lots of practice with what you've already learned, along with some new things too. We'll click on the "Match" button when two are the same, we then get a score. If the shape is different, we then get a point taken off and the result can go negative. Let's go over to our JavaScript starter files, and the code for this is in number 31, which is the shape matcher game. Here I've got the index on the script.js file already open. I'm going to copy the index page, copy the file path, and then paste this into the browser to get it going. We already have all the layout and styling, so all we need to do is work in the script.js file. Let's go over to this now, open up the script.js. Let's make a little bit more space inside the text editor. Inside here, I'm going to begin by creating our shapes along with some variables to store them in. This time though, we're going to be focusing on two new things. We're not going to be using a variable using the var keyword. In fact, we probably won't use them again for the rest of this course. Not because there's anything wrong with variables. They still perfectly valid to use. However, in ES6, which we've already mentioned, is also known as ES 2015, we also have two new keywords we could use in place of var to start all variables. First is let, which allows us to also declare a variable. We need some variables to this game. Let's go ahead and create a let current score. We can set this to be a initial value of zero. Just like var, value stored using let can be updated, also called reassigned. There's a different with let and var. Let values are block scoped. The block scoping applies to things such as functions or statements. Basically anything between a set of curly braces. If you remember back to when we looked at scoping, we learned variables declared inside of a function are scooped to that function, meaning we cannot access them elsewhere in our code. Also variables declared outside of a function are called global. We have access to them anywhere inside of our code. Let values on the other hand, are scoped to not only the block where they were created, but also anywhere else they are used. We can see this better with a simple example using our current score variable. If we add this to an if statement, so let's create an if statement which we've already learned about, and then we can say if current score is less than five, inside here we can say a console.log, and log is the value of current score. Then a string, and this can say inside. Once we're in the console we know where his message is coming from. Then let's do a second console log outside of this if statement. We'll do the same, we'll add the current score to a string. But this time, we'll say outside. Now if we go over to the browser, open up the console, click the "Console" tab, refresh, and now we can see zero and zero. This applies to both the inside and outside. This is expected behavior. We declared our let value to be zero, then log it inside and outside of the if block. Let's go ahead and declare the same variable, but this time inside of the if statements. Let's do the same. We'll say let the current score this time to be equal to a value of 10. Now let's go to the browser and refresh, now we'll see the effect of block scoping. Current score inside of the block is a value of 10. But the current score outside of the block is untouched. If these are both variables, let's change let to the var in both cases. We'd now see that both values would be 10. Because this variable is declared outside of these curly braces, meaning it has global scope. For most cases, we can use the newer let keyword, now to declare variables and this is what we'll be using for the rest of this course. Select "Remove", all of this example, and then change this var to be let. We also need some more variables to this project. Let's go ahead and add them now using our let keyword. We're going to create a variable called let playing. This is going to be initially set to false. This will be turned to true when the user clicks on the "Play" button. Then let's create two more, one for shape 1 and then also one for shape 2, shape 1 and shape 2 are currently unassigned, because we need to add a random value to these later when the user starts playing. Along with the let keyword ES6 also introduced the const keyword, which is short for constant or variables we declare using var and let can be changed or reassigned. However, if we know our value is always going to remain the same, we can declare a constant instead. This will also have the benefit of the value not getting accidentally updated elsewhere in our code. If we declare a const and try to update a value, we'll get an error. Let's set a number to be equal to 10. Then let's say number plus plus. Now we're increasing the value of 10, even though it's stored inside a constant. Let's see what happens inside the console. If we try and log the value of number, reload and we're getting error because we're trying to update the value of a constant. Let's remove these for now. A constant will be useful for declaring the shapes we want to use in this project. We want to select the shapes, but we don't need to change them. Each shape is going to be an object. So we can add these in as an array of objects. Lets setup our constant called shapes, and this is going to be an array. Inside of this array, we can create our object. We need to go ahead and create quite a few of these, so we have some random shapes to select. Let's set the color property and these can be any colors of your choosing. I want to go for the value for the first one of FF595E, then the width of 250, and the height. Let's go for 160, then add a comma. Let's go ahead and copy this and paste this in nine more times, giving us 10 different objects. We're going to keep the first two as the same color, but change the width and height to be slightly different, so 150 for this one, this third one, this is going to have a value of FFCA3A, width of 320, the height, let's change this to be 170. The fourth one can have the same color, width of, let's go for 310, the height of 180. Number 5, this is going to have a color of 8AC926. The width of 190, height of 160 is fine. Let's copy this color, and we'll create two of each color. The width this time, let's go for 200 and then 175. Again, this is all random, so don't worry if yours is slightly different. The next here the color can be 1982C4, the width of 380, height lets go for 185. Copy this color, so these two are the same, then a height of 400. The width for 400 and a height of 120. Then the last pair, let's go for 6A4C93, 370 and the height of 145, copy this color and make the last one the same so it's a paired again. A width for 440 and the height of 160 is fine. When the user clicks "Play", we're going to look through these objects, select a random one. If the computer selects the same random one for shape 1 and shape 2, these would be then be considered a match. Finally, we can do a quick console log of these objects by selecting them with the array index number. Just below our array, do a console log and the value of shapes. Let's go for number 2. Check this out on the console, and there is one of our objects with the color, the width, and the height. In this video, we've concentrated on using the const and let keywords words. If you aren't sure when to use const and let, you should always use const where possible, and then use let if you need to reassign a value. If you make a mistake and use const when it should be let, it's completely fine. The console will alert you to change it. With our shapes now ready, in the next video, we'll look at how to randomly select from this array of objects. 36. Generating a random shape: In the last video, we added an array of shape objects. Now we need a way of randomly selecting one of these shapes from our array. I'm going to add this to a function called select random shape. Back over to our script, we can now remove the console log from the last video and then the set a bay constant for our function called selectRandomShape. This is going to be a ES6 array function. Set this up just like this. Well, now we can select any of these array items just above by the index number. Let's give this a go. Let's set up a constant called randomShape and set this equal to our shapes array and select one of the index numbers. Do a console log. Check if this is working okay with the value of a random shape. In fact, we'll call this randomSelection, just to be a bit more clear. Console log this. Then for this to run, we need to call it by its name. So selectRandomShape, the parentheses. Now this should run inside the console. Open it up, reload. We have a spelling mistake, so this should be shapes. Refresh. Now we're selecting one of our objects. Rather than hard coding in a number, we want them to be selected randomly. To do this, we can generate a random number, like we have seen previously. If we go over to our code, this array has 10 objects. Arrays also begin at zero, so we need to generate a random number between zero and nine. Let's start this in side of our function. Let's store this in a constant. I'll call this randomNum. We already know how to do this with Math.random. Remember, this will create a random number between zero and one. Zero was included but one actually isn't, so will only go to 0.999. You'll see premises after this. To create this random number to be between zero and nine, first thing we need to do is multiply this random number by the length of our shapes array. So shapes.length. Then we can round this number down with Math.floor. Right at a start use Math.floor and then open up the brackets, and then we can close this off right at the very end of the shapes.length, semicolon at the end. Just blow this, let's do a second console log and then we can output the value of our random number. Just check this is working okay, as at the same. Refresh. It says 0, 7, 6, 2, and so 8, there's a 9. This all seems to work in okay, we don't get anything higher than nine and will also have zero. This seems to be working completely fine. Now we've got it, this random number between zero and nine. We can replace the hard-coded number from before for our array. Rather than selecting number 1, let's select our random number. Remove the console log from both two, we don't need this anymore. Give that a "Save" and then over to the console. Now if we keep refreshing, we should see a different object from our array each time. Great, so just to finish this video off, I'm going to change this console log. We don't need to log to the console, and instead, just return this randomSelection. This will return the value so we can use it later. Good. This is an important part of this project, taking care of. Next, we going to use this random objects and assign it to our variables of shape 1 and shape 2, and also repeat this process every second to keep showing different shapes to compare. 37. Repeating with setInterval: In the last video, we created a function which randomly selected one of the shapes inside of our array, which is just here. In this video, we have two main objectives. We want to assign these random shapes to our shape 1 and shape 2 variables. Also, we need to change the shape values every second to update them on the screen. We know this select random shape function down at the bottom is resulting in a random shape. So we can go ahead and assign this to our variables. First of all, let's say shape 1 is equal to select random shape. The same for shape 2 this can also be select random shape 2. Now we need to run this select random shape function every second and update these variables here. To do this, we can use a JavaScript method called setInterval. This will run this function or repeat the same code with a time delay between each repetition. So let's wrap these two here inside of our set interval method. So first let's cut out these two lines here. Then inside a set interval, we create the parentheses. Then inside here, we can run a ES6 arrow function. So let's create this inside here, the curly braces, and then we can paste in our two reassignments. Semicolon at the end here, and then we can add the time delay outside of these curly braces in milliseconds. So 1,000 is equal to one second. So now this function will run every one second, giving us different values for shape 1 and shaped 2 each time this interval will run. First, let's check this is working by logging the values of shape 1 and shaped 2. So console log, shape 1, and then a second console log, this time for shape 2 over to the browser. Reload. Good. So we keep seeing two new objects appearing in the console and they appear to have different values. So this works great, but we don't want this code to run until the player hits it's playable at the top. So first we can surround this timer inside of a function. So just below set interval, let's create our constant, which is going to be a arrow function, and let's call this repeat random shape. Again, it's going to be an arrow function. So we'll set this up just like this. So inside of the body of this function, we're going to add our set interval. So let's cuts out the section we created before, and then paste this inside of our function. So now this set interval will only run each time a call repeat random shape, and we want to do this when a player clicks on the Play button. So let's add an on click handler to our play button. If we go over to our index page and then scroll down to the main section, here's our play button here, which has an id of play. So we can select this with get element by id add a click handler to run our repeat random shape function. Down below this, let's add a comment of start game. Let's first select our button with get elements by id. The id was play.onclick. This is going to run a ES6 arrow function. Then inside here we can call repeat random shape, with the parentheses afterwards. So this will go ahead and run, save this and then over to the console, reload. We don't see anything running just yet. Now if we click on the play button, we now see our objects are now generate it. Good things are now moving on nicely for our game. However, we want to move the shapes out to the console and display them on the screen, and this is what we will do in the next video. 38. Template literals : Welcome back. There is now some basic functionality in our game. We generate two random shapes when we click on this Play button at the top. At the moment though these shapes are just inside the console. But in this video, we'll be actually displaying these shapes on the screen for the player to compare. We're going to do be doing this pile also learning about how to use template literals. This will basically allow us to create a text string which variables passed inside. We've already looked at some ways to include variables with strings. Let's go over to our scripts. We've already looked at methods like this. If you've created a variable such as name and set this to be the value of Chris, then do a console log. Inside here, we've added strings to variables, let's say "Hello", a space, and then add our name. Onto the console and now we'll expect the value of Hello Chris. Using template literals rather than joining these strings and variables with the plus symbol, we can construct one single string by using backticks. Let's remove all of this from here, and then if you look for the backtick on your keyboard, which is this symbol just here, then we can type in the value of Hello inside. Then instead of joining on our variable name, we can add this variable inside of the backticks. Can pass in our expression of variable first using a $ symbol, and then inside the curly braces, we can add our variable name, which just looks like this. If we save this and go over to the console, we see the same value is now working in the browser. Another thing we can do with template literals is to have multi-line text. If we wanted quite a long string just like this, and then continue this down on the second line. We instantly see with these two different colors here that our text editor is highlighting an error. To do this in the traditional way, we would need wrap each line inside the quotes, add a line break, and then join it back together with the plus symbol. However when using these newer template literals, we can just replace the quotes with backticks, such as this quote from here, add a backtick, also at the starts. Now this is all the same color, so it now appears to be working, we don't have the error anymore. Over to the console and there's our multi-line string which preserves the line breaks. Now we can remove this example from before. Great now we know how to use these template literals. We can put them into practice inside of our projects. Up to our function, which is the repeat random shape, first, we can remove these two console logs because we want to output these to the screen. Then we can create a string to contain our styles. The styles which we want to contain is these sections of the objects. We want the color, we want the width, and also the heights, and we're going to set these as style properties of our shapes. Back down to our function, let's go ahead and do this now. Inside of our set interval, just blow our shape 2 here. I'm going to go ahead and create a new constant. Let's start with shape on. Let's call this shape1Styles. We're going to create a template literal, which is basically going to be a string with all of our styles contains. We can then add the styles to our shapes div, and then this will display on the screen. Let's take a look at this with the backticks. First of all we're going to set the width of our div inside these backticks, we can add the $ symbol and then the curly braces to add our variable. The variable once set to this width, is the value of a width of each object. Back down, let's set this be shape1, which is stored inside this variable here. Shape1.width, and then we need to add the value of pixel on the end. Add plus px, semicolon after this, then we want to add this on the next line so it's more clear. The background this time. Let's add this to our $ symbol, open up the braces, and the background could be shape1.color, semicolon at the end. Then finally the heights. This is going to be equal to our variable inside here, and this is shape1.height, and then again we need to also add onto the end our pixel value. Plus px, semicolon at the end, and make sure these backticks is right at the very end and right at the very start and not after each line. Now we'll have these styles we can apply them to our shapes div. If we go over to our index page, we have an empty div with shape1 and also the shape2. We're going to add these style properties to this div here. First, let's select shape1 using document.getElementById, just select this. Just after here, let's go back over to the start and do a document.getElementById. We want to grab shape1. Then what we're going to do is something which we've looked at earlier. We're going to set the style attribute for this div. We're going to set the cssText to be equal to the string which is created, which is stored in this constant called shape1Styles. Let's add this as our cssText. Shape1Styles with the semicolon at the end. This cssText which we just used here, is not something we've seen yet during this course. This will allow us to pass in a string of styles, just like we created here, stored in a variable called shape1Styles. Now lets check this is working in the browser. If we save this and then reload, we can close the console down and click on play. Great, that's our shape1 div on the left-hand side here. Now we can see all the style properties, such as the color, the height, and width, and now apply in as a style attributes, which we've added just here. Now what we need to do is repeat this for our shape2. Let's copy our shape1 here, and then we could paste this in just below, and then let's move this over to keep it all lined up nicely. Now what we need to do is just change shape1 to be shape2. The same for all these ones inside of here we can change this to be shape2 except for the color and also for the height too, and then just as before we can copy this line of code here, we can also select the document.getElementById. This time we want to select the shape2 div, which is over in the index page, which is this div here. Exactly the same we do style.cssText, and this is going to be equal to shape2Styles. Add a semicolon at the end, and then close the browser, reload and hopefully we should get two random shapes when we click "Play". Great, now these two shapes are on the screen, we now need a way to compare them. And this is what we'll look at in the next video. 39. Comparing objects and scoring: Now we have two random shapes appearing on the screen. We need a way to compare these two shaped objects. When the player clicks on the, Match button, which is just here. To begin, we have a variable at the top, which is called playing, which we set early on in this section, which is also set to false. Inside of All-Star game function, we can change this variable to be true once the game has started. Let's scroll down to our stock aim section, which is just here. Then once the user has clicked on the, Play button, we can then go ahead and set playing to be equal to true. Outside of this function, I'm going to create a new comment, which is compare. Now we can add an event handler to the match button, to trigger a function when clicked. Let's go over your index page and take a look for our match button, which is just here. This has an ID of match, so we can grab this inside of our scripts, so document.getElementById, the Id of match. Then we can use a onclick event handler, trigger a ES6 arrow function. Then inside this function we can add an if statement to check if playing a set to true. Let's say, if the variable of playing, so we can just say if playing, and when this is true, this will then run the code inside the if statement. This basically means the code inside this if statement will only run if the player is clicked, Start. Certainly play any variable to be true. Nested inside we can perform another if statements. This will be used to increase the player's score, if the objects are match. Lets nest a second if statement, just like this. But how do we first compare the objects to check if they're same? For this, we have something called objects.is. This will allow us to pass in and out, to shape variables to compare. Objects.is another new JavaScript feature from ES6 or ES 2015, just like the arrow functions and constant lets, which we looked at before. Inside the brackets here you can say objects, so object.is, and then open up the parentheses just afterwards. Inside here, we can pass in our values we want compare, which you have stored in the variables of shape 1 and also shaped 2. If these two objects inside here, are match, then we can increase the player's score. We have the player's score up at the top, could be set to zero and stored inside this current score variable. Let's increase this. If the object is a match, we've have put the score, plus, plus. Over in the index.html, we also have a span element with the Id of score, which is just here. This will allow us to crop these elements and then increase it with a player's score. We can see this value on the screen. Let's do this now back over to our if statements. If these two objects, are match we'll increase the score by one and then select the document.getElementById, then grab at the span container, which had the ID of score. Set the innerHTML to be equal to a value of current score. Good just blow this. After our if section which you just here, we're going to add our l statements. This l statements will run if the objects not match. This'll be used do the opposite and then take a point off the score. Let's say else, current score, and we'll decrease this by one. Then also do the same line here, so document.getElementById, the Id we want to grab, again is score. Then obtain the inner HTML to be equal to the current score. Then refresh, and let's give this a go, click on the Play button. Now, we need to click this Match button, when these two shapes are the same. Let's wave these to be the same. That goes to the value of 1, 2, 3. This also is working fine. If we click on this when the shapes are not match, we see will lose a point each time. Great, all seems to work in fine. But before we call this complete, there is a few small issues we need to address. First, after the game is started, if we keep on clicking the play button, so let's start the game off. Then if we click this multiple times, this will call the stocking function model months, generating lots of random shapes. Also, when playing the game, we want to restrict the user to only press this match button once per set interval. Currently if the user clicks on it multiple times, the score will keep going backwards or forwards. We want to restrict this to only one click per selection. Let's begin by disabling the stop button, when the game is already running. We can do this in side of the play function. On to our scripts, and let's go to the Star Game section here, which is the click handler. First, we need to grab our play button, which has an id of play, which we can see here. Then back to our Star game function, just under the playing equal true. Let's add a command to say disable the play button, when playing. document.getElementsById, select our Play button, and then we can set.disabled to be equal to true. Let's test this out, and then click Play. We see as soon as you click on play that it turns gray, and we can,t click on this button anymore. If we refresh, now our play button is back to normal, and we can restart a new game. Then we can now move on to stopping the player clicking this match button multiple times. First, let's store this match button inside of a variable. We put it up to the top of our code. Let's set up a constant called match button, and our familiar document.getElementById. The button you want to select has the Id of much, we add a semicolon at the end. I'll start this reference inside of a constant because we're going to be selecting this a multiple times. We're first going to disable the button once it's been clicked, and then reactivate the button once new set interval is being generated. Down to the bottom, we can set this button to be disabled after it's has been clicked. Down inside the compare section, and we'll do this in side of the playing section. Let's say matchbtn.disabled is going to be equal to true. This will disable the button after it has been clicked. Inside of this onclick function, this button there needs to be reactivated for each cycle. So can we re-enable it each time a new shape is generated. Up to the set interval section. Just after here, right at the very top, we can also select matchbtn.disabled, but this time to be false. Let's test this out, refresh the browser, click on, Play. Now our game starts, and if we try and click on the match button multiple times, it only works when a new shape is being generated, so we can only click on it once per selection. Great, this is our game. Now complete. Feel free to go ahead and do any customizations, make any changes, or play around with the speed of the shapes using our set interval value just here, or generally experiment with any new features which you like. I hope you've enjoyed building this game and bye for now. 40. Introduction to regular expressions: Welcome back guys. Now we're going to look at something which is really useful in JavaScript. This is regular expressions. Regular expressions, often shortened to rejects, is a way to find a pattern or combination of characters inside of a text string. For example, if we had a paragraph of text, we could say we wanted to search for double spaces and reduce them to be just one space. All we could search for every word inside of a sentence and then change the first character to be a capital letter. Head over to these starter files. Then inside the sidebar, let's go down to number 32, which is introduction to regular expressions. Inside here we have some simple lorem ipsum start text, which you just stored inside the P elements. Open up this example inside the browser. First we can grab this text elements just here and store it inside of a variable to begin working. Down to our scripts, let's start with the let text equals document dot Query Selector. We want to grab our P elements, which stores our text. At this is seen as a string, and then we want to grab the inner HTML. We can start with the basics and such as text to find the location of a particular word as a string. Just below this, this is a pretty simple one to search for text. All we need to do is say text dot search and then inside the bracket we can add a string which you want to search for. Let's search for any of these words inside of a string. Let's go for, "amet" add this in the quotes, A-M-E-T. Now I'll put this to the console. First let's store this results inside the variable. Let new text equal to our search and then we could do a console log for the value of new text. Give that a save and then over to our example, open up the console and we get the value of 23. This is because the word which we searched for in our text string begins at position 23, which basically means this is 23 positions from the start. Let's comment out this example and take a look at a new one. We'll remove this console log will cut this out and actually just paste it down on the bottom. We can use it with all the examples, above. Now we've looked at finding a string inside of our text. Once we find a match, we often want to replace it with something else. For this we have the replace method. Down on the replace text, we will string. Let's create the same example from before so that new text but this time rather than doing it, text dot search, we can do text dot replace. Replace takes in two different values, the first one we're going to add a string to search for. I'm going to search for lorem which is the first word inside here and then as a second value separated by a comma, we can add a word which you want to replace it with. Let's go for any word of your choosing. What's our chips number? We also have our console log of new text down at the bottom. If we reload the browser and take a look, we now see our first word of lorem has been replaced with chips. This works great, but this is because we've added the word lorem. Just here, we have a capital L. It matches our string. If we could changes this to a lowercase, it wouldn't work. Change it to lowercase L, refresh. I will say the word lorem hasn't been replaced this time. This is because this replace is case sensitive, instead if we want to perform a search, which is case insensitive, we can add our pattern to search for inside of the forward slashes. Back over to our code. Let's copy this line from before. We can leave this example in by commenting this out. We can paste this back in underneath this replace text with a regular expression. Rather than having a text string like this, we're going to create a regular expression inside of two forward slashes. Let's search for our word of lorem then we can add to the I modifier just afterwards. If we save this and then refresh, we see now the word lorem is now replaced with chips, even though the L is lowercase. The word lorem appears only once inside of this text string, but if you wanted to search for something which appears multiple times, such as a simple E character. Let's go ahead and take a look at this, if we copy this example and then comment this out, and then paste this in and below the I modify section. We can see here that the I modifier, we'll do a search which is in case-sensitive, but you will only replace the first match inside of our string. We change lorem to be E, there is multiple occurrences and then replaces with a capital A. Reload the browser. Now we see that only the first occurrence of an E is replaced. There is no more capital A's inside of our string. However, if we want to replace all occurrences, we can use the G modifier this time. Let's copy this line of code here, comment this out, and then paste this under the G modifier. All we need to do is change the I to be a G, reload the browser. Now we see that all occurrences of E has been replaced with a capital A. G stands for Global and will find replace all matches in our text string rather than stopping after the first one. Just like when we use the I modifier. It will only searching for one letter but if we want to match to multiple letters, we can add these inside of square brackets. Let's take a look at this. If we copy this line here and comment this out. Let's leave this in the starter files for future reference, paste this in under the square bracket section and then inside of all forward slashes, we can add some square brackets. Inside these square brackets, if we search for H, G, or S. Let's make these lower case with the G modifier and then let's add something which stands out. Let's add some stars and in capitals will say "REPLACED". When we search through the string, the first occurrence of H, G, or S will then be replaced with the string here. Save this, and then reload and scrolling up, we can see the first occurrence has been replaced with our string here. This also stops after the first match. If we want to replace all occurrences of H, G, or S. We could again add the G modifier. Let's copy this line here, comment this out, and then add this under the G modify section. After our regular expression let's add he G modifier, save this and we can see the all matches have now been replaced. These square brackets also works for numbers too. Let's copy this, comment this out and add this just above our console log inside the square brackets, instead of searching for our letters, let's go for the numbers three through six. This will find all numbers from three through to six, remove the G, and then replace it with this text string here. For this to work, we need to add a number into our text above. Let's go for number five add this in, reload. Let's try and look for it, there we go. There's our texts of replaced in a position of our number five. This is a first look at using regular expressions to match a pattern. If we Google Mozilla regular expressions. You're about, find a lot more examples on this regular expression section. We click on this and then go to the Mozilla documentation. We can see there's lots of different ways to create puns. If we scroll down, some of these regular expressions are quite complex tool. I'm not going to go through all of these since most asked specific use cases. You can find almost any way it match a pattern using regular expressions. In the next video, we're going to build a small project using regular expressions to take the user's inputs and perform a find and replace. 41. RegEx find and replace project: Welcome back guys. In this video, we're going to be using regular expressions, to build a simple find and replace app. Inside the starts files, we have a basic form where the user can type in a word inside the find section. This will and then find a word inside his original text and then we can choose a word to replace it with. Once this Replace button is selected, this Replace button will trigger a function which will make all this happen. Let's begin by adding an event listener to this button. Over in the starter files, this is Number 33 which is rejects, find, replace. Down here we have our form with the find inputs, the replace inputs and then our button, which has the ID of replaceBtn. Let's go down to our script which is down at the very bottom. Let's like this with document.getElementById. The ID like we've just seen is replaceBtn. Then add an event listener. Inside the brackets, we know we need to add two values. The first one is the name of the event. We're going to be listening for the click events. Then we're going to trigger a arrow function just like this. Inside here these four things we need to grab and store inside of variables. We need to grab the form inputs for the find section. We need to grab the input for the replace section and then we need to grab our original text, which is our first set of p elements. Then we need to grab our second p elements, which is going to contain our text with the replaced words. Let's add in these four variables inside of our event listener. Let's start by grabbing our original text and then our modified text inside the p elements. Let original texts be equal to documents.querySelectorAll. The original text is the first occurrence of the p elements. Add the p tag inside here at index position zero. Then lets copy this line and paste it in just below. This one is going to be the modified text. The only difference is the p element is this time at index number one. Now we also need to store the user inputs which has an ID or find and also replace. Lets install these two inside a variables as well. Let our findText be equal to documents.getElementbyId, the first one was find. We want to grab the user's value. We've got value, copy this line and paste it in again just below. This is going to be the replace text. Let's replace text. The ID this time is replaced. Okay, good so make sure yours looks like this example here. Now we have all the information we need stored in variables. Next we need to grab the inner HTML of our original text. This is texturing just here, so at the very bottom of our function, let's say originalText.innerHTML describes all the text content from our original text. Then we're going to use the dot replace method, which we looked at in the last video. This takes in our two values. The first one is the word we want to find. This is stored inside a variable called findText then separated by a comma, the word we want to replace it with. This is stored inside of this replace text variable. Replace text as our second value, the semicolon at the end, then we can install this inside of a variable called newText. Finally, we want to output this newText to our empty p elements which is just here. We already have a reference list called modified text. Let's add this down at the bottom, so modifiedText.innerHTML is going to be equal to this newText just here. Okay, good. I think we're ready to go to the browser and give this a test. Let's search for one of our words. Let's say sits, find the word of sits. Then replace it with stand stand. Hit replace and nothing appears to happen. If we look a little closely and we add this in once more. If we click on this replace button and watch very closely down at the bottom. We can see the briefly the new text will flush up and then disappear. This is because, this part inside of the form elements. When we click on this button, the default behavior is to submit the form. This causes the page to reload. This is also why the inputs are now clear at the top because the page has done a refresh. To fix this, we can prevent the default behavior of this event. First, we can add the e, which is the details of our events, inside of the function parenthesis then we can prevent the default behavior inside the function body with e.preventDefault. This will stop our form from submitting and therefore we won't see a page refresh. Let's try this again. We replace sit with stand, click ''Replace'' and there we go under our new tech section. We see the word sit has been replaced with stand and we no longer see a page reload. There is also another way to fix this too. Instead of having e.preventDefault we can remove this. We can remove our e variable from here and instead, if we go up to the button, inside of our form we can also add the type of button. Now this is a type of button rather than submit. This will stop the default submit action. Now let's give this a go and this time we'll replace Ipsum with any of the words. Hit ''Replace''. Now we got also our new text now has this replaced word. The final thing to look at is how to make this search case insensitive. If we search for the word lorom using these small l and replace it with anything. Hit ''Replaced''. We see that this doesn't work below. You may think we could just add a modifier like this, so down to our new text inside the Find and Replace let's add our two forward slashes and then the I modifiers just like this. However, if we were to say this, refresh and give these a go, type in lorem. Our replacement words, we see that this still does not work. To make this work, we need to use a constructor function, so back over to our scripts. Just a bit of a new text we're going to say, ''New regular expression'' just like this. Then inside these brackets we are going to pass in this find text. Our design as our first value. Separated by a comma we can add the I modifier. This constructor function will compile the results including this modifier and then we could install this inside of a variable. Let's say find, with modifier and set this to our constructor function. Then we can use this variable name and passes in through our replace. Rather than what we have here, let's just pass in a variable name. You have to save and then let's try this, so lorem, with lower case l. Hit Replace and now you see this is working. Great, so this constructor function compiles our runtime which is ideal for patterns which may change. Although we know the pattern we looking for, it may change depending on the case of the letters. Great, we now have a working find and replace up which is case insensitive. Let's now move on to the next video. 42. HTTP, request and response: So far in this course, we've looked mainly at how things work on the front-end. We've built user interfaces, different layouts, looked at responsive design, and also, how to use JavaScript. This is all great and really important that we understand all of this. From this section onwards, we are also going to be looking more at the back-end of websites. How a websites will interact with servers, different data sources, and generally, how they communicate with external sources. When our user interface is communicating with servers or generally requesting any information, there are some concepts we need to know to fully understand what is happening. We don't need to be an expert to go too deep into each one of these concepts. As most come as a topic on their own, but having, at least, a general understanding will really help us understand what is going on. The first concept we're going to look at is the client server model. As you can see here from the slide, over on the left-hand side we have some examples of clients. A client can be a web browser, a phone, or even a terminal on our computer. Basically, the client is the one which makes the requests, such as a requesting any web pages which you want to view. On the right-hand side, we have the server which provides these resources, all the services which the client is requesting, such as our webpage, which it will send back to the client if it has it. When a client makes a request, such as requesting a webpage, this is called a HTTP request. HTTP stands for Hypertext Transfer Protocol. This is the standard or the procedure used when transferring hypertext data across the web. The client goes ahead and makes the request, and then the server will try to respond to that request if possible. It may respond with things such as the HTML required for the webpage, any images, or any scripts which may be needed too. Although this may sound a little complex, it is something which we do each time we visit a web browser. First of all, if we go to the Wikipedia homepage, over at the top, you'll notice that HTTPS is at the beginning. This is like the HTTP we mentioned before. But nowadays, HTTP secure is more commonly used as it provides an encrypted version, a greater security, and privacy. Once we enter a URL and hit "Enter", the web browser, or in our case, the client is now making a request for this webpage. If everything went okay, the server will then respond with the requested page and then display it in the browser. This request response cycle also works the same for other clients too, such as a computer terminal, which is also a client. Let's open up the terminal. Make this a little bit bigger. We'll use a terminal more once we get to the node section of this course and you don't need to follow along with the section if you don't want to. But all I'm going to use is a cURL command, which also makes a HTTP request from the terminal. We do this by typing cURL, and then we can type our URL, just like we looked at before inside the browser. HTTPS:// and then www.wikipedia.org. Then hit "Enter". Then if we scroll up to see a lot of information is being returned back to us. This is all the HTML which is used for the Wikipedia website. A lot of this will look common, such as the divs, our span tags, and all the various classes which are added these. It can't be a little bit difficult to read. This is because a terminal doesn't know how to deal with this HTML which is returned back to us, so it's just displayed as plain text. On the other hand, a web browser knows exactly what to do with this HTML. So if go over to the browser, and right-click and then go to View Page Source, this can also be a little bit hard to read, but this is the same information which is being sent back from the server. The difference being the web browser knows how to deal with this information and how to then convert it into a web page. When we make a HTTP request, there is various request methods we can use. Here we can see four examples called GET, POST, PUT, and DELETE. There is more than these four, but these are common ones to get us started. When we want to get a webpage, or we want to get some data, we can use what's called a GET request. This is what is used in the browser to get our webpage from the server. POST will do the opposite and submit some data to the server for processing, such as adding a new record into a database. Next we have the PUT request. Just like POST, this will also submit some data to the server to process. However, the difference being if this data or the resource already exists on the server, it will go ahead and replace it. This is used commonly for updating some data. The final one is the DELETE and this is pretty self-explanatory. This will delete the resource or the data which we specify. We will use some of these methods during this course, particularly in the final project when interacting with a database. Part of this response from the server is also a status code. There are many different responses, but here are some examples. A code of 200 means the request was successful and the requested resource is sent back to the client's inside the body of the response. Next up we have the 301 response, which is a redirection message. This means the resource which we are trying to request has been moved permanently. We usually get the new URI given with the response. A 401 response means the client is unauthorized, usually requiring authentication before receiving the requested response. 404 is a common one which you may have already seen when browsing the web. This is common when a page cannot be found, such as when a user mistypes a URL. A lot of this may just appear to happen in the background by magic, but we can get a better idea of what is going on inside the developer tools. If we return back to any web page such as Wikipedia, and then right-click, and then inspect, inside here, we can go to the Network tab, just at the top here, and then hit Refresh and then can see we have a lot of different file names which were returned back to us. We have the main page. We have some various JPEG images. We have some scripts, some PNG images and scrolling down, we see all these are returned back to us from the server. We can also see the status code too and most of these are code of 200, which we looked at before. This means the request was successful. If we look at the main page at the top, we can see a status code of 304 for this homepage. This means the page has not been modified since the last request, therefore, the browser can use what is called a cached version. A cache is a temporary storage and browsers will use a cache to store our webpages once we visit them, so they can be accessed faster and also reduce the need to keep making additional server requests. This is why if we go up to the top and click on Disable cache, it reloads. We now see that this main page now has a status code of 200. This means we're now making a fresh request to the server for this webpage, rather than storing it inside the browser for quick access. Now, if we uncheck this and then refresh, we can now see the status code of 304, meaning we're using the stored version inside the browser rather than making a new request. This is an overview of how things work between the client and the server. Even by having just a basic knowledge of these concepts will really help you understand what is going on behind the scenes and really help you as a developer. Next up, we'll be looking at APIs and how we can use them in our websites or applications to get data from external sources. 43. What is an API?: This API part of the course is going to be really exciting section. If you've not worked with any APIs before, or generally any data from external sources. We're going to begin by looking at APIs, and this stands for Application Programming Interface, which sounds really complex but it's just a way for us to connect our websites or application to another data source. It basically defines how our app can talk to other apps and services. Some of the biggest companies out there have an API for developers which we can connect with. For example, we could create our own music application, exactly how we wanted to look. Then use the Spotify API to search for songs or albums, or even access any user data, such as any saved tracks, and then display them right there in our own application. There is also a YouTube API, which we can use the search and display videos inside our own projects. This also provides a way for these companies to allow developers to safely access the data, which they allow. These providers will require registration and also an API key first, before granting access. Just like earlier in the course, we looked at using Google Maps. When we have to register and provide an API key, things to work. How do we access this API data? Well, not all APIs are exactly the same, but generally we make a request to a URL, this is a get request, as we learned about in the last video. Because we want to get some data. This URL is called an endpoints. For example, this is Spotify's API endpoints here at the top. This endpoint is usually extended to be more specific about the data we want to get. For example, we can grab some album information. We can get albums with a specific ID. We can perform searches and even retrieve a user's playlist information. To give you a better idea of how this works, there is a simple API which we can use with information all about types of dogs. Let's head over to the browser and I'm going to go to the dog CEO, which is www.dog.ceo. Then to grab the API would do forward slash dog dash API, hit "Enter." We can see this is the internet biggest collection of open-source dog pictures. Some of this will allow us to search through the dog breeds, search through the pictures, and generally gather information which we want to find. This will give us some examples of the end points we can use to get different dog data. This is useful to start with because we don't need to register or use any API keys to get started. Scrolling down, we can see our endpoints here, which is the first part of the web address which we just visited. Inside the API, we can then filter by breeds and then select the images, and then select a random image, and then we return with some JSON data. If we go to the documentation, we can look at some more examples. The first example we see is the list all breeds. So this is the URL end points you need to visit to grab all these dog breeds in JSON formats. If we click on this, copy, then paste it in the browser. Return back towards it's information in JSON format. If yours looks a little hard to read or doesn't look quite like this, you may need a JSON browser extension to format it into a more readable structure. There's lots of different JSON formats we can use, but I'm using a one called JSON formatter. I'll go to Chrome extension, and then JSON formatter. You can follow along with this link and then add this as a Chrome extension just by clicking on the "Add to Chrome" button at the top. I already have this installed, so I'm just going to close down its tab for now. JSON stands for JavaScript Object Notation and its syntax for exchanging data over the web. It's formatted like a JavaScript objects, but it's actually language independent, meaning it can be created and read by other languages too. Here we can see a object like syntax using these round in curly braces. We also have the name value pairs such as status of success. Then inside this message here we have an object containing all the dog breeds which requested. We can see some of them are just empty objects because there's no data for this particular breed. However, for example, if we scroll down, one such as the bulldog is an array which contains two different types. If we head back over to the API documentation, and then if we go down to breed list, here, we can click on the JSON information for any different type of breed which you want to check out. We can see which images we have associated with these. Let's go on a boxer and click on the "JSON Data". You can see by the URL endpoint at the top with filtering the breed, down by the boxer. Then we'll access the images. We can click on any of these images too, and then see which images are provided. To change the breed, all we need to do is change the URL. Rather than having boxer, let's change this to be something else such as hound. Then we get a list of different images for the hound. Let's try one more. Let's go for labrador. Here's a list of all images for the labradors. This is the JSON format and it's probably the most commonly used type. Some of them which used to be popular for data transfer too was a format called XML. Here is an example of the same data using both JSON on the left and XML on the right. XML is very descriptive using semantic tags, which looks a bit like HTML, you will still often see some API data supplied in XML format. However, most now have a JSON version 2, or even just JSON by itself, a more modern APIs. This is because JSON is a lot shorter and lightweight, as we can see over on the left with the same examples. Now I have some background into what an API is and how we can use the data. Let's now get back to our song find application, which started early on the course. Early we created the user interface. Now we're going to move on to grabbing our API data and showing a list of songs on the screen. 44. Fetching data and query strings: Earlier in the course, we created a HTML structure for our song, find the layout. I also challenged you to add some styling and layout using the CSS grid to make things look even better. In this section, we're going to be completing this project by using an API to pull in some real song data which we can use from iTunes. We'll also be using the JavaScript Fetch API, which will allow us to fetch a resource or in our case, we want to fetch the data from iTunes. Let's begin by opening up our song, find a project from earlier. If you haven't already done so, open up the song final project in Visual Studio Code, and then open up the index page in the browser. In the index.html file, we created some sample data for our songs. We're going to be creating this section dynamically using JavaScript and then grabbing the song data from the iTunes API. We can go ahead and remove the contents of this main section, but we'll just leave one in for reference. Let's go to the index page and then scroll down to the main section with the ID of songs. I'm going to leave in one of these articles and then remove the five extra once in from below, for five right down to the bottom of the closing main sunk, I bring this up. We're left with just one song. Give that save, and refresh the browser. The next step is to create our script file. This is going to be a JavaScript file. Right-click new file and call this the script.js. Then we need to link to this in the index.html, so scroll down to the bottom and just before the closing body tag, let's add our script, closes this off, then add the script source. This is in the same directory, so we can just reference this by script.js. If I save. Now we're ready to get going. Let's head over to the iTunes documentation and take a look at what we're going to be using. Head over to Google. Let's do a search for the iTunes, search API. Let's scroll down. What we need is the iTunes search API, which is on the Apple Developer website. Let's click on this. Let's start by selecting the search from the menu, the cyclic, and then we can click on construct a search. When we discussed APIs in the last video, we mentioned that we usually fetch the data by connecting to a URL, which is called an endpoints. Here we can also see the API endpoints provided by iTunes, which is just here. It's itunes.apple.com, forward slash search. Then after this endpoint, we can add some key value pairs to get the information we want. Notice at the end of this URL is a question mark. This is just a separator to separate the URL from the queries which you want to ask. We'll take a look at these in just a moment. This URL with the parameters on the end is called a query string. If we scroll down, we can see some key value pairs in this table here. Starting with the search term, this is probably the most important for our use. Its term which we are going to be searching for to find our songs from the database. Scrolling down, we can also search by media 2 or we can narrow this down to search for on a music. Or we can even include things such as movies, all podcasts. We can also limit our search too so we don't get too many return values. If we scroll down, we can also see this limit parameter here. I'll also use limit too, so we don't get too many search results returned back to us. To see these working in action, we can simply type these into the browser. Let's go up to the top. Let's copy this URL and then add this in a new tab. Before we press enter, we need to add some key value pairs with the search to work. If you go back to the documentation, we can use any of these key value pairs which looked at before, such as a search term. After the question mark, we can add a term and then equal. Let's go for Beyoncé and I hit enter. Then I have a text file which is downloaded. We can open this up and see the contents. We can be a little bit hard to read at the moment, but we can see at the top we have 50 results returned to us, follow by an array of our results with all the information about each song. If we wanted to limit this, we can then add some extra values. Then paste in our query again the term equal Beyoncé. Then we can add more key value pairs. This query string separated by the ampersand, so add the ampersand here. Then we can use limits, which we also looked at before and set this to free results, hit "Enter". We have a new text file download in. Let's open this up. Now have a result counts of free and a lot less data. We just have free individual tracks inside of the array. To see this more clearly, let's copy all information from our text file, then I close this. Go to Google. Then let's search for code beautify. This is what we need, a codebeautifty.org. Open this up. We're going to use the JSON Viewer to see how this looks. On the left we have the JSON inputs which you can paste in our information from a text file and then we can click on beautify in the middle and see the results on the right-hand side. Click on the cross in the top corner to make this even bigger. Now, we can see more clearly the information which is returned from iTunes. We have the results counts which we've seen before. So we have a result array with free values. This first one is an object which contains all the information about the song. We have some URLs for the artwork and we'll use these in our application. To get the images for each truck, we also have the truck ID of the artist name of Beyoncé. We have a truck name and lots more information about the song. This is all JSON data which we can use in our application. We know how to get this data using the URL. We can now use Fetch to actually bring this data into our project. Let's go back over to Visual Studio Code and then into the script.js about a topic onto access the Fetch API. Then inside of here we pass in the URL, which wants access, so paste in. Whoops, in fact, we need to go back over to iTunes and then copy the API endpoints and paste this in between causations. If we give this a save and then go over to our application, reload the browser. If we refresh, we don't see anything different so far. But we can go ahead and assign this fetch to a variable and see what's happening with a console log. Set a constant called data and set this equal to a fetch. Below this we can console.log. Then that's passing the data, which is the data returned by this fetch, then over to the browser. Then if we right-click in "Inspect" and check this out in the console, so let's refresh, so we can see we have something called a promise returned as a response, which appears to be pending. Before we go into any more detail, let's try one more thing. Just after this console log, let's do a JavaScript set time out, which is going to run the same console log after two seconds. Inside here we can pass in a ES_6 [inaudible] function. Then we can copy this console log, paste this in, add a comma, and we'll run this after 2,000 milliseconds. Give us save and then let's return back to the console and then reload. If we wait two seconds, we now see there is a second promise. But this time it resolved with a response. These results which you see inside the console because of two things. First of all, when using fetch, it will return what is called a promise, and second of all, because the request is what is called asynchronous. Don't worry if you don't understand what either of these concepts mean at the moment, we're going to cover what both of these mean in the next video. 45. Async code and promises: In the last video, we fetched some data using the iTunes API. We outputted the same data twice in a console. One immediately, and then a second one after two seconds. This gave us two different results, which are both Promises. We'll take a look at what these are very soon. The first one we can see had a result of pending and then the later one has a response of resolved. To understand why this is happening in the first place, and why we need promises, we first need to understand what asynchronous code is. Some programming languages, such as PHP are the opposite. PHP is classed as synchronous This means when our code is ready it is read from the top of the file to the bottom. Synchronous code such as PHP will begin on the first line. It will then run this code on the first line and then only move onto the next line when the operation has finished. Basically, the program will stop and wait for the operation to finish before moving on to the next line of code. However, a lot of JavaScript code works asynchronously. Take our fetch for example. If the request for the data takes a long time to return back to us, we'll be blocking the rest of the code from running while we wait for this data to come back. Instead, what will happen is this line of code will still run, and before waiting for the response, will then move on to the next line of the program or script, therefore not blocking the rest of the code. Now we have sent the request for this data. We're expecting a response at sometime in the future. We don't know when this data will be returned back to us, or if the data from iTunes will come back at all. For this case, we have what is called Promises, and this is what returned back to us from before. When we looked at fetch in the last video, we sent off the request for our data. We immediately run a console log and this had the result of pending, which you can see here. This is because the program ran the console log before the data was returned. After waiting two seconds, our data must have been returned because this console log was then resolved. Over to our code in Visual Studio. Let's close this sidebar down. Let's take a look at how we can handle this Promise. First, we are going to remove these console logs and clean up our code, leaving just the fetch at the top. Also we going to remove this constant here, add a semicolon at the end. A promise is just a way to declare what we want to do when the data is eventually returned. When the data has been returned successfully, we run the code inside of.then. Dot then can be chained on the end, just like this. Or to make it more readable, you often see it on its own line. Let's add enter and drop this on to the line below. Then inside of.then, we can add a function which you want to run. I'm going to add a ES6 arrow function, just like this. This works just like functions we have already seen. It takes in the response inside of these parentheses as an argument. Add response inside of here. The name is up to us, but response is fairly descriptive. I'm going to leave it as this. The response is just a HTTP response, therefore, we need to extract the Json data from the response body using the.Json method. Inside of here, say response.Json. Then we can go ahead and return this Json data. Or alternatively, when using arrow functions, if the function only has one statement like in here, we can even remove the return keyword and also the curly braces. Add this onto one line, so we're going to remove the curly braces. We're going to remove the return keyword and then pull this response onto the same line. This will do exactly the same but keep our code a little bit more cleaner. We can also chain as many.then cases onto the end as we like. Then let's add one more, which will run after the first one has finished, and then taking the Json data so we can do something with it. Add a second.then, which takes in a function. Again, this is going to be an ES6 arrow function which takes in the data. This data is passed to it from the line above, which is the extracted Json. Okay. Back down to our function, we can then console log the data from our API, Console.log and then pass in our data. One last thing before we go over to the console, we need to add a search term, so up at the top. Remember from before we need to add a search term, just like we looked at inside the browser. Let's go for Beyonce once more. You can of course change it to be anything which you prefer. Give that, "Save" and then reload the browser. Okay. Now we have our response with the 50 results. We could see returned to us we have a results array with 50 values inside of there. Let's go ahead and open this up and then open up our results. We can see the individual data from each song. Again, just like before when we open this up, we can see all the artists information and also some artwork which we'll get to using in our application soon. If we want to narrow this down and only show the results inside the console, we can say data.results. Give that "Save" and then refresh. Now we just have our 50 results. Then I'm also going to remove this query string from inside of the fetch. Cut this out and then we're going to create a constant called URL. Have in store this query string inside of here. Then all we need to do is pass in the URL as our variable and then refresh and check everything is still working okay. Okay. Great. There's our 50 results, which is the same as before. Everything is still working okay. The.then section of the promise handles what to do when a response is resolved. If we have an error and the response is rejected, we can go ahead and chain a.catch onto the end to handle this outcome. Right at the bottom we can say.catch. This is a function which is going to take in the error, and we'll create this as an ES6 arrow function, which simply does a console log. Then inside here we can say, let's go for request fails, then a comma. Then after here we can pass in our error message like this. If we give that a save. If we reload the browser, we don't see any difference because the request is working. We're not getting any errors passed back to us. However, if we create a typing mistake in the URL, so let's delete the e from there and then reload. We now see our error message has been caught with the.catch statement. This is running our texts of request fails. Then we have our error past the function. Okay. Let's go back to Visual Studio and reinstate our URL, check everything is working fine and we're good to go. Great. We now have our data which we're pulling in from iTunes and in the next video, we'll begin to use this data to create our elements, to display our songs in the browser. 46. Map through results: We now we have the data which we need to create our song listening inside of the main container of the index file. Let's go to the index.html, inside this main section we have left in place one song listening and we can use this as a guide. We're going to be looping through all the results which we get back from our API and then construct a new article section just like this one for each song results. We'll create all these same elements using JavaScript inside of the final debug section of our premise. Therefore, we know we have the data which we need to work with so let's begin by commenting out this console log from the script. Let's go down to here, comment this out and then we can store data.results, inside the constant. Let's copy data.results from here and we set a constant called artists and set this to data.results. Now we can go ahead and use map to loop through each one of these results. Blow here. Again still within the final.end section we're going to return artists, which is our constant just here.map. Now for each result we get we want to construct a new song. To do this we need to create our elements. Back over in the HTML, which we've seen before. First we need to create a article which is a rapper, we need to create an image elements, we need two sets of P elements, one for the artist name and one for the song name. Then we also need to construct a audio player, which is going to play the first 30 seconds of each song. We know how to do is already by using creates elements. Let's begin by doing this now in the script. In side of our map, we can say const. Let's first start with the article, answer this to be document.createElement and the elements we want to create is the article. Let's duplicate this and this one is going to be the artist and this time it's going to be P elements. One little trick when we're creating multiple variables is rather than adding the constants keyword each time, instead we can remove this and just separate these with a comma. Just like that. Then below our artists we can copy this, paste it again and this one is going to be for the song. The song name is also a P element too. Now that's our [inaudible] song, which is going to be import the image, and for this will cause once a image elements just make as img. Now after the image, we also need to create our audio elements. Then finally, we also want to create a source elements and this is going to be the audio source which is passed in to the audio player with the file path of the music we'll want to play. Then for the final one, let's call this audioSource, and this can be source, and with the comma from the ends. Now we have our six elements created using JavaScript and stored inside the constants. We can now set the inner HTML for these text elements. We've got two different text elements here. We want to set the inner HTML. We also want to set the source for the image and audio elements too. Let's do this just below our constants. Now for each results we get back, the information is stored inside this result variable. First of all, let's do a quick console. log and check out the information which is returned back to us and stored inside of results. Get that saved and then over to the console. Now we can see for each song we can open this up and find out all the information which is associated with each song. Starting with the artist we want to grab the artist's name, if we open up this object, we can see the artist's name is stored in a property called artist's name. If I could leave this console. log in just for a moment you may need this soon. Let's begin by selecting the artist, so artists. inner HTML. Inside these P elements we're going to add the name of the artist. We know we can access this with result and then. artist's name, which you've seen inside the console from here. Next up we can also add to the inner HTML for the song name, which again is between the P elements stored inside its constant called song, so song. inner HTML this time is equal to result. If we go back over to the browser we want to grab the song name, so if we scroll down we can see this song name is stored inside of track name. That track name inside here then the image source, so img.source is equal to result. I'm going to grab the artwork associated with the song, so let's go for artworkUrl100, and this relates to the size, so this is a 100 pixels wide. I'm just going to copy this, and paste this in. I mentioned before that we're going to have a audio player and this audio player is going to play a preview, which is the first 30 seconds of the song. We can find this audio preview if we scroll down to preview URL. Scroll down. We have interest here. As this is the link which is passed in from Itunes to the preview which you want to play. We can add this preview URL to the audioSource. Let's do that now, so audioSource and then.source is going to be equal to result as we've seen before. This is preview URL, also when working with HTML audio elements for this to appear on the screen we also need to add the controls attribute too otherwise we won't see anything to click on on the screen. To do this underneath the audioSource we can select the audio player, and then we can use.setAttribute. The name of the attribute we want to add is controls, and this doesn't have a value, so can leave an empty string. Now we can answer these elements to be a child, elements of the article rather just like we have with the example just here, so back over to our script. We need to append our artists, our image, our song and also the audio to be a child of the article. Let's go down. I can also remove this console.log. We have our article stored at the top here, which is in article elements. All these elements are going to be a child of this article. Below here we can say article.appendChild, and then inside here we can start passing our child elements first of all is the image, and let's paste this in three more times. We also want to add to the artist, the song and also the audio elements. Then finally we also need to append the audioSource as a child of the audio elements. Let's select the audio.appendChild, and this is going to be the audioSource. Add this in. Great. Now we have an article with all the child elements inside. We now need to go ahead, and add this article to the main container. The main container is this main section here with the ideal songs and this is going to contain all of our articles, which we have in the results. Back over to our scripts. To do this we need to store all this reference to the main section inside of a constant. Let's do this at the top. Just after our map we can say const, and we can call it song container, and set this to documents.getEementsById, the Id we want to grab was songs, so let's match this up with this section here. Great. Now we'll have the songContainer we just want to add all of these articles to this container, so down to the appendChild section we can select the songContainer again. appendChild, and then pass in each available article. Now if everything has gone well, we should see our song articles for each song returned by the API, get that saved and close this below the browser and there we go we now see our song data from the API. We can also remove our demo one from before that should be this article from inside of here bring this up then reload. Great. Let's see how this is looking inside of the developer Tools. Right-click and inspect. Here we have the main section from before with the Id of songs, if we open up nested inside here we have all of our articles for each song which had been returned from our API. We can open up our article and see all the elements which are added using a pen child. First of all, we have the image, we have the P elements with the artist's name, P elements with the song title and then we have our audio player. If we're opening up nested inside is the audioSource, which we added go back to the script we added this audioSource as the child to the audio elements and that's what we see just here. Also we can see the controls attributes which were added to. If we remove this, let's go back up comment out the setAttributes, and then reload, we can see we don't have any audio players now on the screen. I should move this and add this back in. Good. Congratulations if this is all working for you. You successfully pulled in API data from an external source this is a big part of our projects now done. In the next video, we'll make use of this search bar, so we could type in our search term to allow us to search for different songs, rather than hard coding in a search term into the URL which is going here. 47. Creating our search query: We now have a list of songs displaying on the screen, which is all being pulled in from our API data. At the moment though we're using a static query string, i.e. We typed into the search term in the URL just at the top here. This is not what we want to use. Things will be a lot better if we could type in a search term inside the search bar, inside of a web-page. To do this, let's head over to our scripts.jsfFile and first we need to set a variable to store our search term in. Let's go to the top of the page here. Make little space, and we use a let, I call this term. To begin with, let's set this to be a empty string. Then next stop let's create a function which is going to be responsible for updating the search term each time a user types in the input field. Constant update term and this going to be a ES-6 arrow function and Inside here we can update this search term Let's update a term to be equal to document.getElementByID. The ID wants to grab is this input from the top. Let's go down to our search inputs and it has an ID of search inputs so of course we can use this over in our get element by ID. Let's add search inputs inside here. Just like that and then we want to grab the value by using.value. We're going to go ahead and figure this function very soon when the search button just on here is clicked. But for now we can add an if statement to check if the user has actually entered something inside this inputs. To start with this term, we can add an if statement. Let's check if there is no term. Or the term is equal to an empty string. The user has not entered anything into the inputs. We can add an alert with some text saying, "Please enter a search term o-k." First we are checking if the user has actually entered something. Then we can add a else statement just after this. This else statement is going to run once our user has typed in a search term, will know all the code from below is working and pulling any data which we need. Therefore, we can cut all the way down from our constants of URL. Let's close all this out, right down to the very bottom. Good that with a Command or Control x inside of the curly braces for the else statement, paste this in and let's just indebtedness. Let's make it little bit smaller and intense, all the section from four. Now this is all in, it's on the else section. This should all run when we type in something in the search bar. Now all of our faction of the data are constructing our articles is now in the else section. We now have this search term stored in the variable at the top. We can now pass this into our URL. Remove the term or beyonce from here. We can add our query strings, which was a $ symbol, the curly braces and m plus in our term. For this to work, we need to remove these quotations from the start and end and replacing this with back-ticks. Then finally, to run this function, we need to add an event listener to the button. In our index.html, this is the button which is going to trigger our search. Right down at the bottom of our scripts.js, we can add a constant of search button or search Btn, equal to documents. Our query selector. We want to select the button and then we can add an event listener to the Search button. Search Btn.addeventlistener. We want the listener for a click event and then we want to run the function at the top, which is called update Term, which you just here. Let's pass in update Term as the callback. I think this should now be everything we need to get things working. Go to the browser and we can check this out. Reload and now see our songs have been removed because we don't have a search term, anymore. Let's try adding a search term. Let's go for Ed Sheeran. Let's search. We seem to have a problem somewhere. Let's go back over to the code. In fact, let's check the console and no arrows inside of there let's take a look so go search button, which is triggered and update some URL. In fact, he would just add in the name of the search term, as we done before we need to add a term is equal and I pass this in, just like that, give us save then reload and try this once more, it Search and there we go. There's our results for Ed Sheeran and let's just try one more the search and we can see that there is a problem. We still have the results from Ed Sheeran as before. But if we scroll down, right down to the very end of the Ed Sheeran moons, we can now see that the Queen editions have been added to the end. If you search for more than one thing, the results are added onto the end of the last results rather than replacing what is already there and this is something which will fix in the next video. 48. Improving our search: In the last video, we made great progress by wiring up our search button at the top of our website. We also included a small problem. This is when a second search term is performed, rather than replacing the original results, they added onto the end. This is what we'll be fixing in this video. All of our songs, our child elements of the song container. So we need to check if the container first, has songs. If it does then we need to remove them before researching. So let's get started by moving our song container reference to the top of our script. So let's go back to our script.js. and then if you scroll down to our song container, which is just here, let's cut this out of our map. Then we can paste this at the top of our scripts. Now let's move to the top of our scripts. This will give this variable a global scope. Medium can access it in multiple locations. So now if we scroll down to our else section, which is this section here, before we run our search query. First, let's run a while loop which will check if the song container has a child element. So at the top of the else section here, let's say while song container thoughts first child. So it will check if the song container has any child elements. If it does, you want to go ahead and remove it. So we can say song container, removed child, just like that. Then inside removed child, we need to pass in the song container.firstchild. So as it is a loop it will loop through our song container and each there is a child elements, it will go ahead and remove it and so no child elements are left in the container. Once the container is empty, the code can then move on to doing a new search. So let's give this a go in the browser, give that a save, and then reload. I'll do the same search as before, Ed Sheeran. Okay, so now let's do a second search of Queen. It search and now our Queen results will replace the original search. Great, so let's now finish off this query string by adding in some extra parameters. First by setting the media to be music. So let's go to the URL, which is just here. Then after the question mark, we can say media of music. Don't forget to add an ampersand after this so it also looks for the search term. So this will now restrict the search results to be only music rather than any other media types, such as e-books or movies. Remember, all of these options are available in iTunes documentation, which we looked at earlier. Also, this is your application, so feel free to change it to be a movie search up, a podcast search, or any other type of media which you prefer. Finally, I'm going to restrict the number of search results to the 10. Back to the question mark, then we'll say limit equals 10 at the ampersands, give that a save. Reload the browser, add a search. Give that a go, so now we have 10 results. Hit search and there we go, now we have 10 results, all restricted to the media type of music. Write our song, find the app is almost now complete but there is one final touch we need to add. We passed in the audio to the audio player to give us this song preview. So if we click on this, we now see that the audio preview is working. So this all works fine, but if we click on a second audio preview we see that post songs are now playing at the same time. Instead, what we want is the ability to click on an audio preview and then is to pause any other audio players which you currently playing. This is the last thing we need to take care of. Fourth is application and we'll look at this in the next video. 49. Audio previews, capture and bubbling: Welcome back. In the last video, we mentioned that we want to pause any audio players when we click on a ''New one''. This will avoid multiple previews all playing at the same time. To do this, down at the bottom of our script.js file. Let's go right down to the very bottom. We are going to listen out for the play events on the documents. Rather than addEventListener to one of the single buttons on our audio player. Instead, we're going to add this to the documents. It is because there is multiple play buttons all at the same time. It makes sense to add this to the document rather than each individual button. This will list now if when the playback has begun on audio elements and then it will run function. Let's start by selecting the ''document.addEventListener''. The event listener we want to listen out for is the play events, which will be triggered each time the audio started playing. Then we're going to trigger a function which is going to take in the events. This will be an ES 6 arrow function, which will run each time a audio has played. Inside this function, we first want to store all of our audio elements into a constant. Also a constant called audio. Then set is to document.getElements ByTagName. The type name we want to select is the audio tag. This will select all the audio players on the screen and store them inside a constant called audio. We then want to loop through all these audio instances and check if any are already playing. To do this, we can create a for loop. For going to set the initial value of i to be equal to zero. We want the square root and while i is less than the audio.Length, and then i plus plus. Now inside this loop, we'll want to do, we want to check if the audio player, which is currently playing is equal to the event.target.. Now inside here I'm going to create a if statement. We'll just type this out first and then we'll explain for each path is given. If audio i is not equal to the events, so targets and open up the braces. When we're inside of the browser and we click on ''Play'' on any of the songs. The reference to the audio player, which we've clicked will be available as information inside of the events. We can select this with event.target, which we looked at in the past. Back over in our loop, we checking if each individual audio elements is not equal to the event.target. Therefore we have filtering down the audio players which had not the one which we've clicked. Anything we run inside of the loop will apply to all audio players except the one we want. Any audio players which are currently playing with audio i, we can set.pause. Suppose all audio players, which are not the one we've clicked on. Therefore, only one of these audio players playing at the same time. If we give the save and go over to the browser, it'll reload and perform a search. Click on ''Search'', and I click on any of these. Now, if we click on two of the audio previews, we can see this isn't working just yet. It is to work. The final thing we need to do is add a third parameter to the event listener. Let's go back to our function. Then right down at the very end, is after the final curly brace, let's add a third parameter of true. To understand what this will do. Personally to look at something called event capture and bubbling, you will see a tree-like representation of the path right from the window down to the audio player. Remember early we looked at how we receive a lot of information about the events when it's triggered. Such as the event target, which is looked up before, and even things such as the mouse X and Y position. Well, not only did we receive information about the elements which five events, such as an audio player? We also receive information about all events in the tree. It will too. When the event is triggered, it begins at the top of the tree, at the window objects and creates a path all the way down. This is called the capturing phase. Then it goes all the way back up to the top. And this is called the bubbling phase. For the example we just seen in the project, we touched our event listener to the document for a good reason. If we added this to the individual audio player, we would need a new event listener for each audio player in our project. Adding it to the document works better because we just need to add it once. Then all of the audio plays below it in the tree will notify you because of this events information being passed up and down. First, there is a small problem. Now, some events don't actually bubble. Against it, the play event is one of these which doesn't. To solve this little problem, we've added the value of true as the third parameter here. This will execute the event handler in the capture phase. By default, this is set to false, which executes the event handler in the bubbling phase. As we just mentioned, the play events cannot bubble. Now, we'll have the third value of true. Let's give this a save and then go over to the browser and perform a search. Now let's go ahead and click on two of the ''Audio previews''. Great. Now, we click on a second ''Audio preview''. All of the existing audio players will stop. We can maybe understand this better by logging events to the console. Back to our script. Just under the pause, let's do a console log. That's log the value of the events, which is passed just here. Then over to the browser. Then let's open up the console. Right click "Inspect'', open up the console tab. Then let's click on one of the ''Audio players''. As soon as we file one of the audio players, we can see inside the console we have nine events listeners filed 1,2,3,4,5,6,7,8,9. We get nine because we only get the ones back, which we have not clicked on. Remember, restricted the number of songs returned to us to be 10. We've clicked on ''One'' and then we get the remaining nine in the console. Because we checked in size of the loop. If the current audio player is not the event or target, i e, the one which you've clicked on. If you open up one of these. Back to the console and then click on the little drop down here. We can see, as I mentioned before, that the bubble events is set to false. Therefore, the play event won't bubble. Excellent and Well done for finishing this projects, working with external data sources such as APIs and external databases, which we'll look at soon, really opens up the possibilities of what we can do with our projects. Bye for now, and I will see you in the next section. 50. Thank you: Congratulations on reaching the end of this course. I hope you are now a lot more comfortable using JavaScript and working with API data. We started at the very beginning, taken a look at JavaScript basics, such as FL statements, operators, strings, and variables, then we moved on to how we can manipulate the DOM to add interactivity to our projects, functions, and how we could work with events. We covered arrays, different ways to loop over data and objects, all while reinforcing what we've learned with some fun projects. Finally, we start things off by working with APIs, promises, and fetching data, all while building a strong ,find app or everything you've learned into practice. Remember this is just the third part of this course, so be sure to check out the next part to gain a deeper knowledge and learn everything you need to know to build Fullstack applications. Bye for now, and I will see you in the next part of this course. 51. Follow me on Skillshare!: A huge congratulations from me for reaching the end of this class. I hope you really enjoyed it and gained some knowledge from it. If you've enjoyed this class, make sure you check out the rest of my classes here on Skillshare, and also follow me for any updates and also to be informed of any new classes as they become available. Thank you once again! Good luck and hopefully I'll see you again in a future class.