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

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

Chris Dixon, Web Developer & Online Teacher

Play Speed
  • 0.5x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 2x
51 Lessons (5h 39m)
    • 1. Welcome to the course!

      2:28
    • 2. Download starter files

      1:24
    • 3. Variables, strings and numbers

      9:32
    • 4. Javascript arithmetic and operators

      7:52
    • 5. Alert, prompt and confirm

      9:28
    • 6. If/else statements and comparison

      8:48
    • 7. Nesting if else statements

      3:44
    • 8. Else if and logical operators

      5:06
    • 9. The ternary operator

      5:09
    • 10. The switch statement

      5:27
    • 11. Time to practice: The dragon slayer game

      10:59
    • 12. DOM Manipulation

      16:11
    • 13. Adding and removing elements with Javascript

      11:19
    • 14. Time to practice: adding elements with Javascript

      1:03
    • 15. Javascript functions

      4:44
    • 16. Function arguments

      4:46
    • 17. Scope and hoisting

      10:23
    • 18. Arrow functions

      3:37
    • 19. Javascript events

      10:09
    • 20. The event object

      4:28
    • 21. External Javascript

      2:45
    • 22. Time to practice: pixel to em converter

      1:37
    • 23. Solution: pixel to em converter

      7:20
    • 24. Javascript arrays

      3:35
    • 25. Array methods

      7:30
    • 26. Looping through arrays: forEach

      7:04
    • 27. Looping through arrays: map

      3:31
    • 28. Time to practice: arrays

      1:36
    • 29. Solution- arrays

      3:23
    • 30. For loop

      10:23
    • 31. While loop

      4:13
    • 32. Objects

      8:23
    • 33. Looping through objects

      4:35
    • 34. Object constructor function

      9:18
    • 35. Const and let

      11:13
    • 36. Generating a random shape

      4:27
    • 37. Repeating with setInterval

      4:36
    • 38. Template literals

      8:31
    • 39. Comparing objects and scoring

      9:24
    • 40. Introduction to regular expressions

      9:53
    • 41. RegEx find and replace project

      9:25
    • 42. HTTP, request and response

      9:32
    • 43. What is an API?

      7:43
    • 44. Fetching data and query strings

      9:59
    • 45. Async code and promises

      8:33
    • 46. Map through results

      12:04
    • 47. Creating our search query

      6:37
    • 48. Improving our search

      4:49
    • 49. Audio previews, capture and bubbling

      8:38
    • 50. Thank you

      1:13
    • 51. Follow me on Skillshare!

      0:23
30 students are watching this class

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!

Transcripts

1. Welcome to the course!: Welcome to full stack Web developments for beginners is courses designed to take you from a beginner to a Web developer capable of not only building front end user interfaces of websites but also design and build the back end to interact with two. So who My my name is Chris on? I will be on stricter for this course I'm Web developer and also the producer of lots off tutorials teaching thousands of students. The skills they need to build websites on applications is cause is the third part in the full series where we will continue to build on everything from the 1st 2 parts of this course. This course is all about jobs, scripts, AP eyes on working with external dates sources. We begin by looking at Jost Basics on flow control. This will give you an introduction to the basics off the job script programming language, including rounded things off with a Dragon Slayer project. Then we continue our jobs journey by looking out dom manipulation functions and events and then finishing off the section. We have another mini project to give you some more practice with their move onto loops, Arrays objects on regular expressions Don't worry if you were unsure of what all this means is yet we look over everything you need to know and then build a fun shape much a game. See how it all fits together with finished off its course by building a song. Find application. It is where things really begin to get interest in, as because AP eyes on fetching data from external sources. You will connect city iTunes Library, the search for some data which we can go ahead and use in our projects. We also even look at some next generation jobs. Good features from here, six on beyond all, while explain things in a straightforward, simple to understand way which even beginners will understand along would reinforce in things with some fun yet challenging projects along the way. I hope you all excited to learn about job script on AP eyes in the third part off this course 2. Download starter files: Welcome back, I. So, as you already know, this is the third part in the series. It's not essential that the 1st 2 parts are completed before continuing with this course. You can just come straight in if you just want to learn about job script on AP eyes. However, if you have not completed the early sections, something you will need to progress for. This course is the start of files for the song Find application. If you go to the class on click on, your project is here later on. In the course one begin to work with AP. Eyes will have the song finder dot zip, HTML and CSS Order created from the earlier sections of the course. If you have not already completed these, just simply download this hey HTML and CSS Starter, and then you can continue with the course as normal. Have you taken the earlier part or not? You will also need the jobs group started files on these will include all the hatred ill on CSS to get a started would learn in JavaScript. This will say it was creating the JavaScript skeleton structures or each individual lesson so we can dive straight in tow. Learn in our job script. So go ahead and download the files, which you need. And then let's move on to learning all about JavaScript. 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 jobs, good cars to offer. The first concept is called dates Types. States types are pretty Simple as it sounds, is the type of data which we use him to begin. I've opened up the job script started files on number one, which is variables, strings and numbers, and then open up the index page, both in a text editor on also over inside the browser. In this video, we're going to look at two of these dates times, and these are strings and numbers. A string is just some text, such as a name on the number is, as you have guessed, a number which is positive or negative, such as a user's age. Also, we need a way to stall these values, too. This is where variables come in. I'm going to go over to chrome and open up the console would right, click and then inspect. Then, if we go to this console tub, which is just here, this is the consul where you can run some child scripts. As always, if you using a different browser. All major browsers have a consul to You can usually find this console from the menu often under the developer tools. We have already seen the elements top and also took a brief look at the network top two. This time, though, we're going to be using this console to begin. We create a variable by using the var keyword. That's a scrolling. So you can see this a little bit better, So type in the var. Keyword. The variable is simply a place to store our data, such as a string on number. Well, then give this variable the name. So if we wanted to store use his name, we could simply stole the name like this. Some of our name equals Chris. So this equal symbol assigns this value to this variable name of Chris. And then we're and this would a semicolon strings need to be surrounded in quote. This could be even a single quotes, which is just like this, all double quotes like we've used here. And then he answer to call this in the console will just take the name of all variable. So if a type of name would then get returned the volume of Chris So we see some arrows on the left hand side. The right arrow is an input which would put in. So we've added the name of Chris and then return back towards. We have the value of Chris. If you wanted to change the value of this variable weaken, do what's called reassignment. We just call available name just like this without the var keyword on. Set it to a new volume with the equal symbol. So looking at the new names such as Chris Dixon and then it's semicolon at the ends. And here answer. And now we get returned back towards the value of Chris Dixon again. If we just call name Enter, we'll get his finally return that once more we can create a Zeman E valuables as we need to . So Charles, at age two, again using of our key word, we said the name of age and said this food value off 34. When working with numbers, we don't surround the value in quotes, just like we did with string. We just simply type the number like this, then hits. Answer. If we call our age veritable by typing in age with then get returned the value of 34. Sometimes you see undefined to just like we're seeing here, such as when we set a valuable This is just because nothing is returned. In this case, we just simply set in or a sign in this variable. So we have our name and age variables declared. But how come, you know, use this well, we could do something like adding them to a sentence. So if we declare a new variable called Joint well, consider this equal to a string. So my name is and in outer space, And now we're gonna add a plus symbol, toe art. And if into the end of this, I'm going to add are available off name So this will be my name is and then Chris and of a plus symbol art a second string looking at Andi I, um, in the space and then at our age, veritable onto the end. So this should print out. My name is Chris Andi. I am 34. Joining strings and vegetables like this with the plus symbol is also called concatenation or Concord's for short. But that's just a fancy term for joining these together and then hit Enter a Number can Type in joins, which still available name. And now, as the bow string, which we expected. Job script is also the default scripting language for all Major browses. So this is why all works fine inside the console. But more realistically, we want to add to the cold over internal project. If we go over to our started files again in our 1st 1 which is variables, strings and numbers we could get to work out in this insider here. You don't need to use these started files if you prefer, but it would just say was typing all the hate mail structure we need each time it will also behind the for future reference to job script could be added even the head or the body section. It's often preferred to add it to the bottom off the body section just before the close and talk. This means that below did last and not block the rest of the hate schimmel from Loadem. The job script is placed inside off script tugs, so let's open up the opening and closing script. OG A number can go ahead with the audience all cold inside, just like we did inside the console. So just like we did before, we can aren't available of name equals Chris Answer. Display this in the console weaken. Do a console log and then inside the brackets weaken art over variable name. So save that's clear the console and be load. And there's our value off Chris looking, then reassigned this name just like we did inside the console again, this time without the variable and then changes to be my full name. The game was on console log of the same name. Variable reload and there's a reassigned name. And then let's do the age next So far, age equals 34 and now you can also do. I was same string that we did inside the console off joined so we can set this equal to my name is the Space Democrat Arts are available name. So just with my name is Chris and then the string off and I am the space and then out on the end the age available with this chemical on at the end. Then we can console. Don't log our new string off joint over to the console reload. And there we go says I was string, which includes our variables of our name and age. We said earlier that we can use double or single quotes, one working with strings. There is a case. So when we need to be careful, if we change our quotes to be single, is that a single of the start on the end of this string and then also replace these two here? So now all over strings, a single save and then refresh. We see this still works perfectly fine. The problem arises when we want to use one of these same quote in our text. So 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 era. This is because our quotations and no long impairs on things a little bit mixed up. Fixing this is pretty straightforward, only to do with surround the section in the opposite type of quote. So here, rather than having the free single quotes, let's change the surrounding ones to be double just like that. So What? Could you just change this section here? All can change all of these single ones to be doubles. Except the one that we want here. Even way will work. Fine, save and then reload. And now old string works perfectly fine with the apostrophe here. So this is just something to be aware of when using quotations? I don't know. We'll move on to the next video. We'll take a look at JavaScript, arithmetic and operators. 4. Javascript arithmetic and operators: in the last video, we were introduced numbers in job, script by store. No age into a variable. But it's so much more we can do with these numbers, though. Let's head over to the console on CDs 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 are subtraction, multiplication addition on division. So inside here we can simply state 10. Take away five and then returns. We get the value or five. We can go ahead and do. 34. Onda Multiplication is the star single, so 1st 4 multiplied by seven on. That's a value of 238. Addition is a plus symbol, which we've seen before, so 12 at six, he's 18. If you want to divide in JavaScript, it's the forward slash so free divided by free gives us a value of one. Let's try a number 12 divided by four, which is free. We also have module is which is a percent symbol. Let's to 12% and then free module is is the remainder, which is left over after divide him. So free goes into 12 equally. So there's nothing left over the same if we do 12 and then full four goes into 12 3 times with nothing left over. So the value is zero. However it would changes to be 13 and then free Free will go into 13 4 times making 12 we'd warn left over. This is why we get the value of born just here. All these additions, subtractions, multiplication ins, divisions on also module ISS a role what we called arithmetic operators. There are more operators to in JavaScript on Look over these two. As we go through this course, these operators can also be used for values stored in variables to let's go over to our start a file into number two, which is arithmetic and operators. Let's close this down, open up our second index page on Also, open this up in the browser. So I'm just going to copy the path from here and then paste this in to the browser. So first, let's look at some arithmetic operators inside of all code editor. So just here we can see all the operators which will have inside of a comment. So let's societies to some valuables, it's available. So, let's say, left school on the age of 16. Them cassettes our age. So my age is 34. The number could do some calculations to work out how many years since we have to go. So let's create a new variable called years since school, the number consent this to our age. So my age is 34. Take away the number of years since we left school, which is stored inside this valuable, So this will translate to 34. Take away 16. Let's check this out with a console log, just like we did before to a consul dot log A number compassion, a variable off years since school. And now the council should do this calculation photos. So refresh. Uh, we got a spelling mistake there. So console that log refresh. So it's 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 of value off free numbers just like this, let's stroll down on well, other comments, so order off operation. Let's start a number such as 10 plus 10 multiplied by two. Then let's do a second console log. We can look to the console, the value off number say that reload. We get the value of 30. So if you go back and look at our number, we may expect the calculation to be run from left to right. So templates 10 is 20 multiplied by two is 40. In fact, what happens is a multiplication happens first, so 10 multiplied by two. He's 20 and then the 10 is added on giving us a volley or 30. And this is the value which you see over the console just here. This is because multiplication on also division have a higher precedence than subtraction or addition. If you wanted to change his soldier 10 plus 10 happens. First, we can rough thes inside of rockets, also called parentheses. Just like this, these brackets will make sure that this calculation is performed first, so this will be 20 multiplied by two. Give us a value of four C. Let's check this out in a console by refreshing, and there's a value off 40. It's worth noting, too, that if all of the operators had equal presidents. 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 multiplication Z and so on were called operators. There is also to more operators available tours called increments on detriments. Let's give this a go for now. Comment, Alice, console log with the two forward slashes on Also this one here to give us a clear console below this, we're going to create a new section on This is for increments on detriment. So now we know that this number variable is a value of 40. If we go ahead and our number plus plus just like this, this would increments the value by one each time. So if we say this and go over to the console with a consul, log off the number, they should know increments the value of 40 to be 41. If we were to go ahead and increment this again, we have number plus plus. This should not 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 de Crimmins, which, as you may have guessed, will reduce the value by warn each time I'm a notice with the negative symbols, just like that on reload, and now our initial value of 40 is now reduced to 39. This is a common thing to do for increasing a place golf, for example, or increase in the number of items in a shopping basket. So 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 all things on D Begin June development. It's not intended as a way to communicate with users off our websites or apps. However, there are some ways Baltimore precise some more methods we can use to communicate with the user. The first of these is and alert on Alert is used to pop up on alert box of the user. The lots of kind of like a pop up box with some information on an O. K button to click on to close this pop up, but its most basic weaken simply, I'll put something to the user. So let's go. Oh, to our script Inside of old Starts a file. Let's go to number free alert, prompt, unconfirmed. And open this up and I'm going to copy the path and then paste is inside the browser. Or you can simply double click on the index file inside the folder. So down under the alert comment here, which is going to support a alert papo. And then inside here we can do anything we want, such as a calculation. So 10 modelers and then free. Give that save an open of 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 text. Also, instead of a calculation. Remember that text strings have the quotations, so let's say hello refresh And there's our text just here. This alert can even contain valuables to, such as our name example from before. So we had a variable off name equals Chris. We could go ahead and add this to the end of all string. So hello, plus so valuable name. Say that and there goes. There's Hello, Chris Inside the alert. If we go ahead and add even more text toe alert, let's are some more text just after this, let's say please, looking in to continue, Say that's and reload by default all these days on the war in a single line, we can break this onto a new line using a backslash and then an end. So inside of our string here that's on the box lush and then the end. This box slash, followed by an end, may look a little unusual, but we'll cover what this is, and also some similar ones later when we look at regular expressions. So for now, let's give that save reload. And now is a line break just after this end, the next one I want to show you is prompt. This will pop up on prompt the user for some input. So let's go on comments these two out with the forward slashes and then go down to this prom section. Let's begin with a simple problems, which is the name of problems and then the brackets. Just after inside here we can add a text string. So hello, What is your name but a question mark? So Index Page And this is how a prompt looks. By default. We'll get the text, which were idea just here. And then we got an input section where the user can type in some information, it's gonna be canceled or click on OK, if we enter our names such as Chris, insider here and then press OK, nothing appears to happen. This is because we need a way to store the uses input. We already know we can do this by using available. So let's said this problems to equal to available. Let's save our name equals problems. And then to see this in action, we can do a council log and then look the value off our name. So just to recap were prompting the user to import their name with installing this import inside of a variable called name and then displaying this inside the console. Let's say that on. Try this out. So say, Chris. Okay, right, click and inspect. Open the console and there's our value of Chris. Let's try one more. Just type in anything inside of here, okay? And there's the value stored inside this name valuable. This prompted returns the value entered by the user like we've just seen all we can select council. So if I click council born here, well, then get the value off. No returned. You will often come across both know on defines they both generally mean something is missing. Both Nolan undefined also considered dates types, too, just like number and string which have already seen. Let's go over to our text editor on creating alert. Let's welcome the new user with the text of welcome space. Ah, our variable name and then ours. A string at the very end words an exclamation mark. If we say that reload, we cannot own name, it's OK and there's our text string or welcome Chris with the exclamation at the end. If we reload the browser and instead hit cancel, we'll get the words welcome. No, no refers to a blank object reference. It may not make too much sense of the moment because we've no looked about. Objects are yet what it generally means. Something is missing. So 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 available is empty. So if we go ahead and create a new available, 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. So as our initial alerts, let's council this and then we get our second alert, which say's undefined, and this is the value off undefined variable here. Next, we want to take a look at something similar to prompt, so that's common. Tell these free lines here. If using visual studio code command and forward slash will comment our or lines together. So now let's go down to confirm. So just under here we can take a look at how a confirm is used, just like the 1st 2 were. Type in the name and then the brackets. Just afterwards, let's begin by adding in a text ring. So you must the over 16 to answer, Let's say please confirm and then over the browser. Close this down from before reload and there's a text that we see here. We also have a council andan. OK, boon. So let's click on the council on also. Okay, so nothing appears to happen when you click on these bonds. Since confirmed has no input field, it will return true if the user clicks. Okay, Awful. If the council Belin is selected looking again series by setting this to a variable. So let's save the age equals of confirm, then a console log which passes in our age variable. Then let's check this out. Open up the console, click on the console tab, so let's reload. So if you click on OK, well, get the value of true. Then if you click on council will get the value of false this true or false value is also another important JOHRJ group dates Type, which is called 1,000,000,000 billions, is 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 uses over 16 we can let them view the page or if the uses logged in, we can let them see the admin section to help decide what to do. In these cases, we have conditional statements on this is what will 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 in action based on if the value is true or false. To do this, we have conditional statements. For example, if a player's health is zero or less, the play will lose a life. If a player collect 200 coins they're makin as 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. So basically thes conditional statements allow us to decide what we want. So we're called to do under different circumstances. A common type of conditional statements is, if else, let's begin with the If section this basically say's if something is true, then run this code so over to our started file. Let's open up before, which is if else in comparison. And then I'm going to open this up inside the browser, then down sore script section. We can begin to create any statement, so add that if key words followed by the brackets or parentheses and then we had a set off curly braces where we can add a code that we want to run. Let's say we want to aren't on alert for all message. We needs either condition where want is alert to run. So inside of these brackets here we are out of condition. So we say of 10 is greater than five. Then run this alert. And it's not some text saying turn is greater than five. So if this is true, it's a little bit run. If this wasn't true that we wouldn't get anything happening at all, so saved us reload. And there's our alert, saying 10 is greater than five. This greater than symbol is a comparison operator, and there's lots more canoes such as the less sun symbol. So now 10 is not less than five, so this will be falls, meaning if you go to the browser and refresh, This statement is now false, so we won't see the alert. This is because, as we mentioned before, the cold will only run. If the condition is true. We can also combine these greater than and less than symbols with the equals operated to. For example, it would changes to be 10 on it were to say if 10 is greater than 10 and do this alert refresh. We don't see the alert because 10 is not grace in 10. However, if you want to run a track to see if 10 is equal to the whole greats is on. We can combine them just like this. So great to Donald Equal, Teoh. And now our conditions should not be true. And then we see the alert. This also works with less son too, as you would expect so if 10 is less than or equal to, then it ruined the alert. So this may be confusing at first because you've already used this equal symbol to a sign of value to a variable. So before we don't think such ours forex equals five. So he would assign in the value of five to this X with the equal symbol. Instead, when comparing, we used the double equals. So we can say if X is equal to 10 then alert the value of true. So save that refresh. And of course, we don't get the alert popping up because X is not equal to tempt. We can also add an exclamation mark to do the opposite, so an exclamation and then equals. So if X is not equal to 10 we should now get the alert popping up. Let's try something else. If we are a number, so are you. Have the value of X equal. Five. If you had a second variable of why on this time, if we set the number inside the quotations just like this, this will be now considered a string because it's insider quotations. We can check this out if we do a console log for each valuable. So let's do a console log just below. You could say type off and then X save that. And now if we open up the console, we should now see what type off data is contained inside of X. So we see the X is a number which would expect because we've declared that just here. However, if we go ahead and changes to be, why refresh and I will see the dates type is string because this is added inside the quotations. So now with this knowledge, let's see how this effects all competition. So let's go ahead and compare the valuable why, which is a string 25 So save So this is a string and this is number. So in theory they shouldn't work. So refresh. I always still see the pop up. So this is evaluating is true, even though it's comparing the number to a string. This is because the double equals will only check the value rather than the data type. If you want this comparison to be even more strict, un also check if the value as well as the dates type is equal. We can go ahead and changes to be triple equals. Say that reload. And now we don't see the popular because the data type is not equal. Let's try the sweet X on X is a number, so we're comparing. If X is equal to five, both in value on also dates. Type is, of course, it should be true. I want to see the pop up true. So this works because X is equal type on value to five. However, we could also add an exclamation mark, and the two equals and niece will do exactly the opposite. So now this will only run the alert. If X is not equal type on value to five so for saving reload, we don't see the alert anymore. Great. This is how we can use comparison operators on the really useful when combined with the statements, as we've just seen, if statement will run its from cold is true. But what if one alternative to run if some cold is not true? But this one needs art? A second condition called else so. Let's delete this example from before and creating new variable cold hungry aren't initially said this to be true. And then we can say if hungry. Then inside the quotations weaken alert. Get some food just like that. So if we just under variable name like this, this will check if the variable is true and then if it is, it will run some code. It's let's save refresh, and there's a text off. Get some food. However, if wanted an alternative, we can also add else and the second, the block of code. We'll run an alert. If the condition is false this time, let's say maybe later. So now if we change hungry to be false, this statement is now false. So therefore this cold one run well instead to the else Damon will run alert in maybe later . Let's try to Cinderella za refresh and there's all text of maybe later. That's try this once more my changing the spark to true. Now we get to get some food. These, if else statements really are a fundamental part of job script on also programming in general. So if you still a little unsure, I would recommend Goldbach for this video to better understand how they work. Although you will get lots more practice for all this section next week on steak things even further by nest in these statements together. 7. Nesting if else statements: that's head over to our started files and into our nest in conditional statement section. Here in our last example, was a simple if else, to check if the condition is true. So we checked if the variable of hungry was set to true. If it waas, we alerted the text of Get some food. Otherwise we'll get the text off, maybe later. Sometimes we may want to check if more than one condition is true if all running on a code . But this weaken nest, our If else statements deceives induction, I'm going to aren't a second variable, so that's not a second variable off craving. I don't want to set this to pizza, then inside off this first. If section I'm going to nest in a second statement, let's make some space to make this more clear. So we'll say if craving is equal to pizza number Canal, it'll block of cold to say alert. Give me a pizza now. We can also remove this alert from here to so first we check in. If the condition is true by checking if the person is hungry. If it's true, it will also do a second that check to see if the craven is equal to pizza and then it will say, Give me pizza else. We'll get the text off, maybe later. So let's say that on open this up in the browser and the refresh and there's a text off. Give me pizza. But what if the first condition was true off hungry, but we weren't craving pizza. So let's change this variable to you. Something else, such as Chinese say that and then refresh so we don't see any alerts. This is because alot hungry is set to true. Craving is no longer set to pizza. Therefore it's alert won't run for this case. Well can also bride a l statement which is also nested inside of here. So else and then inside this block, we can poor a alert with the text off. Let's get some food. I remember if he wanted art an apostrophe in like this. This single quotation is the same as the two outers. So would need to change is to be double quotations but is to work so we give that save and then if we go over to the browser and then reload, we'll get the text off. Let's get some food. This is because this if statement is originally true. So therefore it will move on to the 2nd 1 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 prints all the tax off. Let's get some food. Ondas expected If we change hungry to be false, this if statement won't run it all instead, the else statement will run on. We'll get the text off, maybe later. So this is how we can nest. If else statements inside of us, we can go even further and nest inside of this east. Ayman too, but generally would don't want to go too deep because this makes over cold, more complex and unreadable on. There's often more elegant solutions to this. This is how we can nest. Our conditional statements on excerpt will 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 for case we can use, called else if we use else if to check a new condition. If the first condition is false on, you can use it like this. So inside of our nested fl statement, I'm going to art and else if statements. So just after this open and set of curly braces, missile else if and then open and close and new set of curly braces pushing the last L statement to the end inside here we can add some more brackets to check if the 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 on to 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 off else if will then run on this time, Weaken due on alert. Let's say this time give me Chinese just like that on If pizza or Chinese is not the value of craving. This l statements will ruin at the end, saying, Let's get some food So save that's so. Now we're craving is Chinese. We should now see the text off. Give me Chinese. Let's try a few more options. If we changes to pizza, we get pizza on if we changes to be something different. So that's a chicken refresh. We have a four back saying and let's get on food. Also, just to be clear, we have this else if block nested inside this s statements, but it works 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. Birthday is simply and or not. So let's come and tell this example and take a look at these so comments out all the code from before. Even in the two valuables, let's say if hungry and then on would it to Ambersons. Craving is pizza. Then we can add, I were 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 on also, if craving is equals pizza, let's changes to pizza on. See what happens. Refresh, and there's our alert. If it closes down and change Eva one of these before us, we don't see the alert pop off. Let's try the way rounds. Let's changes to beach again and again. Both of these conditions need to be true for this cold to run. If we only want one of these conditions to be true. So, for example, if we're hungry or craving a certain food Denmark and run this code So rather than both these conditions needing to be true, we can run this code if only one evaluates to true. We can do this with the or operator, which is the two pipes just like that. And now we only have one of these conditions evaluated to true, which is hungry. So save, refresh. And now the alert works. So look at Andi on or the last one I want to show you is the not operator on. This is the exclamation mark which were locked earlier. We looked at this using the S statements to check if something is not equal. So let's take this or section off the end of here even hungry. Then you can add an exclamation mark. Insider here. So if not hungry or if this means falls, then we'll get the alert. So first of all, let's save and then refresh on. We don't see anything. However, if we changes to be falls and then run the code would now see the alert. So this basically does the opposite. So here was saying if not hungry, which is false. Then run this code insider here. So this is it now for if else on also else if along with logical operators, hope that makes sense and not too overwhelming. Remember, a lot of this just takes practice. I will get a lot more as you progress through this course. 9. The ternary operator: Another type of conditional statement is called the turn re operator. So make sure you're in number seven, which is eternally operator started file, and I wouldn't get to work in the script section below. The tannery operator is often used as a shorter alternative to the if else statement. It's also a one line statement so it can look a little simpler, too. We begin by adding a condition we want to check. So she has a calculation. So we say 10 is greater than five. The condition is and followed by the question mark. Then we declare what we want to happen if the result is true or false. So the first statements is true. Separated by a colon on the 2nd 1 is false. So what we're saying here is, if 10 is great in a five, the 1st 1 is print the text of True. The 2nd 1 is simply print the text of false. If we say this in an open of this file in the browser refresh, we don't see anything happen at first. This is because we need to all ports the answer, such as a consul long. So before this, let's are the console dot log and then inside the brackets weaken. Aren't this full turn the operator Now. If we save, refresh and then open up the council, click on the council tab and there we got the text off. True, because 10 is greater than five if we join. Just to be 10 is less than five with then get the second option of false. Let's try this and there's false inside. The browser later will 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. So let's go back over, Let's say, and that's other were variable off, hungry on small Aun said. This to be a 1,000,000,000 volley off. True, let's remove this console log never could save our should I eat and then we can set this to our turn operator. So the condition we want to check is if hungry. So if this folly was true, where the question mark and then are there were two options. If it's true, will say yes. Let's eat separate by a coal on If it's false, will say not just yet at a semicolon at the end of their And then you can do a console log and then log the results off. Should I eat. So just a recap. We'll check in this variable here if it's true or false. If it's true, footprints in the text off. Yes, let's eat. If this was set to be false, would then get the second value of not just yet. This result is installed inside the variable called Should I eat on? This is a value which would display in inside the console. So to the council now this is set to true. So we get yes, let's eat. If this was false, not just gets there's lots more uses for this to such as constructing a text string with outcome. So if we were to go ahead and say variable is locked in and we'll set this initially to be a value of false, then we can go ahead on a text string off Hello with a space and then inside the brackets weaken ardour, turn the operator. So first, we're going to check our condition offer logged in the question mark and then our two options first of all. If this is true work and then it's a welcome buck separated by a colon, we aren't able false condition. We can say please log into your account like the chemical at the very end. And now we need a way to display this to the user so we can surround this whole section inside of an alert than the brackets at the very start and then it closes. Alert off, right at the very end with a closing bracket. There we go to make sure we have the two brackets at the end, one for the alert on the 2nd 1 for this logged in section, give that save Reload. First we get the text saying Hello. Please log into your account because we're not logged in. However, if we said this to be a value of true, therefore we looked in reload. I will get the message off. Hello, Welcome back. This turn. The operator is really simple to use on also a good alternative to the if else statement. It's also a little bit more compact on McCann on this all on my mind to know on the show another code, but also make it more readable 10. The switch statement: Welcome back for this video head over to Section eight off I was started files, which is for the switch statements. This is the final type of conditional statements, which we're going to cover in a way. Switch does a similar job today if else statements. We've already looked up, but the difference is we can check against his many conditions as we want. Then we are the brake statement to break out the switch. Once a match is found, let's give this a try, you know, switch Simon section of the starter code. So down in between the script, let's begin again were available. Someone set this. Be food on. Discover any food once. Let's start weight eggs with, then create a switch. Statements on the syntax is similar to the if statements inside of the brackets. We aren't the condition that we want to test against. We want to check the food variable. So inside the switch time working our various cases to check if they march this food valuable. So, first of all, let's aren't a case, so we'll say pizza. So this checks if pizza much is is variable if it does, whereas the colon a normal could declare on the next line will want to do so. That's simply to a console log. And then we'll say Pizza is awesome just like that. And then we can argue the break keyword. We aren't break to break out with a switch statements. If this is a much if it's not it that moves on to the next case. Flights out a new case here, a number contract, a second condition. Let's say eggs. If this is a much we don't want to do a console log to display the message off. Eggs are awesome. Then what are the break keyword again Just afterwards, let's add one more case on this time. Will our bacon colon and then a console look and that's a bacon is awesome. And then, once more, break out with statements. Okay, so that's I was switched Damon's altogether there, So just a recap work rating invariable called eggs. What, and checking for much is inside a switch statements. So if the case of pizza is a much with them, print all the text off pizza is awesome. If it is with them, break out with a statement on we don't check any of the extra cases below. If it's not a much which isn't in this case, then it moves down to eggs and then displays a text off. Eggs are awesome, but this time, because the march will will break out of the switch statement. Therefore, it won't even check this next one. So let's give that save and reload the browser. Open up the console and there we go. So eggs much. Therefore we get the text off. Eggs are awesome, but what do we do if none of these cases are much for this, we aren't a default, which actors a fall buck, so right at the very bottom, going to add a default. And then just after this, we can aren't a console log, no for the text. Let's say I love in outer space American onto the name of all food with semicolon at the end. Say that and then reload the browser. We still got the text off. Eggs are awesome because we have a much, however, if we go up and change this food to be anything else, such as cheese, which won't much any of these free cases. Therefore, the default will kick in reload and never go. So we got a text of I Love and then we're passing the variable or food, which is cheese. Notre. In this default case, we've left on the break keywords because it's at the end of the switch statement. We can argue this default anywhere we want. But remember toe also use a break if it's not at the very end. We can also change things around a little, too. If we wanted the same outcome for multiple Katie's, we could just combine them like this. So let's say after pizza, what can I add? A second case? Let's go for pasta game with the colon afterwards. So now if the case off food much is pizza or pasta, we can then say I love Italian, so save. Let's keep it, says cheese. For now, we get the full Bach, and if we changes to be pasta reload. I love Italian, then pizza. We still get. I love to tell you we switch statements. We can also go on with as many cases as we want. No, it's time to move on, to build in a little game, to put the things we have learned in this section into practice 11. Time to practice: The dragon slayer game: we know 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. It will be pretty simple, but it will get us thinking about what we want to do next. Based on the condition when the first finish, the page on this is the finished project were first asked our name working and answered our name and then click. Ok, then we move on to our next green where were asked if you would like to play with that one name inside the string if the council will get a text off, maybe next time. However, if we reload the game, I would name look OK And then we say, Would you like to play and click on OK would then move on to being asked if we'd like to bottle the dragon again. If we cancel will get a message or come back when you're brave enough. However, if were to go through and play the game at our name would you like to play? Yes. Would you like to bottle the dragon click? OK, we then have a random chance of what will be the dragon. So this time we've defeated the drug in because we compared this to a random number which determines if we win or lose. So it is a 50 50 chance what this message will be. Let's give this one more go. If we refresh. I don't name a naked crew. This time it's a is we've lost so you can get this ago if you feel comfortable doing so on . That would really included 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 us up if you want to. Otherwise, I'm going to go ahead and build this now. So that's close this off and then go to the start of files for the Dragon Slayer. Game down in the script, I'm going to begin by creating a variable called random. This is the only section which we haven't yet covered. To generate a random number. We use math, don't run them and then the brackets just like this. And then let's do a consul log for the word random, so save and then reload. And in fact, we need to go to a project, open up the console and there's all random number. If we keep refreshing, we'll get different values each time. A random number in JavaScript by default is between zero and one zero being included but one not being included. This will end up with the highest value of 0.999 If you keep refreshing, we don't see any values high in the morning. So to make this easy, photos were 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 difference decimal places. If you want this to be a whole number, we can even around this number, up or down, we can run the number down with master floor. Oh, if want around the number up, we can say math, not seal, which is sure foreseen in and then surrounds the rest Follow code inside the brackets. Now, if you save and then reload, well gets a random number, which is round it So now we're taking care of this random number on 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've defeated the drug in. If the random number is over, 50 will say you've lost. So let's get back to work with this game. We couldn't move the console log and then I want to set a second variable off name. And this name is going to be the value posting by the user inside of a prompt. So what is your name? So this will have a prompt to the user asking for the name which we can type in. And this value is stored inside this variable next, often going to create a new variable. Coldplay on This is for our second screen, which is going to be a confirm. Inside the confirm, you can say hello out of space and then I use his name. So this is the screen which was seen inside the final version. The first of all we get What is your name? When you type in your name, you can say OK, and this section here is the one which was storing inside a play. So hello. Name on any text Ring off. Would you like to play with the question mark on the semi column? Now we need to do some conditional checks. So first of all, we're going to check if the user has selected play. So if play is true, then we want to run some cold. Okay? So if the user has chosen to play the game, we don't want to create a new confirm. And this time we're going to ask the question off. Would you like to battle a dragon with a question mark and the semi colon? So if we go to the finished version just here, let's reload. So what's your name? Okay, then we have this section. Would you like to play? If? Okay, this is a section which we just created saying Would you like to battle a dragon? So we need to stall this inside a variable. I'm gonna call my own bottle, just change up. So now have a true or false value inside of this valuable called bottle. So if the user wants to go ahead and play, we can then create a new s statement and this time nested inside a play. So we'll say if Buttle is true, then insider here wants a bustle. Or if the users clicked on council, Buttle will befalls. And then we need to provide a l statement so we'll say not bottling. So first of all, let's deal with the else statement. So if the user is chose not to battle, will simply do an alert on its alert. Can say, Come back when you're brave enough. Okay? So let's first give this a test in the browser over to our projects. That's refresh. So what's your name? Type this in. We'll say OK. Hello, Chris. Would you like to play? Okay, so this is this section here saying, Would you like to play? If play is true? Well, then asked Would you like to bottle the drug in which you see here? Remember, we've not set a condition. If this is true yet we've only said condition if the user clicks council. So if the user councils, we should get this message here. Let's try this. And now we get to come back when you're brave enough. Okay? Now, when it's 100 lei condition if the user clicks on. Okay, so lets out. A condition is the user decides to battle. So before we set up this random number between zero and 99 stored it in a variable called random each time we ruin run them. We can then use the term the operator to check if this is greater than 50. If it is, we can then say you defeated the dragon and then exclamation mark, then separate by the coal on. If this number is less than 50 we can then say you lost. So say the and let's give this a go type anything into there. Would you like to play? Yes. Would you like to bottle? Okay, we don't see any results on the screen. It is because we've created our turn re operator. Both would not displayed the results on the screen. So that's set the result to be a variable call results and set this to overturn the operator. Then just after this, we can do a console log with the value of results and in fact, will change is to be an alert, just like the rest. So even then, over to the browser, what's your name. Would you like to play? Yes, I would like to bottle. Okay, so we lost that time. Let's try again. Was it like to play? Yes. On this time we defeated the dragon because the random number must have been over 50. Okay, good. So handled most off the use cases here. If the use wants to play, it's the user wants to bottle. So the last case the handle is if the user doesn't want to play at all. So if we refresh the browser so this time, if we type on name in and click on OK, well, then want to handle the case if the user doesn't want to play currently inside. Hey, we're checking. If the user wants to play on, if they do with Enron this cold instead, it's the user clicks on council. We don't want to alert a message saying Maybe next time we can do this as an l statements at the very bottom. So else we'll do on alert. Or maybe next time say that. Give us a go. What's your name? Click. Ok. Would you like to play this time? My click council and the message off maybe next time. So great everything is now working on. I hope you enjoy building this game. Don't worry. If it was something which you couldn't quite manage, that is quite a lot to take in there on each step. Just take a little bit of thinking about to decide what we're going to do next. So hope, you know, looking forward it to the next section on. I'll see you there. 12. DOM Manipulation: Welcome back. This video is where job script begins to get really interesting by manipulating at Leedom, the Dom stands for the documents object model and is a tree like representation off our Web documents. It is an interface to allow programming languages to access and update the content and structure. He will see the same structure as our webpages. From the top, we have the documents inside. There is a root H melo element. Under this we have the familiar head and body, then followed by our elements, text and attributes, for example. And the great thing about it is that it can connect to languages such as Java script so we can change things. This opens up many possibilities, such as the ability to access elements to change the content, attributes and styles or even create and delete elements to. It may sound complex, but it is pretty easy to get started with one of the easiest ways off. Manipulating the Dom is to grab on elements on a page and change it, for example, selecting the P elements and then change in the text. Let's head over to a job script starter on Open up the Dom manipulation section. Let's head over to our jobs group started files and goto open number 10 which is Dom manipulation inside here. We first need some hate mail to go ahead and change. So inside the body that's open and close the P elements and then at some text inside off Hello. And then we'll open up the Spahn elements and then at the tax of user, this will display on the screen the text off. Hello, user. Well, there needs Arden. I d to dishpan element. So broken. Grab it. Using JavaScript. Let's call this I d the user name. Okay, It's no. If you scroll down to our script section, which is just below here, we can start with what is called get element My i d. So this is pretty self descriptive. These crops and elements by the i. D. Such as user name. First we grab the documents. This is the documents object, which is basically a webpage. Remember, the Dharma stands for documents. Object model. So our tree like structure is a model of our webpage. Then after selecting his documents, weaken then none of this town in this case, we're going to select an I d on the documents we have get elements by i d inside the brackets weaken then adds the name of the I d which want to select in our case is user name , not a semicolon at the end. Notice one type in get elements by i. D. We haven't uppercase letter for every word after get issues refer to as camel casing and it makes it more readable because we can better see the start of each word. If he saves that and go over to the browser, we'll see that nothing will change. This is because we have selected the element we want, but we have not yet done anything with it. We can change the contents by set in the inner HTML. So just before the semicolon, where are the dots? In a hate smell number considers to be a value such as a string. Let's say, Chris, what's the browser we load and now we see the text off. Hello, Chris, as well as using a text string for our inner hates Jemele. We can also use a variable too. So that sets a variable for our name of our name equals a string off Chris. And then, rather than I was string just here. We can pass in our valuable name off the browse and reload on. We still see that our text off 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. So just below this, we can access the same elements with documents. Thoughts get element by i d. Again, we want to select the user name, he capital end for name. And then, instead of selecting the inner hate them all this time we concert the style. Let's say the dark color to be equal to a value of red, and this will change the text color off our text inside of this spun. So save refresh. And there's a red color for the word Chris we can use. Any CSS property will want insider here. The only difference is we need to come. Okay, so any CSS properties which have multiple words such as background color and font size so over in CSS would normally do something like this, I would say fund sighs using a hyphen or a dash, but instead When using JavaScript, we need to refer to this camel casing which was seen just here. So rather than a dash, use a capital letter such as this. And then let's set the text to be a value 24 pixels. Let's see this in the browser and never goes. And now or text of Chris is a larger phones. We can also use a class in place of this I d. So let's go up to RP elements and then a class. Oh, hello, Denmark. News documents thought Get elements by class name that's at the new section off Get elements by class. Name on. This works in a similar way to above. First we select the document and then none of it down by use any class name. So get Ella moans by class name. Plus, in the name of our class which was hello, which much is the section to see you and then a semicolon at the ends. So notice here when using a class name we add an s on to the end of elements. This because we may have multiple classes on our page, for example, we could have a second set off p elements. So if we go ahead and our second set just here and then I have the same class off. Hello? Well, that's a text off. Welcome back. So now if we're hard, more than one class selected, like we do to see, uh, how do you know which one we're changing? Well, let's assign this to a variable on display to the console. Let's say variable. We'll test equals old first class and then to a console. Log inside the browser with the value of test. But with the browser right click and inspect inside of the console will see a hate schimmel collection with two items inside the brackets. This is kind of like an array which will cover soon. These two items are worth two elements. With the class off. Hello. It would 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 a class of hello has a index position off zero and then our 2nd 1 has an index position of one. We can access thes two elements by this index position. So inside the consulate would say test which is name of all variable and then inside a square brackets, we can access either of these elements by the index number. So beginning with zero, he answer. And there's our first P elements, which contains our text of Hello, Chris, don't work and access. I was second value with Test one. It's enter and this is our second element with the tax of welcome Buck. This position number can also be used inside of our selector. So over, you know, code. We're going to grab all the elements with the class name of hello and then inside the square brackets, we cannot release down to all 1st 1 which is position zero. We can do anything which would previous the scene. So China set in the style dot color to be a value off purple save, then reload. So we'll first element is no purple. And of course we can changes to be worn. And this will now make the welcome Bach text purple instead. Next, we have get elements by tag name, as the name suggests weaken. Select all the elements on a page by the tug, such as our pl Ammon for text or I am G for the image tongue so down at the very bottom. But at a comments off, Get elements by tag name again. This has a s, too, because you can select more than one element. After he we used the document door to get elements by tag name, which is just here. The brackets and then inside the quotations weaken. Aren't the elements will want to select. Let's crumble P elements on once more because we have more than one set of P elements. We need to grab these by the index number. So again, the 1st 1 is position zero. We're concert to the inner HTML. Let's set this to a string value or changed if we say that and then reloads. We've now changed our P elements art in the exposition zero The next two. We're going to look out a based on the query selector. This is just like the selector we using CSS. Let's say this word an empty image. So up to the HTML after our two p elements, let's onto the I M G elements. If we give that save, then it was the browser. We'll see. We don't see any image on the screen because we have not yet said a source attribute. So let's aren't the source attributes using JavaScript. First we can grab this image using query selector. So a comments off query selector and then we use documents daughter, query, selector, and then pass in the name off I. M. G. So this is the same way as would select our image in CSS. What can also select it with the I. D and class name, too, and we'll take a look at that in just a moment. So using query selector, we still have access to the inner html un also audience styles too. But for this example, I'm going to show you something. You and this is how to aren't an attribute. The attribute we're going to art is the image sauce. I'm a do this by using dot set attributes inside the brackets will go ahead and ARD to values. First is the name of the Attributes wants Aunt, which is sauce and then separated by a comma and then the name of image Don't J. Peg. You can use any image of your choice. Both have added an image into the start of file, which is just here. So closes down, give that save and then reload the browser. And there's an image which is now on the screen. If we open up the developer, tools would 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 have changed. That was second pl a moans we welcome back and also our image with the source off image dodge a peg. So the end result is exactly the same as if woods type this in the Haight Schimmel boats. We've added this by using JavaScript. So I mentioned that when using query selector weaken select any element in the same ways we normally would in CSS so as well as the tug names such as Image, we can also select this image with a class or I d. If we aren't an i d to this image off image AnAnd school down. Just like when using CSS, we need to use the harsh as the selector and then the i d name. So now save and then reloads we can see this still works, but this time using the I d the same for the class. It would change the image. I have a class off image this time. Just like when selecting Nissen CSS We need to use the daughter as a prefix on the should still work inside the browser. Finally, something similar to this is Query Select All Query selector which we just looked at Only select the first much in elements on the page Query select All Never Hands will return a list of all the much in elements we can see this point. I didn't a second image into our HMO. So copy this section here on paste in below, using the same class name You could say that and then refresh We'll still see this only one image on the screen. This is because query selector will only select the first elements on the page. However, if we go ahead and add query select all which looks like this and then do documents don't squeal. Disliked all this will go ahead and return a list of both of our images. So first, let's talk the class off image And then after this, we aren't the square brackets. There were compassionate index number, so just like before. The index number zero is the first image on a page when the fuck will just come and tell it's query selector. So now we've selected our first image. We can then use set attributes like we just looked at then personal first Fund year, which is the sauce on the second mom, which is image the JPEG. So this will select the first fine. You even it would warn image on the screen, however, if we want our to the image in twice records, copy this line of cold here and then paste it in one more time. But this time it's like the index value of Born. Now we have two images on the screen. Selecting two elements like this will be better done with a 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 job script 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. Hasn't attributes on setting styles. Now we're going to cover how to actually create new elements and also how to remove them to Let's head over to our started files. We're going to begin in number 11 which is audience un removing elements with JavaScript. I also have this open inside the browser we can see in our started files. We have a one ordered list with the to list items off apples and pears, which would have just here. Let's begin down in the script section. We're going to look at what is called a document dot right document. That right is away offsetting a text string toe a page so documents don't right. And then inside of the brackets, we can add a text string such as documents, right text. If we say that and reload the browser, we now have this text appeared alongside, I will not a list document. That right is for audience a simple text bring to our page. This is commonly used for testing purposes. What it can cause problems if used incorrectly. For example, if you go to google dot com and then open up the console with right click and inspects inside here, if we do a documents not right and then passing a text string such as Hello hey, center! And now we see the Google Home page has been replaced with our document rights, so a document right will override all of the existing content if the page has already loaded. So we need to be really careful when using this, you'll see at the top of the started template we have our own or the list, which is just here. This is a list we can work with by adding and removing some list items using JavaScript if we want to create a new element on the page he was in JavaScript, we can use he create elements method. So let's remove this document that right and then inside here, we can do the documents, don't create element. Let's create a variable. To start this in called list item on set was to document dot create element 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 who want to create, such as a list item. Any element tag name could be added to, such as a Dave or API elements. So creating this won't do anything on its own because I love created it. That is still no text inside elements. We can add a text use need, create textile method. So let's just add some comments. So creates elements. And then after here, we're going to create the Texan old. You can also stole this inside of available called item text said It's equal to documents dot create X note. Then inside the brackets, we can pass in the text string. We want to aunt so sticking with the fruits going to add to the value of bananas. Okay, good. So if we say that and then reload the browser, go to our index page. We still don't see any extra items on the screen because although we have our elements which you created here on also text which you have here, we have not yet added this text to the contents of these elements. We can do this with the upend child method. Tonight's art text two elements. So first of all, let's grab our list item, which is just here. So we say list item dot upend child on the child we want to upend. Is this item text just here so antes inside the brackets and then give us save and then reload so we still don't see the elements on the screen. Let's see what's going on with a console log. That's console. Log the value off our list item over to the console. Right click. Inspect so we'll see. There we have our element created. We've got our opening and closing list item and then the text off bananas as the child. So the final step is to again use a pen. Child art. This new item to this existent list, which is just here, is existent. List has an idea of list. So first, let's grab this and story inside available so down at the bottom that's select the parent list. Install this inside a variable called list so we know how to do this. It's documents dot get elements by i d. The idea we gave this is list and then shot a semicolon at the end to stall this inside this variable. So now have the parent list on We have the child wants art would go ahead and add these now . So, uh, new list item to list. And we do this with list daughter. A pen child which we've seen before on the item Wants Art is the list item at a semicolon at the ends. We load the browser and dare ago says, or bananas as a newly sytem. So just to recap what we're doing here, we're grabbing the full list and storing it inside a variable. We're then adding to this list the child, which is this new list item. So you may be wondering, why do all of this instead of just typing in a new list item? Well, inside the hate Shimo Well, there is a lot of cases where we want to do this with javascript in a to do up. For example, each time the user types in a new to do item, this could be I did to the list just like we've done here. Or, for example, in another course, which I have will build a music player application where we construct a list of songs so moving on as well as I didn't items to a list. We can also replace any existent items which you already have. For example, if you wanted to replace this past list item with something else, what could also do it is to So first, let's create a new lease item called grapes. So let's create grapes. List item I would do is just like before we can create a new valuable called new list item and then said this to be documents, talk, create elements. The elements we want to create is a list item. Then, just like we've seen before, we can also create our text node. So it's a new item text. Now, this is just exactly the same as what we did before we were created. I will list item and then I will text in old bananas. But this time we're going to be creating grapes, so this is equal to documents. Don't create Texan old text of grapes cynical at the ends on no money to art. It is text to this item. So we say new list item and then append the child off new item text just like that. So I've got a new lease item here which were access. And here were then at in the Child, which is a new item text, which is the text node of grapes. So now we have this new list item weaken uses to replace any off the list items we already have. As I mentioned before, I want to be selecting pairs, which is the index position off one So down at the bottom, that's quite variable, called item to replace and then documents don't scream. Re select all. We're going to grab the list items on then the item we want is our index position more Okay , good. So now we have our item that we want to add in on also the item Want to replace? We can now go ahead on and use replace child to complete this. So just after here, let's liked our list. Don't replace child replaced child takes in two values. The 1st 1 is going to be our new least item which is a new item and then separated by a comma. We aren't in the item want to replace which is stored in this available here. So at this in a second value say that then reloads good. So now our second item is now grapes rather than what we hard originally, which is passed. Finally, if we wanted to completely remove an element rather than replace it with something else, we can also use the remove child 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 and then we use dot removed childs inside the brackets, or we need to do is our to the child will want to remove. So for wanted to remove the other grapes, which is stored in new list item. We just add this in as a volume save and then reloads, and now the value of grapes has been removed from our list. So when removing these items, we always need to specify the parent first, which is our list here, and then remove one of the child items just like this. Rather than accessing the elements to remove directly good, we now know how tow ARDS remove with updates, elements using JavaScript. So now let's move on to the next video 14. Time to practice: adding elements with Javascript: we could some waste art update on remove elements from the dump. 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 on the top of the page full by an image these cover placed inside a container and then aren't of the image on the text as child items. Also, you will need to add the image sauce and alter attributes to use in JavaScript because it has to do this in the dorm 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. So all we need to do is create a job. Good version off this hedge. Small cold we see here. So good luck with this on. Once you were doing will move on to javascript functions 15. Javascript functions: we know I want to look ask using JavaScript functions. Functions are really important, and there's something which you use a lot when working with job scripts or programming. In general, the function is a block or two snippet of code, which wouldn't call when required. You can think of it as a task or a set of tasks which contained inside this function. We can then call this function each time we want to run the code within these functions. Also reusable. So have some code. Want to repeat multiple times we can pocket to code into a function. So let's get started off in all functions. Start a file which you open up. The sidebar is number 13 and then down to our script. Have a 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 high. This name is completely up to us, would try to choose something descriptive, and then we answer the brackets afterwards, which also known as parentheses. Then my heart, a set of curly braces. Afterwards, I want to hit enter, and then, within these curly braces, we can add the code which you want to run a woman called Function for a simple example. Weaken just aren't a alert. And then inside of here, just some text off high from function, we can add as many lines of code as it wants inside this function, although is often good to know, overload the function and just keep it to warn related task. This section here won't do anything as of yet as we only declared dysfunction. This is why it's sometimes referred to as a function declaration or function definition actually run this cold. We want to call this by the function name off high, followed by the parentheses and the semicolon. This is often called invoking a function, and now, if we save and then openness in the browser, well now gets our cold run from inside, which is our alert off high from function. We can also call this function as many times as it wants by repeating the same function call. So if a copy this and paste in below, we should now see the alert problem twice. So is a, well 1st 1 click, OK, and then I was second alert just afterwards its function can contain any codes which were like so if it went up to the top and added a empty def what effect will go for the P elements? I will keep this empty both at an I d off text. We could use this function to go ahead and change the in a hate smell. Awful text elements here. So down inside the function body, we know how to do this with a document dot Get elements by i d the i d is text which we have here and now we're concerts of the inner hates Jemele of RP elements to be a text string off text from function Wait a semi colon at the ends. So now if you remove one of these function calls save and then over in the browser gets our alert and then I would text from function. So this type of function is called a name function simply because we are a name just like we have done here. There is also on anonymous function to this is where we don't give the function of name. Instead, we can assign this function to a variable so you can remove the name and just keeping these parentheses just after the function. Anamika nards a variable and that's called this The anonymous function set the value equal to dysfunction. Here we can then call this by its name off anonymous function sort of place high with this , followed by the prophecies reloads. There's a alert, and also the text from function is still working. So both ways will do a similar thing by running the code inside of these braces Just here there is a difference so on. We'll look at what this is. Soon we'll look at hosting. Well, for now, let's move on to the next video and look at function arguments. 16. Function arguments: if we head over to the start of file for this video, which is function arguments inside. Here we have our P elements from the last video with the idea of text and then a simple named function which is going to set the in haste Jemele to be taxed from function. So in the last video seen some basic function uses, but functions could become even more useful if of passing 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 called arguments. So if it wants to pass in a name, what could do it just like this? Now the function has access to these arguments bypassing the name. We want to reference it by inside of these function for embassies. So that's our name inside a here. Pounds of this name here acts like a variable silicon references inside the function The name give this data insider here is called a parameter. Now we can use this name inside of all function in any way which would choose So for example, we can use it to sir to the inner hates Jamal. It's rather than text from function. Let's just say hi and then other valuable name onto the ends. If you say that we now have the value off Hi, Chris and Chris being the arguments was 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 changes to be multiply. And also the function coal. Let's say I wanted to pass in two numbers rather than a string. Let's go for 20 free on 15 look and then Neymar parameters inside. Here. Let's go from number one and number two never could update our P elements here with the values of number one multiplies by number two. So it gives us save and then over the Broza. But now, with the value off 345. If you were to make a mistake, such as only person in one of these arguments, let's say 20 free. We load well, get the value off, 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 all need one value insider here reloads. We still get the value of 20 free, however, though we don't have our second value past in which is number two. So instead, if was out, put the value of number two. Say this. Reload well, get the value off undefined so it won't cause any major problems. Such is our website crush in. It just means the function can't do its job without all the data in which it needs. Alternatively, we can also use the return key word to return the value after the calculation. This may be useful if you want to start 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. And then, instead of updating the dom, will get Adam and by I D wouldn't comment this out on. Instead, we can return the calculation off number one multiplied by number two, cynical at the ends. Now we forgive that save and then reload the browser. We'll see. The dom has not being updated Instead, Now this value was being returned so we can store it inside. Available for future use. We can do this down at the bottom by out in a variable called some and certain is to our function call, and then we can check. This is working by doing a console log on a log in the value off some. It's a lot available. Assume inside here, open up the console and there's I will return value of free 145. So now I have this stored inside available, and it's now up to us. What we want to do would just return volume. So adding argument is a great way to extend the capability of a function. Next up, we look at two important job script concepts called scope and hoisting. 17. Scope and hoisting: we're going to now look at two important things to understand when using JavaScript on this is called scope on hoisting, begin with scope on the law. This relates to all variables we know looking at these terms because they have a lot to the way it functions. Scope basically determines where we have access to all variables. First, let's go to our start a project on into the scope and hoisting section down, and here we have a multi function, which we've seen before multiplying the value is the number one and number two, and also just like the last video have our MTP elements to display the result in the browser. So this time, rather than passing number one and number two as a argument to the function, we can go ahead on and declare these variables. Let's save Ah no more is able to five and involved, known to is equal to 10. If we save that now, these two values should be multiplied, which we have here and then displayed in all P elements reload and there's our value or 50 on the screen. This is working okay because the variables which had declared have been declared outside a dysfunction body. This means these variables are global. All have global scope. Global variables could be accessed anywhere in our code. For example, our variable is being accessed here inside of the function. But we could also access. It's outside of the function to which we could see with a console log. So they were console log outside of the function body. I'm oclock the value of one of these variables. Say that then reload on. We can see that No, only to have access to the variables inside the function, we can also access ease outside the function to which you see here with the console log. However, it was to grab these two variables here and then put them out and then instead paste them inside off our function body Give that save reloads. So we now see the old valuables can be accessed inside of the function. What was the on console log is throwing an error. This is because we have 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 could only be accessed locally inside the function, which there were declared. This is why I will get element by i d. It's look dating, but of a console log, which is outside. The function is now thrown an error. We can prove this by moving at this console log to be inside of the function. Let's move this inside of the coat embraces the function and then over to the browser. Now the council log also has access to these local variables to So this is how scope works . It's all about where we declare our variables. So remember, declared him outside of a function will mean the global and can be accessed anywhere. Variables declared inside a function only have local scope and can only be access within the function. Next, we have another one of these words, which you'll hear about call hoisting. Hoisting basically means that job script will move or hoist your variables and functions to the top of the current scope. They're not physically moved to the top, both actually stored in memory so that could be used at any time in the script. This call is some behavior which remain not expect. Let's go over to our example from before and take a look at this in more detail sold over to all 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 who declared this function first, and then it called Blow on Our cold is read from top to bottom. But what for? Called the function first before we declared it so. If removed, multiply to be about the top, therefore calling the function before we actually declare it. Let's say that on to see what happens. We still see things working because, as we said before, functions of variables stored in memory. So when this function is called, just hear the browser or the interpreter already knows it exists. When we looked at functions a few videos ago, we looked at two different types. This type which we see here, which is a name function and also an anonymous function which does not have a name. Remember, it looks like this, So if you remove the name and then stall this inside a veritable calls anonymous function and said this equal to all function just to you. If you call this function down at the bottom to change, multiplied to be anonymous function and then movies down to the bottom save and then we loads, we'll 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 on named functions. Well, the difference Weird and anonymous functions is when calling it first. It will result in an error. So if move this anonymous function, call back up to the top. Both the browse and reload would now see an error in the console, and this is no longer working. So this is a difference between the two function types. Anonymous functions are not hoisted. We'll start in memory. But named function declarations, which was seen first, are hoisted. Hoisting also happens with valuables to Let's take a look at this. If it comments out this function, remember, in visual studio code, this is command or control with a forward slash and then if we declare available of X to be 10 and then the second variable of why to be equal to five and then Let's alert these two values off except Boy. So let's add X and Y and separate these with a string unless odd a pipe symbol insider here . If we say that and then reload the browser, we don't get our alerts off 10 and then five. So this is the behavior which we would expect. We've declared a variable X and why and then alerted these to the screen. So this is all expected behaviour. But what would happen instead if we moved the alert above our variable of my well, let's say this and check this out in the browser reload, get the value of 10 and then why is undefined? So we said before the valuables are hoisted So we would expect that the values of X and why a both starting memory onda available Will McCall This alert But this is no happening. So there is one thing to be aware off, though on a low, these variables are stored in memory. Only the declaration such as thieve arable of x unavailable why he stored in memory robin on the actual value which we assigned to wear or five on also 10. So to see it is more clearly, let's go into our example on This is the initialization. This first valuable is the initialization. This means we declare a variable of X on, assigned the value of 10 to this variable. A declaration on newer hand is when we just declare a variable name without assigning a value such as the CIA. So this is the declaration. So now we know the difference between the initialization on the declaration. Why would this matter to our code? Well, when any of these variables hoisted even the ones where we sat an initial value like this only the declaration he stored in memory. This is why our variable of why which we have here is shown up as undefined available. Why is actually hoisted or stored in memory? So the browser is aware there exists, but it's not aware off the initial value, which is set to five. Hence why we get the value off undefined. So this may all seem a little complex if this is new to you. But this is how the cold is red. So it's really important to understand, to avoid any bugs or expected behaviour. 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 of local, which were hard inside the function here, place them at the top of the function body or if wants our variables to be global, we should set them at the top of our script. So let's move No Xa. Why, right up to the top of the script that's on this above I will alert from before. You can also set this to be able value of five gives us save and then refresh. And now we don't have a problem because of all variables and now set at the top of the current scope. So when she was said Thies at the very top, or at least above the code, which you're going to access them in O. K C alert. This will ensure our cold is wrote in a similar way in which is red on possibly avoiding any unexpected behavior 18. Arrow functions: like most programming languages, Java script evolves over time, and this can change aren't new features on syntax. Job script is based on a scripting language called at my Script, which aims to standardize the implementation off JavaScript. This is why you will often hear versions off JavaScript being referred to us being such as ? Yes, five. You're six or you're seven, for example, Yes, five or EC rescript. Version five is a version which is currently fully implemented in all browsers. We don't the need for any tools to confuse things even further. You will also hear them refer to as the year of each release. Yes, six came out in 2015. So you may also hear this called S 2015 as we go for this course will use a modern features or syntax from the Essex specification and above, This just means a more modern way of writing Josh scripts or a new feature. Starting in this video, we'll look at the Essex are all function. A narrow function is a way of writing a function which have already seen, but with a shorter, cleaner syntax. If you go to the start of files into the arrow functions section. If we scroll down, we'll see the values off Number one and number two multiplied inside of an anonymous function. Which was he? Just here. Anne s six arrow function allows us to ruin the same code inside of his car races, but using a shorter syntax so we could still keep a variable of anonymous function. But rather than having the word function, you can just use the parentheses like this, and then the equals and greater than symbol and all the rest of the cold inside the curly braces just stays the same. If we say this and then reload, we'll still see the value of 50 in the browser you may often here is called a fat arrow function to because of how this Intacs looks with 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 release our two variables appear on instead posses in as arguments, so that's are no more and then numb to broken and passing these values as arguments were McCall a function so five 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 shorten this syntax, even fervor, by completely removing the parentheses. So if he only wanted to pass in one number, such as five, you have a second perimeter here. We can also remove the brackets or parentheses and just leave all parameter name insider here and then to avoid. And errors will just remove this number to from here, reload the browser and now get the volley or five. So this is now a shorter, cleanest Intacs. And this is how well right functions for a lot of the rest of the cold June's course. So this is all great and working fine now, and this is how we can use an ear six barrel function. 19. Javascript events: Now it's time to look at another important part off building websites, and this is JavaScript events. Events are triggered in many ways. When importance clicked. This contributor an event when a mouse hovers over in elements this could trigger an event to even when a page first loads this contributor eight on load 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 often elements When im Miles hovers over it, he only W free schools websites under the Hay Tchmil dorm events. There's a huge list of events we can listen for if we scroll down. First of all, we have the mouse events, so we have on Click we have on double click on most leave on most answer on mouse over outs and earth further down. We also have keyboard events, which triggered when various keys oppressed, for example, contribute events when the keyboard button is pressed up or down. And there's pretty much every kind of events to cover a supreme which anything which can happen on a Web page, thank you, informs here we can decide what we want to do. The things that Charles on Change on Search on submit, which is what to do when the form has been submitted. There's also drug events, clipboard events on so many more. We're going to be using some of these juniors video, and this gives us so many options, which we can respond to inside of all code. If we head over to the start of files, we can go ahead and take a look at some examples. So go to the job script events file, and then let's get started. Inside of our example, he will have some simple text inside of a P elements, and then inside the script, we've got a narrow function inside here. We just change the style of the font size to efforts for pixels and then run this function so called the browser and reload. This is the text which we have after the style has been applied. So currently we're calling our function inside of the script, which is just here. If you want to dysfunction toe only run when something happens, such as a user moving the mouse over the text, Will Conard dysfunction call into an event. So inside the P, Adam and Christina inside the opening tire, we're gonna add on mouse over, 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 all function, which is changed on size and then at the premises just afterwards. This will then run dysfunction every time the mouses over this text. Then let's comment out at this function. Call right at the bottom save and then over to the browser says I was standard size text. And now, if you hover over with the mouse will now see the text has been increased to 34 pixels. We can choose any event we want to trigger dysfunction. So Charles on Click that's changed on mouse over to be on click. Well, the browser. And then if we click the text, the function is now called. Things such as on Click on Mouse events are really common, and we'll see them a lot. There is also some on common ones, which you can see from the list before, such as if the user tries to copy something from the page. So let's are on copy. Never comments this out and then do something. Sir Charles and alert on a message off. Stop copy and my stuff just like it hurts and then save. And now for right, click and then copy. We now see the message appearing on the screen. Let's remove this alert from here on green. Stay this. We can even run some cold when the page has finished loaded. We've on load. We can do this inside of the body. Let's go inside the opening stock and then on on load. So he arrived and calling a function. I'm just going to apply. It's in JavaScript to run, so that's copy this document. Don't get element by i d. Just up to there, and then we can paste in our job script inside the quotations so we'll grab in this text element in exchange the inner html to be our tech string off changed. Now, if we saved us now, as soon as the page has loaded, this will override the text to be changed. This method off handling events within a hey HTML. Elements like we're doing with these two examples is called In Line event handlers. Although this Coble work, it is considered but practice to do things like this. It is better to keep the hate Schimmel and JavaScript separate, even place in the job script 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 Haitian Ill. So first, the ones from the body section that's everything from inside here and also the own copy one from here. Then we can get to work moving all these into a script section. So let's start by access in old P elements here on Store it inside a variable. Let's save our text elements on set is two documents, doors query, selector. I'm going to select overpay elements with the P tug. We can then attach an event listener to this text elements. So our text element and then dot art event listener inside the brackets, This event listener takes in two values. First is the type of event we want to listen for, so let's say click. This name is generally like the ones we looked up before without with word on before it. So, rather than on click, which we used before. Would you shoes click. Also on mouse over would just be mouse over the second value. All the second parameter separated by a comma is the function which you want to run. Let's add our non most function into here the parentheses and then open and close the curly braces. But a semicolon at the ends inside this function bodywork and then run some code. It's last copy this section, but before and in fact we can remove its function. We don't need this anymore. Let's remove all this and then inside this anonymous function, look and then paste this in. Remember, this is the one which changes the font size to the 1st 4 pixels. You that save and then reload. There's a text. Once we click this in no increases to fertile pixels. So remember this is an anonymous function because, but not 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 at so removed the function keyword and then ask the arrow just afterwards, which is the equals and then the greatest symbol. Check this is working okay. Like Lincoln Sext, using this odd 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. So we would need to loop through all of them. I will cover looping in the next section. Or if you wanted to give this function and name so we could reuse elsewhere. We can cut out from here and create a separate function. That's because a little bit smaller, so all fits online. And then I'm going to go ahead and copy from this close embrace here, right to the stars, off this function parentheses. In fact, we could these other place Then about this, we can create a function. So give us the name of ah, change on size just like this. Never consent this equal to the function which was copied on its face is a little bit So now we have our separate function which is now a self contained on stalled in the value of change. Fun size. Now, instead of having this as the second argument, weaken now just paste in this variable name on the cold should work exactly the same refresh click on the text on the function it still works even over now, placed it into its own variable. This also means now different parts of our cold can still run this function by access in this name here. So notice woman called the function just here. We didn't add the parentheses just afterwards like this. This is because, adding these will run the function straight away. It won't wait for the event handler first. So now it's just on these in save and refresh, and we could see the text is immediately 34 pixels in before we've clicked on the smaller text. So let's remove these now from this example and say this. So this is it. Now for our first look, I events the really useful and something which will use a lot when working with job script . We'll continue looking at events in the next video. We'll look at the event object 20. The event object: you should know have a grasp of what events are on, what we can do with them. There is also some additional information which is passed to the Event handler, which is called the events object. This information is all about the event, such as what type event? It waas. What element was triggered on lots more information which will now look at if we go over to our started files for the events object insider here we've got our text on pretty much the same example from the last video. We have a event listener which once clicked well, then change the font size 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 could be any name of your choosen, but it's often called event or even a short because it contains the information passed to it about other events. You can think of this as a veritable which holds this information, but what information is passed to it? Well, let's go inside all function and do a consul log when we can take a look. So come so log the value of E. Save this and an open off these in the browser, right click and inspect and then go into our council, which is no open. If we trigger dysfunction by clicking on our text, I would now say some information inside the console. Let's open this up on see what it contains. So if we scroll down, we can see it is a huge amount of information, which is passed to the event handler most that you will never really use. But we can see some information about the events so we see it's a mouse event. We'll see what position on the screen the most event was triggered with the X and Y coordinates. I want to take a look at these X and Y positions in just a moment. Self. Now, if we scroll even further down to the targets, which is just here, we're considers the reference the object which dispatched the event. In our case, it's the P elements with the idea of text. We can see this better if we go over to the browser rather than just logging e weaken selectee don't target refresh trigger events and there's our events target, which is the P element with the idea of text. We can use any piece of this information inside bubble cold. So, for example, if you go back to console log in the full events and refresh, we'll mention before they would have some most positions, which is claims X and claim. My, this is the X and Y position of where we clicked on this text. We can now go ahead and track the most position over our elements by using his clients ex and why so back over to our function. Let's change this. Documents don't get element by i d from changing the style. Instead, we can change the inner hatred female of the P elements to be equal to the event. Traxis would e adults clients x which is the X value of the mouse. Then it's our daybreak element. It's on the Y value on a separate line. And what access? Why would e daughter claim why with a cynical on the ends? Now, if we go down below all function into the event listener rather listening for a click event , we can listen for the mouse over events, so this will cause the events to be fired each time the miles moves over the P elements, which will and display the values of X and y. So say that and then over to the browser. Look, in fact, was a consul down. And then each time I move the mouse over the P elements, we can see the X and Y co ordinance are updated each time. So this is how we can use the events object to get some extra information about the events . 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 on organized by moving over JavaScript into separate files. 21. External Javascript: over in the job script started files. There is a folder you go inside the menu called External John scripts. If we open up this index or hate small page, it's the same code which we ended the last video on. What were you doing in this video? Is taken the job script out of this hatchimals file on placing it into its own separate file. Kind of like what we did earlier. We'd CSS first. We need to go over to our Project folder and create a file at this too with a dot Js extension. So inside of this external job script file, click on the new fire like on Call This Anything we want. I want to call this script dot Js Then when it could the contents of the script from Indexed or Hey Tchmil and then paste it into this new file, sparkle to the index and then scroll down to Allscripts section to make this a little bit smaller just for now and then if we could, all the contents of our script leaving these two tugs in place paces back into our script dot Js file gives us safe. Good. The JavaScript is now in its separate file. The things the work that we still need to think this file in the index page, using the source attributes so back over to the index. Let's just move the script tags up together, and then let's go ahead and aren't the source attributes. This is going to be a relative path to our script dot Js file the script file and also this index page in the same folder level sucking just simply aren't script dot Js If we save this and then gold to the browser, we load and now we're called. It still works. So each time we move over, DP Elements would now getting updated X and Y value for the mouse. Ah, lot of the advantages off external jobs. Good files is similar to external CSS files. First, we have the separate HTML CSS and JavaScript making, called more organized, readable maintainable. Also, having separate JavaScript in its own file will enable us to use it in multiple vaginal files. If we just leave the Java script in the script files as we had before, you can also be used in this born single file. We can also add multiple job script files to a hate mail Page two. All we need to do is add more script tags with source attribute for each file next week on to put what we've learned in this section into practice by building a calculator to convert pixel values, Tow em. 22. Time to practice: pixel to em converter: So now is your chance to put into practice what we've learned so far. In this course, we're going to be creating a calculator which converts pixel values to be m. Remember, A M is a relative size, which is based on the pair of container. So, for example, in pixels if the parent container waas 20 pixels, we wanted the text inside to be 18 pixels. Brinkley convert. And then when he'd said the value to be no 0.9 ems. So everything what you need to build this calculator you have learned so far in this course , it shouldn't throw up any surprises on if we go over to the start of files. And if we go over to 20 which is the pixel to Emma calculator, and if you go to the script dot Js, we have the calculation at the top. So to get the M size, we divide the required pixel size by the parent pixel size on. This is the conversion you will need to make this work. Also, if you go over to the index page, were already prided all the styles on the market, but you'll need to get started, so everything you need to do will be in side of the charge would file so we can go ahead and focus on out in the JavaScript, so may look a little complex. But all we need to do is to get this calculation, grab the values for parents and also required size on performance calculation when this bullet is clicked. So good luck with this. Give us 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 a hope you manage to get your calculated to work or at least give it a good go . I'm not going to go ahead and show you how I did my version. It may be a different approach to how you did yours. What a songs. It's working. It's fine. That is usually more than one way to do things. So all the CSS and hate smell, as you can see here, has been taken care off photos in the start of files. So all we need to do is go over to the script Js on start to work inside of here. Let's go ahead and create a function to perform his calculation. So when I call mine, calculate on Set is to a narrow function. So inside of here I'm going to begin by grabbing the values off the parents on required. So that's this box here, arms at this one here and then store them in side of variables. So the variable of parent value said is to be documents got get elements by i D on the i d want to grab. We take a look at the index page. Is this parent input here with the idea of parents and then the second input has the idea of required. I will use this in just a moment. So that's our parents inside of here. We can and grab the value. Weird dot Value number could do the same for the required value so far required. Val is equal to documents. Start get element by I d. Remember the idea we looked at before was required, and in the game we can grab the value with dollars value. So now we're grabbing it. The two values of the to import fields, the third variable or want to create is for the output on. This is the results that you see here. So this is the P element which is going to update the results each time we perform the calculation. Let's grab this with the idea of results and then story inside. A variable of our results equals documents, don't get element by i d and the elements wars results. I'm looking just all this for no. So now we want to perform this calculation. Each time the user clicks on this convert Putin, if you go back to the index or hey, Jim, o This poor turn is just here. We can grab this Putin with a query selector and then as an event listener for each click, Sidanko heads and perform this calculation. So the button Install this inside a valuable called Bt again on and document doors. Query selector. So grab your button and then for the sport, and we can go ahead and aren't a event listener Inside the brackets we conard to values. The 1st 1 is click, and this is the type of event who want to listen out for once the bullet is being clicked with them. Want to go ahead and ruin his function here? Let's obviously in a civil second volume detective working, Okay, we can then do a consul log inside the function and then we could log on to values off the parent value on the required value, such as check These are okay, so parent value in an empty space and then the required value. Save that boats of browser and then open up the console. Okay, so let's aren't a value. In fact, we just click on convert first, and we shouldn't see anything inside the console because we're all putting the values of these two inputs. Let's add something inside of here. 20 and 16. Convert. There we go. There's over two values inside of there. So the simple way to go ahead and update this result here it's just grab this result variable here on set the hate smell to be the results off this calculation here, which is it required value divided by the pattern value. So let's give us a go if we say results don't in a HTML is equal to the required value divided by the parent value. Oh, it's a browser on some values into here. Convert. I'll get the value of 0.6. It was said These were both 20. We should get the value of one M, so this is a straightforward way of doing things. However, if we refresh and only aren't one value in place, click convert. Well, she would get the message off infinity. Or if you just click on convert without any values in place, we'll get not a number. So we want to protect against any empty fields resulting in these errors. We can do this by adding eight if else statements inside of this calculation so below. This wouldn't say if we can add an exclamation mark and then parent value. So if the pattern volley was empty, remember the pipe is for all Oh, did required value. He's empty. So if even one of these fields is empty with them, want to create an alert to the user? Just with a simple message off, Please fill in all fields just like that. And then we can also add an else statement. So this l statement will run if all fields have been answered. If this is the case, we want to grab this results in a HTML turns. Go ahead and run this code. Let's give it a go in the browser. Now click on Convert will see the message of Please fill in all fields. Let's just try one of these. We'll get the same message. And then if we try the calculation, everything seems to work and 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 manipulations functions on events. If something's is still confusing to you. Don't worry too much. Everyone learns at different paces on. There is a lot to take in here if you're 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 his calls. So you'll still get plenty more practice that using these techniques, I will see you know in the next section where will cover loops, arrays and objects. 24. Javascript arrays: Let's kick off this new section by looking at jobs trip to raise. We've already had plenty of practice writing variables, which, as we know store a single value a raise. Also start values to just like a variable bull took in on more than one over to the arrays started file, which is just here. We can start Honore just like a normal variable. So down to the script, we can use the var keywords 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 consent Maura more separated by commas inside the square brackets. Let's say a cut, a comma, a string off dog become a Now Let's go for a tiger with a semi colon at the end. So now let's I'll put this would an alert. So let's say alert inside is alert. We can alert I would array off animals. Let's see our alert inside the browser reloads, and there's other free items which, inside of our array, all we cannot put this to an element just like already seen. So if we go over to our age smell that's great a div. We have a 90 equal to animals. You can just leave the contents empty for now and then go down to our script number and ground based, weird get element by I. D. The idea was animals, Anamika said. The inner HTML like we've seen plenty times previously and set this to our animals array, save no, just down and then refresh. And now we'll see. I would array on the screen, so we've only you strings inside this array. But we can also contain any of the data type, such as numbers or billions. He's going exactly the same. Separated by a comma, we are given numbers or other quotations. You can also sets our building values off. True or false. Say that we also see these are inputted as expected. So displaying our animals array just like this will display all items inside of all right. But if we just wanted to select a particular born, we could reference it's by its position in the array. So just like we've looked at previously, we can select an index number with square brackets and then out our index value. Remember a raise, just like we've looked at earlier begin opposition. Zero. So say that. And now we should get the first phone you off cut. And of course we can change is to be any number. So if you want to take go, go zero worn and into said this to be to and there's Tiger inside the browser. This is similar to what we looked earlier when we looked at query select all and added the square brackets after along with access in the values of an array. We can also use the length property to see how many values it contains. So over to our script, leave the square brackets and then we can say animals don't length on. Our ray has five different values, so we should see the value of five inside the browser. Good. This is how we can use javascript to raise. We'll continue to raise in the next video. Well, we look at some built in a ray methods 25. Array methods: in. I would start a 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 would then display them in a div with the idea of animals about the top to get elements by. I d is down at the very bottom this time, which you can see here. This is because before we can get to display in this array, the recent built in methods we can use called a ray methods There's quite a lot of these methods we can use. He we're going to look at some of the most common ones, including how toe aren't on remove values from an array using JavaScript starting with that shift. So if we scroll up to the first Commons, which you just here shift will remove the first element from our ray, which no cases cut or we need to do, is access the array by its name and then say, don't shift and it is simple. Is that so? Now, if we open up this array, Medford's inside the browser we now see our first value of cuts is now removed So 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 it wanted to. Well, we need to do is a sign of valuable surcharge animal one and set this equal to our value of animals. Don't shift. Then we can check this out inside the console. So console log on its outpost. Value of animal one save inspect inside the console. And there was expected we have our first value of cuts instead. If you wanted to art items to the beginning of the array we can use on shift have as many items as we want. Let's comment out these two lines here and then moved on to on shift. He We can start with the animals array just like before, and then select the one shift method gainful by the brackets and semi colon. And then as a string, I'm going to add some new animals, Sir Charles Leopard separated by a comma. A second value of bird. Okay, so let's see if I would leopard and bird is now inside the browser there goes to know got leopard and bird pushed to the Stars off array. So this new array is returned towards with these new additions. This shift in unsheathed kind of like a pair. The both modified the beginning, often array. The next two, 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 ray. So that's comments out this line here. Move down to push. Starting with our animals array, we can use the daughter, push Mefford and then inside here, weaken as some more values. So that's our Leopard and Dan Old Bird, this time to the end of an array refresh. So there's all 1st 5 items from before, and then our last two pushed to the end of the race. Next open have pop, which is pretty straightforward. We'll call the pop Mefford to remove the last item of the array. So comments on this line here and down to the pop section here This is pretty simple. This is just like when we used animals don't shift, but this time we use animals don't pump. We don't have any values inside the brackets because we're simply removing the last item. Say this. We load on. Our last value is removed from the original ray. So these four methods of great both the limited toe only work in which the beginning or the end of an array to remove auto add items in different positions. We can use the spice method to make sure all the methods we have just looked at commented out on. We returned to the original ray. Wait over five items, then we can call animals dot slice. So just here, use the spice method game with the brackets and a semicolon to begin removing items we need to add into values inside of these brackets or parentheses. Let's say we wanted to remove this tiger. Would you just here remember, a raise began opposition zero meaning the tiger will be at index position to, So I will. First value is to make sure this is spelt correctly. So displays just like that and then we aren't our first vision, which is to So if you just have one volume like this, all the items after number two will also be deleted. So, just like that, So everything from tiger onwards is removed or working at a second value, which is a number of items to remove. Setting this to be one will only remove our tiger value, leaving our giraffe and lion on the end. So this is how we can remove items. But if instead we wanted to replace his item. So if we wanted to replace the lion, we can just add in some values after this, so separated by a comma. Let's replace a lion with a fish. We load and there we go. So we still have our original cut Dog giraffe and lion put fish now replaces our value off tiger. We can also add multiple items in two. Only to do is separate these by a comma. Let's go for a monkey this time refresh and there's an extra two items in the middle. Let's wrap This video opened one more, which is how to reverse the array so which returned in reverse order. What we need to do is go down to a reverse section and select the animals. Don't reverse rockets and semi colon on. Remember from before the line is at the end and the cat is at the beginning. If a refresh this is now it's walked over. There is also some more rain methods to which could do various things. I'm looking for more of these soon. If he interested in a full list, just head over to Google and then do a search for Mozilla A Ray methods. It's enter and it should be the first results which props up. So it's like 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 a rate or land, and he's over methods to so feel free to take a look through all these different methods and find out how the work we looked at some of these so far, such as its place shift unsure shift push on reverse. So this is it now for this video on. I will see you next time 26. Looping through arrays: forEach: in the next few videos we're going to be focusing on. Lupin Looking makes repeating tasks really easy in this video. We'll be looking at the for each loop before each loop will run a function for each item in the array. First, let's go over to our started files. So let's head over to number 23. Looping through a raise closes down and he would have a basic starter. We have our empty div, and then I worked on Masari. First of all, let's take a look at the problem. If we wanted to do anything with these array items, we will need to select each item individually. So let's do a console log on. Let's look to the console. The value of animals. I was where brackets to select our in next number of zero. If we wanted the carts and then let's say to upper case, followed by the brackets on a semicolon At the ends to upper case is a Josh Good methods to transform a string to upper case or capital letters to lower Case is also available to so now, if wanted to select our second item to we'll copy this and paste said this the warm and then we'll need to do this for each isom inside the array. This would take up a lot of time on the lot off repetitive cold. Let's go to the browser and into the console. Refresh, and there's about uppercase cut on dog. So, of course, this would take a lot of repetition to do this, that I will. Full array. Imagine if we hard hundreds of values in the ray. There would need to be a lot all repetitive. Cold on This is not great. This is where the for each loop comes in for each will run a function for each array elements to say It was a lot of repetition, so let's go over to our cold. Remove the council logs and see how this looks. First, we select our animals array, and then we use dot for each. This is also common case with a capital E brackets. Semi colon with them. Pass in a function which you want to run for each array elements 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 calibrations weaken, ruin our function code with them. Pass in the name of our choice, which you want to give each individual array elements. Let's call each individual item simply animal. Now, if you want to do something with each way value, we can use this animal variable. Let's say alert. I will animal semicolon refresh the browser so there's cuts. Okay, dog, it's okay. Gain 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. So let's say a string off animal animal type. Close the string and then aren't available on to the end. Refresh the browser. A nosy animal type of cuts dog, saiga, giraffe and lion, or even going back to our up. A case example. We could use the animal variable and then say animal 0.2 of the case Rockets afterwards refresh and now we see open case values Inside the alert. We can push all these new items as upper case to a new array. To first, let's create a new empty array. So just after animals that save our upper case names, we don't need to add any values. Weaken simply just aren't the square brackets to create an empty ray. We know how to push items to an array. Will you see dot push Mefford, which we looked out in the last video. So down inside our loop, instead of our alert, we can say uppercase names, which is our empty, courageous here. Don't push, then inside the brackets, that annual awards push he stored inside this animal variable So animal on. Let's set these to be the case so to over case the parentheses. So this time, rather than I'll put in East the console, let's do our familiar get element by i d. Which is this. Animals live here. American. Push our new array to the stiff. Let's say documents dot get elements by I D. How animals i d. I'm looking, said the dot in Haiti, Mo. To be equal to a new array off uppercase names across with stomach alone at the end. Oh, that Broza. And there's a new array of uppercase values. Another feature off, for each is the ability to access each item by the position or the index number. First we had a second valuable name off our choice. Inside the function I want to call mine index so separated by a comma. Ah, the variable name off index they're makin uses index in side off our function. So that's open to the index before the animal name. Enjoying this on. So even then refresh and now have the index position as well as the value. So 0123 and four we can construct this new array item in any way we want. For example, if you wanted out of space between index andan animal name, we can do that with a string. So that's a in next plus on. You could have space or even a dash and also joined on our animal on the end. Refresh on. There we go. Finally, index numbers begin at zero. So if we wanted this to start a war, but could you simply add plus one on to the end? So let's say index plus one on their ghosts. Now index number starts from one, which is probably more realistic when I'll put in to the user. Now let's move on to look at another way of Lupin through a raise on This is called map 27. Looping through arrays: map: Okay, let's begin by going over to our empty starter, which this time is Number 24. This has a pretty similar example. What we looked at in the last video we have our Dave, which is empty. And then we have our animals array. Also have a second array, which is on the animals set to other case, which is created using this for each loop. Now we're going to look at another way of looping through a raise, which is called mop. First, I want to quickly show you something which will help you see the difference between mop on for each. If we go ahead on removed, the upper case name array on in place, assigned the results off the for each to a variable. Let's save our but the case names on set this to be our animals dot for each. Now, let's simplify this example by removing the index number some of the second value from inside here. Remove the contents from this function. A number can simplify this function by simply return in the animals array dot to upper case just like that. So now what we're doing is looping through our original ray running a function which will return our animals in upper case and then stole them inside this variable. This return statement ends the execution off the function on, then returns the new value. Now we scroll across. We conceive this Cooper case Names here, which has been upward to the screen, now refers to this variable just here. If you say this and then reload the browser, we get the value off undefined. Just hold on to this for now, and we'll talk about this more in a moment. However, if we change the for each this time to be mop, so remove the four each keyword from here. Changes to be Don't mop this time. If we refresh, we now see the values off our array in upper case. So this is a key difference between for each mop. Only using mop will return and you array. So basically, for each will loop all over the items and do something with them, such as making them up a case and pushing them to a new array or even a database. Mark will also loop over the items and do something with them, but it also returns and new array with the transformed items which will have access to buy stolen them inside of this variable Just as a final thought, we could also make this function shorter by using the e Essex arrow function. So just after dot MMA, we can remove this function key word here on keep our animal on you zero just like that refresh and I were a ray 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 on reload the browser on everything still works fine. So I hope this makes sense for a lot of purposes. Mark on for each are interchangeable. Well, you'll need to use Mup when you want a new array returned. 28. Time to practice: arrays: before move on to looking at more types of loops. I think we should take a breather and make sure understands what we could so far with a raise and also looping through them over in the start of files. So open up the sidebar and go to 25 which is times practice. And then let's open this up. Let's copy the path and then open this up in side of the browser. Okay, so all the in the started file, I added some instructions for a little challenge to give you some more practice. We have a empty div with the idea of characters on Dive 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's also a little hint at the top here inside the comments, so we can use the dot sort Mefford to solve the array. Then the second part is to use the dot mop to Lou, prove this new array and adds the text of name before each character so they look just like the comment here. So the text of name and then the string of books, money from the Array and then name Daffy Duck and so on for each item inside of this array . And then finally, I'll put these values inside of this MTD of other top. This is a great chance to reinforce what we've called so far. Birth of a 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. So let's go over to our starters on Let's go down to your script. Let's go for number one first, which is to arrange elements into alphabetical order and then store inside a new variable. So let's go down and use this dot sort method here. So that's a characters which is our original name. Don't sort. And then when it stole these inside of a new variable, that's a sign these to the variable name off. Salt is characters. The name is up to you. So let's try this out over in the browser on factors to a console. Don't log for was sorted characters right refresh. Open up the console one of the array and there's our array, which returned now in alphabetical order. So go ahead and remove this console log and then move on to number two. So we need to return a new array which each elements have in the name prefix. So we needs Auntie string of name before the outpost of each volume to do this. I'm going to use the map function, which we looked at recently. Let's access our sortie characters, which is our array off character names in alphabetical order. Dimpling cold. Don't knock a number capacity in a function. I'm going to use the ES six auto function on creative variable called character for each item inside the ray. Create our arrow function on inside of all function and we're going to return first of all the strength. So the text off name which you have here that's a name Colon, then the name of our individual character which is stored inside this variable. Okay, so now because we're returning the string, we now need to start this inside of edible. So save our on its A soul Names on set this to all function. So now have these stored inside available. We can Now I'll put these the browser using this idea of characters. Let's grab this empty Dave with a documents door to get elements by i d. Which guards the I d off characters, said the adults in a hate smell to be equal to this variable here off sort names. Cynical, not the ends. I was a console on. There we go. So now there's all over. Strings off. Name books Bunny named Daffy Duck. Jessica Rabbit on Roger Rabbit. We now have the name prefixes, A string on the's also in alphabetical order. So if you money to do this, great. If not, just consider it a learning experience. And next up, we're going to take a look at another type of loop, which is the fall asleep. 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 in the race. However, the form while loop, which we're going to look at, is a bit more general purpose and not exclusive to a race. Let's say we wanted to grab one of these characters and add it to the old order list. Let's call Tool Starter. I'm have our empty or not a list here on our array off characters just like before. So if you wanted to add that these characters to this empty you well, to do this, we need to loop through each item inside its array, our ally tags, and then place them in silence on our list. First, we can create an empty variable, distort his character names with the Allied tanks. It's, let's say, on the characters great available, called Item On that set this to be a empty string. So if we're to do this manually without using the loop, we'll need to do it something like this. So we'll grab our empty item, which is this variable here, and the news plus equals plus equals will add the value on the right to this item on the left. So let's say characters, which is our ray here and then position zero. So this would assign I will Roger Rabbit Value, which is just here to available of item. We could then add this onto a new line by Adan, a break tank and then a semicolon at the end. If you copied this and added this scene three more times again, manually would need to warn Teoh and free they were at these items to this or nor the list with a documents daughter get element by I d won't select the idea of characters and then set the inner HTML to be equal to oh item if you say this and then reload the browser Good . So our ray items and now on the page. But this way is not ideal because you may have hundreds of items inside the array and this will mean a lot off repetition. We need to repeat these lines multiple times for each item in the rape. This is a problem in which a loop could sell for us. We create a full loop just like this. It's on the for keyword deeper embassies and then open and close the curly braces inside of these prophecies. Here, the for loop takes in free statements. First is what is called the initial Isar. Let's say our initial value off I of equal to zero with the semicolon at the end, he would consider it a variable with our initial value is common to see this valuable, called I, which stands for increments. This is because this is incrementally with each loop after the semi colon. Second is the condition the loop will continue as long as this condition is true. We want to keep looping for the length off the characters in the side of this ray. So we can say while I is less than the characters daughter length cynical, not the ends. Third, we say how we want to increase the value of I with each loop. If you say I plus plus, this will increase the value by warn each time. So the first loop I begins at the value of zero. Then after the second loop, I will be worn the for Duke. I will be too, and someone then, just like a function. We can add that the cold will 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 ray. If this is confusing, let's console log the value of I to see what's going on. So comes a log. The value of I with this browser Open up our console. Okay, so we've got 012 on free. Remember, we initialized I to be zero. So this is the starting value would then have four items inside the array. So there are four different values here. These four values off zero fruit to free should also look familiar. If the same is what we did right at the start. We have our values of zero fruit to free as our index positions inside the square brackets . So rather than having these four lines of code, we can simply copy one of these lines instead of a console log. We can no idea inside of a for loop to leave these four lines. We don't need these anymore. We're going to be using these with our loop now and then the hard coded value of zero condemn be replaced with the value of I, which, as we know, is zero warrants even free, and someone. Now if we say this and then reload, we still have the same four names upon screen here. But this time we're using that the four loop with a lot less cold. This is good because this will be repeated forest long as we have items in the ray. So, for example, if we were to go on ads, any new value on here that you say hello inside of there, this will also be added to the end of the array. So just remove these for now. So since the characters container is a an order list which is just here, we can improve this loop by surrounding each item inside of the list Item tugs. So just before characters that's under string off L I people a symbol and then right at the very end change outbreak tag to be able closing list item. Do that save Reload. And now we see this is a list item because we have the bullet on the left inside. If we're also right, click and inspects. Click on the inspector and choose any one of these list items we can now see on the screen . We have our own order list and then nested inside. We have over four list items, just like standard hate Shimo. If you remember back in the Dom manipulation video who looked at Query Select all. If you go back into a starter files on it was scroll up to Number 10 which is don manipulation. Let's quickly open up the index page down at the very bottom Hard query, select all where was selected our two images by the end exposition. Remember, we said we can access all our images by this index number, but this is also not ideal because we're repeating cold. So rather than Jupiter hating cold like this, these are the kind of things which a four loop would be useful for if it closes down and then go back to our for Luke started file, which is down here are provided to different images inside this folder so we can go ahead on undies and no so close a sidebar. So if you go to our not a list of the top inside Haiti tomorrow, let's aren't an image, first of all, with the sauce off Bugs Bunny, which has the dot PNG extension. And then I was second image this time of the source off Daffy Duck. Don't PNG close yourself? So now we have over two images. I'm going to go ahead and stall this reference inside a variable called images. So down to our script and its goal right down to the very bottom on its select, a variable called images Said this to be documents don't query, select all and then grab all the images with the I m. G. Tuck. Then we can use the loop against do anything we want with these images. I'm going to grab the name of each of these image files on the screen. So just below our images variable let's create a new four loop construct is just like we did before American art that were free values. So first of all, let's set our initial Isar, so I is going to be equal to zero a semi colon. We're going to run this loop while I is less on images which still available here daughter length. So this will be two elements long because you have two different image elements on the screen. So this will run twice the chemical at the end, and then we're going to increment this one on each loop. Now let's check out the output with a consul log. The value want to display is the images, so all images variable here inside the square brackets. We can, aren't I? So this will access the first image on the first loop and then on the second loopy will access the second image because I will be equal to one. So first, let's check this out in the browser. I don't to the console, so there's over two images, which we just lived through. If you wanted to grab the name of the source, we could use the dot get attribute, and then inside the brackets, that really to want to grab is the sauce. So no, back over to the browser. We now get the source attribute, name for each image. And again, if I had a lot of different images, Loop will be really useful for something like this. Loops can really say it was a lot of time when performing repetitive tasks. So this is how a four loop works, and next we'll look at the while loop 31. While loop: inside of our while Loop started file. We have the same example which we looked at in the last video with the For Loop. We have two images. We have about another list. We have other characters array, and then we're pushing our characters into this empty div. And then we have over two images just below this followed. Put you looked at before. We'll continue to ruin as long as this condition is true, which is just here. So while there is items inside the array, this will keep running a while. Loop, which regards to look at now, does a similar job. But this time, while it runs while a condition evaluates to true, we can modify this to be a while loop by changing the four to be a while. We can also remove the first on also the third statement from the brackets. Remove the starter Andi I plus Plus, this is because a while 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. You can do this outside of the loop. So just above the loop let's say of our I is equal to zero final weaken increments I on each loop right at the very bottom. So let's say I plus plus give us save. So to recap, this loop will begin zero, which was set just here it will lend aren't the first array item which is his first line here. And then after it's done this, it will land increments I to be one. This will also continue to run until the value of I is no longer less than the land off the array. So forgive that. Say, we should still have our four names on the screen from our array. Well, this time using the while loop. Having the I plus plus right at the very end is really important. If we forget to increases on each loop, I will always be less down 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're to remove this and then save refresh, we can see that the browser is struggling to load. We can still see this spinnin in the corner on Also, we have the option to stop loading. The page on the browser will crush. However, a lot of modern browsers will also detect. This is the case on will stop running after a period of time, which you can see here. So now let's just aren't this back in. So there's no more problems and then reload. Onda will looped items back on the screen before we wrap this video up. Let's take a look at one more example. Let's go down to the very bottom on. Let's create some more variables For some numbers, let's say X is equal to five on why is equal to 10. Then create a while loop, just like we did before. And then we can create our condition. So let's say if the value of X is less than why Democrat ruin of a loop. Let's do a console. Don't log. Love the value of X and no McCree increments X, I warn each time. So while the value of X is less than why weaken our police the console and then increment it by warn each time. So say this over to the console refresh and there we go. That's the values of five right fruit to nine. If you wanted us to go all the way to 10 just like the value of why we could set this to be less than or equal to And this will now go up to 10. Okay, good. So this is how we use a while. Loop in JavaScript on in the next video, we're going to move on to looking at John script objects. 32. Objects: Welcome back, guys. We know going to look at JavaScript objects, objects of a collection or properties which have a name and a value pair, for example. Just like in real life, a computer is an object. The computer can have many properties. For example, a property name of manufacturer Onda. Value of Apple, a property name off monitor size on the value of 22 inch or sticking with our characters from before, a character could be an object to with a property name off. First name on the value of Mickey or property name of color in the value of red. So these are all just names and values, which are much together, which construct a object. Let's create an object over in the object started file, which is just in empty script tug. First, we define a new object with the new keyword, so new objects followed by the brackets on semicolon look and then a Sinus new object to a variable. 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. I never could do a consul log with the value off character say that and then reload. We'll see a set off curly braces. This is just an empty object because we've no yet. I did any properties. If we go back over to our project, we can now Ardis in. We can do this by selecting our character. Then it's a dot first name on Set this equal to you books. Then we can say character. Don't last name equal to Bunny, then character. Let's say we had an image so dot image equal to a string off Bugs Bunny does PNG. I want to. One more will say character don't color is equal to gray. So here we given the character objects the properties of first name, last name, image and color. And then we're signing these values on the right inside. If you say that and then go back over to the console, let's see what effect this has. Would now see some contents in side of our work. Curly braces. So I will object now has some properties look unstable? First name of bugs, our last name of money on someone on these aren't named value pairs. So first name of books is a name value pair last name of money is a name value pair, too. We can access any of these properties directly with the name just like this. So let's go over to a consul. Log on. Just blow is we can add a second console log. So if we wanted to access our characters cooler, we could select the full character and as a dot color. Refresh this and there's our value of gray, which is this property just here. Actress and values just like this with the DOT is called the dot notation. There is also a second way off access in these properties, so this is the bracket notation on this time. Instead of access in the properties with the DOT, we can do a consul log on instead U Z Square brackets. So let's select the character object, the square brackets and American access, our color cynical and that the ends refresh and there's our two values agree first with the dot notation and then second with the brackets. Another way to create an object is called object literal, and rather than declared a m to object which we are 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 blow this. We increase our object and store it inside available. So let's save our character on that. Set this to object rather than having an empty object, we can now assign our name value Pez. So let's say our first name, He Colon. No first name is books separated by a comma. We can aren't our 2nd 1 off. Last name on this is funny again. Our image. So Bugs Bunny, dos, PNG and finally, the color. So these previous values, which have looked at a just simple strings. These can also be any dates type, which you've already covered. So Charles Honore so we can add multiple values for the color. Let's say we have a cooler value of gray and then separated by a comma. Also white, too. If we say this on, the fact will remove these consul logs just leaving our character over to the console. Okay, great. So there's I were named value pairs, just like before, but this time I'll 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. So the end expedition off zero is gray on. The index of Born is white. We can even add functions to our objects. So just after the cooler we can add a comma. And then let's set a function which will create a string which contaminates our first name and last name. Let's say our full name is equal to a function on entry to function just like we've seen previously. Inside the function body, we can do a alert on inside the alert. Let's create string, say, in my full name is a space and American art our properties. So let's say this. No first name, then as a empty string for the space and then on the end will say this daughter last name cynical, not the ends. So it is a couple of things to notice you, first of all, when we are as a function as a property, often object. This is called a method on also have used the this keyword toe access our properties and when a function is called as a method of an object, the value of this is set to this current object. So therefore, we can access any of these properties on this object by using the start and then the name of our property. So if you give this to save and go over to the browser so you can see our method off, full name is here. But if you want to actually run this method on display the alert we need to execute it with in the parentheses. So back to our console log. And it's a character dot full name the prophecies just after and now for save and then call This would now see our method. Ruin on the alert is in the browser on the string of my full name is Bugs Bunny closes down . So this is it. Now for our first look at objects, the really useful for grouping together information about almost any type of item. Next, we'll stick with the topic off objects and look at how we can loop through them. 33. Looping through objects: just like when we were working with a raise. You have lots of properties on an object we may want to live through them. This is more efficient, on less cold than selecting each property separately. Inside of all started file, which is looping through objects, we have a current object just here, which we can live through. I'm going to create an empty variable to start with, distort the results. Let's save our results on the surface to be an empty string. This is going to start the results off each object property which will live through as a string. The looper used to live through object is called the four in Loop On. It looks like this. So we start off with a standard looking for loop, just like before. And then we go up to the premises and set our variable off I. But this time say in character on character is the name of object, which is here. So now inside of the loop body weaken. Do some console logs. Let's start with a console. I don't log for the value of I and see what we get that's open this up inside the console right click Inspect, and now we can see we get the values of first name, last name, image in color. This is because the value of I is the key. So this is basically the values on the left hand side off our properties. If you wanted to access the values on the right inside of all properties, we could then do a second console log on this time instead of I. We do the character I typical in that the ends, the fresh we could see each pair is no on the screen. So first name of bugs, last name of money on if wanted to see these better. We could do 1/3 console log and just add something to separate these values. China's and dashes. And there we go. So there's our properties. Okay, good. So now have access to all of these properties on also the names and values Individually, we can now go ahead and construct our results and create a string to display on the screen . So let's go down to our four loop on below these consul logs. So it's construct. That was string we can access. This results variable at today's would plus equals. So, 1st 4 let's set the value of I, which is our property names such as first name and last name. Then on to this a string would a call on in between and space. Then, just after this week in art all property names such as Boog's on Bunny, just like we're seeing with this console log here. So let's aren't character I and then add these onto their own separate line. We Daybreak Tunc. So now we've created a results, which is a string of all of our characters, properties with names and values. We can now put this the browser inside an empty div. Let's go up to the body section, create a diff on at an I D off outputs. Is he constantly location where we all put our results string and then go down to the bottom outside of the four loop. That's to a document. Stores get elements by I d want to grab the output, which is our Empty Dev, and then set the inner hate smell to be equal to our results. Variable. If we say this and then over to a browser reload, we now see the string with grated with the property name value followed by a break tag on. This is a string which you created just here and this is repeated for each item inside of our object because of added this to a four in loop. So this is how we can loop through objects and it really convenience, 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 construct of function. 34. Object constructor function: We've already looked at a few ways to create objects, and these are fine if we just want to create a single object like we don't previously. However, if we want to create multiple objects with 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, then create multiple objects using the same structure. For example, if a hard multiple characters there would use you to contain the same properties so it has a name and a cooler, let's give this a go over in. I was started file object constructed function down in our scripts. The constructive function is created just like a normal function which you looked out, use the function keyword and then set a name such as character. Constructive functions usually have an uppercase first letter, just like we see here so we can distinguish them from regular functions will come back to this in just a moment. But first we can create a new object based on this constructive function by using the new key would. So just below this that's used. The new key word we say new character on this character here, most much the name of our function. Just a both. And then inside the brackets, we can add some values, which you want to use in the object. So the first name, Let's say, Mickey separated by a comma. A second volume off mouse for the second name we can then aren't an array of colors. So Mickey Mouse we can use reds. Um, we can also say yellow on also black, too. Make this a little bit smaller. Just after the ray, we can add a comma. American art, a name for our image. So let's say, Mickey milestones, PNG, and then are the semicolon at the end. So now we've created this new character. We can now assign it to a variable called Mickey Grayson, have constructed a new character or past in some values inside the parentheses. But how do pass them in? So the answer is the same as a regular function. We can pass them in as arguments. So inside the constructor, we can say first last cool, huh? On image, which is in the same order as you created down here down, he would have our values for the first name, last name, color and image. But these not yet linked to own names above we can do this inside of the function body. First of all, let's say this thought first name equals first, so 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 what you starred in this first variable and then we'll set in these first name to Mickey and also in JavaScript. The this keywords can be a little complicated to understand when used in this way. The key word of this refers to this object. We consider this by doing a console log on a log in the value off this and then over to our council. We consider that the disc keyword is referred into our character with the first name of Mickey. He we can also see our property with the name value pairs which have already added, However, if we go ahead and move all console log to be outside of the current object just like this and now go back O tall browser. Well, now say we don't get our object returned. Instead, the this keyword now refers to the window object. This window object represents the browser's window. Any global functions, objects and valuables, which would create will then become part of this window. If we go ahead and clear the console and type in window, it's enter will now get a window returned on. If we open this up, we can also see the properties on this window object inside. Here we can see of a character function, which is just here, and also remember, we created a variable called Mickey. This will also be stored on the global object to. So if you scroll down, he's our variable of Mickey, and inside the console can have access that any of thes by their name. So let's say window So Mickey, it's enter, and there's our character with the first name of Mickey. We also have access to lot more properties of the browser, such as Window Start, Inuit. It's enter Armagh, Cassian pixels, the Inuit off the browser. So let's now go back over to our constructor. First, we can remove this console log and number can add that the rest of our property names. Second of all, we have this daughter last name, and this is equal to lust. They start color is equal to color and then finally have this dot Image is equal to image now to see what Mickey looks like inside of the browser with a console log. That's the console log with the value off available, which is Mickey Refresh. So there's our character object with our first name of Mickey last name. A mouse would have a cooler array with free, different values and then our image at the very end goods. Mickey now has all the names and values added to the object. These properties can also be accessed individually. For example, if you wanted select the first color who could say Mickey, don't color and then access the index position or zero refresh and there's our first value in the array of red. So now these blueprints or this constructor, which we have here is now set up, wouldn't go ahead and create multiple objects based off these templates, just like we did with Mickey. So just blowing Mickey here we can create a new variable on this time we can call it Duffy . This is also a new current object. And then inside weaken passing our values. The first name of Duffy, the second name of duck and then our array of colors. Now let's set the colors inside a here to B block and then orange, a common just after our ray. And this is going to be for Image, which is daffy duck dot p and G. A cynical at the end and still more so. I say variable off bugs is equal to a new character that will values the 1st 1 A string off bugs The last name of money array with our colors off gray on also white A calm again just after the array on the final image off Bugs Bunny adults PNG that your zoom out on. Check this all out. That's all looking fine. Now if we console log any of these extra values console log and then we can do somethin. Sir Charles Bugs, which is a Wilford object just here on target. The last name which would are put to the console the value of money saving refresh. And there we go those bunny inside of the console goods. This all looks like it's working fine and this is the object constructed function, which is a really it's a way of creating multiple objects with the same structure. 35. Const and let: Welcome back to this brand new section will be reinforcing what you've already learned along with learning new stuff such as constant, let template literal certain intervals on regular expressions we know once put our skills into practice by building a fun game. I've already added the hate mail on CSS into the start of file, so can focus on getting this game work in. Using JavaScript in this game or we need to do is click on the matchbook on when to random shapes the same size and color. So this is the finished version in front of us here, or 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 to do is click on the match burn when the two random shapes are the same size and color. Although look simple, there is a big going on behind the scenes. I will get a lot of practice with what you've already learned, along with some new things to so we click on. The much boom went to are the same with then get score. If the shop is different within. Get a point taken off on the result can go negative. So let's go over to our job. Script started files on the cold for this is in number 31 which is the shape much a game. You have got the index and the script dot Js file already open. So I'm going to copy the index page, open the file half and then pays to see into the browser to get was going so I would have all the layout and styling. So all we need to do is work in the script. Doctor s file. Let's go over It is now open the script, doctor. Yes, and it's making a little bit more space inside the text editor. So inside a heat, I'm going to begin by creating our shapes along with some valuables. Stoltmann. This time, though, we're going to focus in on to new things. We're not going to be using a variable using the var keyword. In fact, republic, we won't use them gain for the rest of this course. Not because there's anything wrong with variables. They're still perfectly valid to use. However, in here six, which Rhoda mentioned, is also known as E. S. 2015. We also have two new keywords we could use in place off. Our distort all variables First is let, which allows us to also declare variable. We need some valuables for this game. Let's go ahead and create a less corn score. I would consider this to be a initial value of zero, just like var value stored using Let can be updated. Also called resigned. There is a different soul with let and vile let values a block scoped. The block scope in applies to things such as functions or a statements, basically anything between a set of curly braces. If you remember back to when we looked at scope in, we learn variables, declared insider function scoped to the function, meaning we cannot access them elsewhere in our code. Also, variables declared outside of function called global. So we have access to them anywhere inside of all cold let values, on the other hand, a scoped to know only the block where they were created, but also anywhere else they are used. We consider this better with a simple example, using our current school variable. If we add these to any statements, that's quite a statement, which we've already learned bowels. I never could say if current score is less than five inside here, we can say a console, the log on a log, the value off current school and then a string on this can say inside. So once when the consul wouldn't know what his message is coming from. Then let's do a second console log. Outside of these statements, we'll do the same. Will ask the current school to a string. But this time we'll say outside. Now, if you go over to the Broza, open up the console like the council tab, refresh and now we can see zero and zero on. This applies to both the inside and outside. This is expected behaviour. We declared our let value to be zero, then log it inside and outside off the if block. Let's go ahead and declare the same variable. But this time, inside of the statements, let's do the same. Will say Let's the current scar this time to be equal to a value of 10. Now, if you close the browser and refresh now, we'll see the effect all block scope in corn score inside of the block is a value of 10 but the current score outside of the block is untouched if feasible, variables. So it's changing. Let two of our in both cases would now see the both values would be 10 because this variable is declared outside of these curly braces, meaning it has global scope. The most cases we can use the newer let keyword now to declare variables, and this is what will be using it for the rest of this course. So that's remove all of this example and then changes far to be. Let we also need some more variables. This project. Let's go ahead and add them now using our last keyword, So we're going to create a variable calls. Let playing on this is going to be initially set a false. This will return to true when the user clicks on the play button. Then it's great to more 14 shape one and then also one for shape, too shape on and shaped to currently on the signs because we need to add a random value to these later when the use starts playing along with the lucky words. Yes, six also introduced the constant keyword which is short for constant all variables we declare using violent. Let's can be changed or resigned. However, if we know all value is always going to remain the same, what can declare a constant instead? This will also have the benefit of the value, not getting accidentally updated elsewhere in our cold. If we declare a const and try to update value, we'll get an error. So let's set a number to be equal to 10 and let's say number plus plus. So 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 Real owes, I will get an error because they're trying to update the value of a constant. Let's remove these for no, A constant will be useful low for declaring the shapes who want to use in this project. We want to select the shapes, but we don't need to change them. Each hope is going to be an object. So can add these in as an array of objects that said about a constant cold shapes on This is going to be in array inside its array. We can create our objects, so we need to go ahead and create quite a few of these. Still have some random shapes to select. Let's set the color property on these any colors of your choosing. I want to go for the value for the 1st 1 off FF 59 5 e, then the wit off 250 On the height, let's go 460 and other comma on. Let's go ahead and copy this and paste is in nine more times given us 10 different objects , so we're going to keep the 1st 2 as the same color, but change the width and height to be slightly different. So 1 50 for this one. The 3rd 1 This is going to have a value off FF. See a free A with off 320 the height. Less changes to be 1 74 Phone can have the same color with off. Let's go for 410 the height of 1 80 Number five. This is typical of eight a. C 9 to 6. The wit fall of 1 90 1 60 is fine. Copy. This color will create two of each color the width. This time, let's go over 200 then 175 Again, it's all random, so don't worry if yours is slightly different. So the next year the color could be 198 two C four, the width off free 80 high school for 185 cos color. So these two were the same, and I hide all for hundreds. So you wait for four hundreds on the height off 1 20 and then the last pair. Let's go for six A for C nine, free 3 70 the height of wonderful five. Copy this color and made the last one the same. So it's a paired again. A wait for 4 40 on the height of 1 60 is fine. So when the user clicks play, we're going to live through these objects. Let the random one. If the computer select the same random one for shape on and shape, too. These were then considered a much so. Finally, we could do a quick console log of these objects by selecting them with the array index number. So just below over array, you a console log on Bali, all shapes. Let's go for number two. Check this out on the console. On there is one of our object, the color, the wit on the height. So in this video we have concentrated on using the constant and neck keywords. If you are unsure of when to use constant less, you should always use constant where possible and then use less if you need to re assign a value. If you make a mistake and use constant, it should be a let. It's completely fine. The console will alert you to change it. With all 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 off shape objects. Now we need a way off randomly selecting one of these shapes from our ray. I'm going to add this to a function called Select Random Shape. So back over to our script, we can now remove the console log from the last video An Anisette obey constant for function called Select random shape. This is going to be a S six arrow function. So set this up just like this. We know we can select any of these array items just above by the index number. So let's give us a go. Let's set up a constant called random shape on that said this equal to our shapes array and select one of the index numbers. Do a council log effect is working okay with the value off random shape and in fact, will call this random selection. Just be a bit more clear council like this. And then for this to run, we need to call it by its name. So select random shape the parentheses, and now they should ruin inside the console. Open up, we load and we have a spelling mistake. So this should be shapes, refresh, and now it's left in one of our objects, but rather the hearts called in in a number. We want them to be selected randomly to do this weaken. Generate a random number like we're seeing it previously. If we go over to a cold, this array has 10 objects. A raise. Also begin a zero, so we need to generate a random number between zero and nine. So let's start this inside of all function. Let's start. It's in a constant. I'll call this random num. We already know how to do this with math at random. Remember, this will create a random number between zero and one zero is included, but one actually isn't. So it won't go to 0.999 Easy premises after this. So to create this random number to be between zero and nine, the first thing we need to do is multiply this random number by the land off our shapes array. So shapes don't, then and then we can round this number down with math. Don't floor so right at the start. Use math top floor and then open up the brackets. Another thing closes off right at the very end. After a shape, start length, cynical at the ends, Just blow this. Let's do a second console log and then we can all put the value of our random number. Just checked. This is working. Okay, that's at this in Refresh says zero, seven six to so eight, there's a nine. So this all seems to work and okay, we don't get anything higher than nine on. We also have zero. So this seems to work in a completely fine. Now we've added this random number between zero and nine. We can replace the hard coded number from before former Ray. It's a rather in selecting number. Warn, Let's, like our random number. Remove the console log from both to We don't need this anymore. So give that save and then over to the console. So now if you keep refreshing, we should see a difference object from our array each time. Great. So just to finish this video off, I'm going to change his console log. We don't need to look to the console on instead, just return this random selection to return a random selection. This will return the value so we can use it later. Good. This is an important part of his project. Taken care off. Next, we're going to use this random object and assign it to our variables or the shape on and shape too. On. 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 off 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 on and shape two 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 valuables. So first of all, let's say shape warn is equal to select random shape the same four shape too. This can also be select random shape too. Now, we need to ruin this select random shape function every second on update these variables here. To do this, we can use a job script Mefford called set interval. This will run this function or repeat the same code with a time delay between each repetition. That's rough. These two here inside off. I was set into little Mefford. So first let's cut out these two lines here than inside a set interval. We create the prophecies, then inside here we can ruin a ES six arrow function. Let's create this inside here the curly braces and then we can paste in our to reassignments chemical at the end of here, American as the times away outside of these curly braces in milliseconds, so 1000 is equal to one second. So now this function will run every one second, giving us different values, the shape on and shaped to each time this interval run. But let's check this of work in and by logging the values of shape on and shaped to. So it comes a log shape, Um, and then a second console log, this time for shape, too over to the browser reloads. Okay, good. So keep seeing it to new objects appearing in the console on day pH have different values, so this works great, but we don't want this cold to run until a player it is played one of the top. So first we can surround this timer inside the function. So just above all set interval, let's create our constant, which is going to be a arrow function on its police. Repeat random shape again. It's going to be a narrow function, so set this up just like this. So inside off the body of this function, we're going to add, I was set Interval. So let's cut out the section of Creative before and then Paste is inside off our function. So now this set interval will only ruin each time a call repeats random shape. I want to do this when a player clicks on the play Born, let's add a on click handler to Old Claiborne. If we go over to index page and then scroll down to the main section, he's old play born here, which has an idea of play so I can select this would get element by i d. Article Candler to ruin our Pete running shape function so down below this that's odd. A comment off start game. So let's first select all button. We've get elements by i d. The i d. Was play Thoughts on Click. This is going to ruin a six out of function and then inside here we can call repeat random shape with the prep sees afterwards, So this will go ahead and run. Say this and then over to the console. Reload. We don't see anything runnin just yet. Now for click on the play button would now see our objects and now generated good things and are moving on nicely for our game. However, we want to move these shapes out of the console and display them on the screen, and this is what we'll do in the next video. 38. Template literals : welcome back that is now a some basic functionality in our game. We generating it too. Random shapes. Wilma. Click on this play button at the top. At the moment, though, these shapes are just inside the console. But in this video will be actually displaying the shapes on the screen for the player to compare. We're going to do in this pile also learning about how to use template literal. This will basically allow us to create a text string with some valuables past. Inside. We've already looked at some ways to include variables which strings, so let's go over to our script. I've already looked at methods like this. If we created a variable, such is name on set is to be a value of Chris. Then do a council log on inside of here. We've added strings, the valuables. So let's say hello a space And then I was our name off to the console, and now we'll expect the value of Hello, Chris, using template literal Z. Rather than joining the strings and variables with the plus symbol, we can construct one single string by using tactics. It's less remove all of this from here and then if you look for the back tick on your keyboard, which is this symbol just here, they're makin type in the value of hello inside. Then, instead of joining on our available name, we cannot. This variable inside of the back ticks so can pass in our expression. Available first using a dollar symbol and then inside the curly braces weaken aren't available name, which just looks like this. You could say this and go over to the console. We'll see the same value is no work in in the browser. Another thing we can do with template neutrals is to have multiplying text. If you wanted a string quite a long string just like this, and then continue this down on the second line, we're instantly see with these two different colors here with our text editor is highlighting and error to do this in the traditional way, we'll need to wrap each line insider quotes at the line break and then join the back together with D plus symbol. However one using these newer template literal, we can just replace the quotes wave back six such a move. These quote from here at a buck tick also at the start. Now this is all the same color. So it now appears to work in. We don't have the anymore. So obviously the console and there's our multi line string which preserves the line breaks . Okay, so now we can remove this example from before. Great. Now we know how to use these template literal Z. We can put them into practice inside of all projects, so hope to our function, which is the repeat running shape for us. We can remove these two consul logs because we're going to I'll put these to the screen. Then we can create a string to contain our styles. The stars which want to contain is thes sections off the object. We want the color. We want the weight on also the height. I'm going to set these as style properties of other shapes. So back down, 12 function. Let's go ahead and do this. No. Okay, so inside of always set interval just below I was shaped to here. I'm going to go ahead and create a new constant Let's start with shape on. So let's call this shape, warn styles. We're going to create a template literal, which is basically going to be a string with Volvo styles contains we can then of these styles. So what was shapes? Div and then this will display on the screen. So let's take a look at this with the back ticks. So first of all, we're going to set the width awful. A div inside his back takes weaken our to the dollar symbol and then the curly braces Ardell available. The variable wants set to this which is the value off a width of each objects so back down . Let's set this to be shape on which is stored inside this variable here, so shape on dot with and then when it's aren't the value off pixel on the end, so are close p x semicolon After this, then I want to add this on the next line So it's more clear the back around this time that said this to a dollar symbol. Open up The braces on the background could be shape on dark color. So, Michael, not the end. And then finally the height this is going to be equal. Teoh, I were were variable inside here on this is shape on Don't Heights And then again we need to also add on to the end our pixel value. So plus p x some call at the ends and make sure these tactics is right at the very end and right at the very start and not after each line. Now we have these styles. We can apply them to our shapes. Div. If we go over to our index page, we have an empty div for shape. Warn on also for shape too. So we're going to add these style properties today. Steve here first, let's select shape on using documents. Daughter, get element by I d dislike this. So just after here, let's go back over to the start and do a documents thought gets elements by I d want to grab shape one and then we're going to do is something which have looked at earlier. We're going to set the style attribute for this day of we're going to set the CSS text to be equal to the string which was created which is stored in this constant called shape. One styles. Let's on this other will see us as text so shape on styles we de stem ical not the end. So this CSS text, which was just used here, is not something we've seen yet. June's course. This will allow us to pass in a string off styles just like we created here, starting a variable called shape on Styles. So now let's check. This is working in the browser. It would say this and then reload. We can close the council down on Click on Play, Grace. That's our shape one div on the left, inside, here and now we can see all the style. Property is such as a color, the height and the width. And now we're playing as a style attributes which have added just here. Now all we need to do is repeat this for our shape too. So let's copy was shape on here, American base in just below. And then let's move this over to keep all lined up nicely. Okay, so now what we need to do is just change shape on to be shaped to the same for all these ones. Inside. He weaken changes to be shaped to same for the color on. Also for the height, too. And then, just as before, we could copy this line of code here We can also select the documents. Daughter gets element by i d. This time I want to select the shape to DIV, which is over in index page, which is this stiff here? Exactly the same. We do it style. Don't see us as text on this is going to be equal to shape two styles a cynical of the ends and then over the Broza reloads on Hopefully we should get to random shapes when we could play. Great. So now these two shapes on the screen will now need a way to compare them on. This is what we'll look at in the next video. 39. Comparing objects and scoring: Now I have to random shapes appearing on the screen. We need a way to compare these two shape objects when the player clicks on the much born, which is just here to begin, we have a variable at the top, which is called Playing, which was set early on in his section, which is also set to false in the side of All Stars Game function Weaken changes variable to be true once the game has started. Slash school Now two All Star Game section, which is just here. And then once the user has clicked on the play born, we can then go ahead and set to play in to be equal to true. Outside this function, I'm going to create a new comment, which is compare. So now we can add an event handler to the much born to trigger a function when clicked. So let's go over your index page on Take a look for much Boone. What you just here? This has an idea of much so we could grab this inside of a script, so documents thought gets elements by I d the idea off much, and then we can use a on click event handler trigger A s six auto function and then inside its function working aren't an if statement to check if playing a set the true. So I say, if available off playing So going to say if playing on when this is true, this will end Run the code inside the statements. So this basically means the cold inside This s statement will only run if the player has click Start Certainly play invaluable to be true nested inside we can perform another statement. This will be used to increase the place score If the objects are much so that's nest a second if statement just like this. But how do we first compare the objects to check if the same for this we have something called object dot is this will allow us to pass in our to shave variables to compare object dot is is another new jobs good feature from here six or yes, 2015 just like the arrow functions and constant let which looked at before. So inside the bracket even say objects So object dot is and then open up the parentheses just afterwards Inside a hell compassion in our values will want to compare, which would have starred in the valuables off shape on On also shaped to. So if these two objects inside here are much, then we can increase the players score. We have the players score about the top, Cooley said. 20 and stored inside his current score variable. That's increased this. If the object is much we have couldn't score bliss bliss over in the index or hates Jamal. We also have a spine elements with the idea of score, which is just here. This will. I was to craft this elements and then increase it with the players score so we can see this value on the screen. Let's do this now, back over to our statements. So if these two objects are much will increase the school by warn and then select the documents does get element by i d. Then grab it. The spun container, which had the i d off score, said the HTML to be equal to a value of corn school. Okay, good. So just blow this. So after our if section would you just here? We're going to add a l statement. This l statements will run. Is the objects and not a much this will be used to the opposite and then take a point off the score. Let's say else current scar well, decreases by one, then also do this same line here. So documents dot gets element by I d. The idea. Want to grab again the score, then update the ahead smell to be equal to the corn school and then refresh and then give us a go click on the play burn. So now we need to click this much burn when these two shapes are the same. Let's wait for these for the same ghost of all you have worn too free. So this also is working fine. If we click on this one, the shapes are not too much. We'll see. We'll lose a point each time. Great that all seems to work and fine. But before we call this game complete, that is a few small issues we need to address first after the game has started. If we keep on clicking the play born, let's start the game off. And then if you click this multiple times, this will call. The star came function more than months, generating lots of random shapes. Also, when playing the game, we want to restrict the user toe. Only press this much button once per set interval. So currently the user clicks on it multiple times. The score will keep going backwards or forwards. We want to restrict this toe only one click per selection. So let's begin by disabling the start button. When the game is already running, We can do it is in side of the play function. Oh, it's all the scripts on Let's Go to this Star game section here, which is the click handler. First, we need to grab all play button, which has an I d off play, which we can see here. AnAnd Bachtell Start game function just under playing equal. True, let's add a comment to, say, disable the play button when playing so documents dot gets elements by i d. Select All Play button and then we concert dot disables to be equal to true. Let's test this out and then click play. We'll see assumes you click on play that it turns gray and we can click on this button anymore. If we refresh now, I'll play Button is back to normal are we can restart a new game, then we can now move on to stop in the player. Clicking this much Bourne multiple times. So first, let's start this much button inside of a variable. So up to the top of our cold. Let's set of a constant called much button on our familiar document or get elements by I D . The boots and we want to select house idea of much. We had a semicolon at the ends. I have stalled this reference inside of a constant because we're going to be select NIST multiple times. Well, first gone to disable the button once it's being clicked and then reactivate the button once a new set interval is being generated. So down to the bottom, we concert this button to be disabled after it's being clicked. So down inside the compare section, I will do this in the side of the plane section. Let's say much BCN dot disables. He's going to be equal, too true. So this will disable the button after is being clicked inside of this on click function this bulletin that needs to be reactivated for each cycle so it can re enable it each time a new shape is generated so off to the set interval section. So just after here, right at the very talk, we can also select much bt n dot disables, but this time to be false. That's test result. Refresh the browser. Complain. So now our game starts on if we try and click on the much Bourne multiple times, the 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 customization ins. Make any changes or play around with 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 on Bye for now. 40. Introduction to regular expressions: Welcome back, guys. For now, we're going to look at something which is really useful in John Script on the seas. Regular expressions, regular expressions, often shortened to rejects, is a way to find a pattern or combination of characters inside all of a text ring. 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. So head over to the start of files and then inside a sidebar. Let's go down to Number 1st 2 which is introduction to regular expressions Inside. Here we have some simple Laura MIPs, um started text, which you just start inside of the P elements and then opened up this example inside the browser. So first we can grab these text elements just here and started in side of a variable to begin working so down to our script. Let's start with the let's text equals documents dart query selector. So we want to grab RP elements, which doors over text. So at the scene as a string and then we want to grab the inner hate schimmel. We can start with the basics on searches text to find the location off a particular word as a string. So just below this, this is a pretty simple one to search for or text only to do is say, text, don't search. And then inside the brackets Conard a string which you want to search for. Let's search for any of these words inside of a string. Let's go for I met on these in the quotes AM 80 and now we can. I'll put this to the console. So first, let's store this result inside of a variable. So let new text equal to a search. I never could do a console log for the value off new text you that say, even then over to our example. Open up the console and we get the value off 20 free. This is because the word which was search for you know, a text string begins our position 20 free, which basically means this is 23 positions in from the start. So let's calm until this example on. Take a look at a new one and in fact will remove this console log or could discount on actual. Just paste it down on the bottom so we can use it with all the examples above. So now we've looked at finding a string inside of all text. Want to find a match? We often want to replace it with something else. For this, we have the replace method. So down on the replace text, there was strength. 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 1st 1 we're going to add a string to search for. I'm going to search for La REM, which is the first word insider 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 choose in with our chips. Remember, also have counsel log of new text down to the bottom. So now if you reload the browser and take a look when now see your first word of law room has been replaced with chips. This works great, but this because we've added the word Lottum just here we have a capital l So much is that with string, it was changes to a lower case. It wouldn't work to change its well. Okay, cell refresh. I will see the word Laura hasn't been replaced this time. This is because this replace is case sensitive. Instead, if you want to perform a search which is case insensitive, we can add sour pattern to search for inside of the forward slashes. So back over to our code. That's copy this line from before. We can leave this example in by comment in this out. Now welcome paces back in underneath this replace text with a regular expression. So rather than having a text string like this, we're going to create a regular expression inside of two forward slashes. Okay, let's search for a word off Florham and then we can r to the I modifier just afterwards. If we say this and then refresh, we see now the word Lottum is now replaced with chips, even though the l is lower case. So the word Laura appears only once inside of this text ring. But if wanted search for something which appears multiple times, such as a simple e character just like this, let's go ahead and take a look at this. So the company's example and then comment is out, and then paste is in below the eye. Modify section so we can see here that the I modify. We'll do a search, which is in case sensitive, but you will only replace the first much inside of a string. So we changed law room to be E whether these multiple occurrences number places with a capital A. We load the browser. Now we see the only the first occurrence of an E is replaced. There is no more capital A's inside of a string. However, if you want to replace all occurences, we can use the G modifier this time. So that's copy this line of cold here. Common this out and then paste. It's under the G modifier. All we need to do is change the I to be a G, reload the browser and now we see that all occurrences of an E is being replaced with a capital A so G stands for global and will find to replace all. Much is, you know, texting Rather than stopping after the first born, just like when we used t I modifier, he will only searching for one letter. But if you want to march to multiple letters, we can add that these inside of square brackets Let's take a look at this. If we copy this line here on common this out, let's leave this in the start of files. For future reference, place this in under the square brackets section and then inside of old forward slashes we conard some square brackets and then inside the square brackets of research for hey, Judge G or S let's make these lower case through the G modifier. And then it's odd something which stands out, Let's add some stars on in capitals will say replaced. So now we're research through the string. The first occurrence off Hey, H G or S will let it be replaced with this string. Here, say this and then reload on scrolling up we can see the first occurrence has been replaced with a string here again, this also stops after the first much if you wanted to replace all occurences of hate. GRS looking again at the G modifier. So let's copy this line here, coming this out and then at this under the G modify section. So after our regular expressionist aren't the g modifier say this, you can see the all marches have now been replaced. The square brackets also works for numbers to, so let's copy this. Common this out on that. This just above our council. Log inside the square brackets instead of searching for our letters. Let's go for the numbers free fruit to six. So this will find all numbers from free food to six. Remove the G and then replace it with this texting here. For this to work, we need to add a number into our text above. Let's go for number five. This in. Reload on this, trying to look for it. There we go. So there's our text or replaced in the position off the number five. Good. This is a first look at using regular expressions too much a pattern. If you google Mozilla regular expressions. Just do a search for Miss Ella Regular expressions. You be able to find a lot more examples under this regular expression section, so you click on this and then go over to the Mozilla Documentation will consider there's lots of different ways to create puns. You would scroll down some of these regular expressions, a quite complex to on. I'm not going to go through all of these, since most are specific use cases, but you can find, almost anyway, much apart in using regular expressions. In the next video, we're going to build a small project using regular expressions to take the user's input and perform a find and replace. 41. RegEx find and replace project: welcome Buckeyes in this video, we're going to be using regular expressions to build a simple find and replace up. Inside. The start files will have a basic form where the user can type in a word inside the fine section. This will and find a word inside its original text. A number can choose a word to replace it would. Once this replaced button is selected, this replaced button will trigger a function which will make always happen. Let's begin by idea an event listener to this button. So over in the start of files, this is number 33 which is rejects. Find a replace. So down here we have our form with the finding puts the replace imports and then all button , which has I d of replace BTM. Let's go down to our script, which is down at the very bottom. Let's like this weird documents thought get element by I d. The idea, like we've just seen, is replaced BCN and then at an event listener. Inside the brackets, we know we need hard to values. The 1st 1 is the name of the event, so we're going to be listening for the click events and then we're going to trigger a arrow function just like this. So inside of here, this four things we need to grub and store inside of variables. We need to grab the form inputs for the fine section. We need to grab the input for the replace section and no money to grab our original text, which they will first set of p elements. And then when it to grab I was second p elements which is going to contain our text with the replaced words. Let's un in these four variables inside off our event listener. Let's start by grabbing our original text on. Then I will modify text inside the P elements. So let's original text be equal to documents. Thought query select all the original text is the first occurrence off the P elements. So on the P tight inside here, that's index position zero. Then let's copy this line and paste in just below this one is going to be the modified text on. The only difference is the P element is this time art index number one. So now we also need stalling the user inputs which has an I d off find on also replace Let's stall these two inside of variables as well, so less I were fined text equal to documents does get Ella moons by i d. The 1st 1 was fined and we want to grab the users value we don't value. Copy this line and paste in again just below Aunt, this is going to be the replace text. So that replace text on the i d. This time he's replace. Okay, Good. So make sure yours looks like this example here and now have all the information we need stored in variables. So next we need to grab the inner hate Shamil off. Original text on this is this text ring just here. So at the very bottom of our function, it's a original text thought in a hedge demo, the scrubs, all the sex content from our original text and then we're going to use the dot replace method which we looked at in the last video. This takes an hour to values. The 1st 1 is the word you want to find. This is stored inside a variable cold find text, then separated by a comma. The word will want to replace it with on this is stored inside of this. Replace text variable. So replace text as our second value. A cynical, not the end a number. Install this inside of available called new text. Finally, we want to help put this new text to our MTP elements, which is just here. We would have a reference this called Modify text. Let's out this down at the bottom. So modified text dot in a Hey, Jamal is going to be equal to this new text just here. Okay, good. So I think we're ready to go with the browser and give this a test. Let's search for one of our words. Let's say sit. So find the word of sits and then replaces were stunned. Replace on that. Nothing appears to happen if we look a little closely and we had this and it once more. If you click on this, replace button and watch very closely down at the bottom, we can see that briefly, the new text will flush up and then disappear. This is because this bullet is inside off 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 and now clear at the top. Because the page has done a refresh fixes, we could prevent the default behavior off this event. First we can onto the which is the details off our event inside of the function parentheses . Then we can prevents the default behavior inside the function body. We've e door prevents default, so this will stop our form from submitting and therefore won't see a page refresh. That's right. It's a game. Will place sits, withstand, click for place and there we go Under our new tech section. We see the word sit has been replaced with stand. I'm no longer see a page reload. There is also another way to fix this too. Instead of having e da prevent default, we can remove this. We can remove our e available from here on instead. If we go up to the button inside of old form, we can also add the type of button A. Now, this is a type of button rather than submits. This will stop the default, submit action. So now let's give us a go on. This time will replace Ipsum. We've any of the words it replaces. There we go. So a new text now houses replaced word. The final thing to look at is how to make this search case insensitive. If we search for the word Laura, Um, using the small L on a place is weird. And if in it replace, we'll 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 are there were two forward slashes and then the I modifier just like this. However, if we were to say this refresh on, give this a go type in the room, I'll replace them words. We'll see that this still does not work. To make this work, we need to use a constructive function so back over to our scripts. So just above new text, we're going to say new regular expression just like this, then inside these brackets going to pass in this fine text. So I descend Asil, first value separated by a comma. We can add the I modifier. This constructive function will compile the results, including this modifier. I never consol this inside of a variable. Let's say find we have modifier and said this to over constructive function. The number can use this variable name and passes in to our replace. So rather than what we have here, that's just possibly in available name, you've got safe. And then let's try this so low room. But in lower case L it replace. And now we see this is working great. So this constructive function compiles at run time, which is ideal for Patton's, which may change. Although we know the pattern we're 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's We've built user interfaces, different layouts, looked a responsive design on also how to use JavaScript. This is all great and really important that we understand all of this from this section onwards, we also going to looking more at the back end of websites. How are websites will interacted servers, different data sources on generally how they communicate with external sources. When are we use interface is communicating with servers or generally requesting any information, the arts and 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 coming, of course topic on their own, both having at least a general understanding will really help us understand what is going on. The first concept we going to look at is the client server model, As you can see here from the slide off 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 or computer. Basically, the client is the one which makes the requests. So Charles requesting any Web pages which wants of you on the right on side. We have the server, which provides these resource is all the services which the clients is requesting, such as our Web page, which you will send back to the clients if it has its. When a client makes a request, such as a question, a Web page, this is called a H T t P Request. Http stands for hypertext transfer protocol. This is the standard all the procedure used when transferring hypertext data across the Web . So the client goes ahead and makes the request, and then the server will trying to respond to the request. If possible, it may respond with things such as the hate Schimmel required for the Web page, any images or any scripts which may be needed to. So although this may sound a little complex, it is something which would do each time we visit a Web browser. First of all, if we go to the Wikipedia home page, but but let's hope you'll know it sounds. Hey, https is at the beginning. This is like the hate TCP we mentioned before. But nowadays http secure is more commonly used as it provides an encrypted version the greater security and privacy. Once we enter a girl on his answer the Web browser or no case, the clients is now making a request for this webpage. If everything went OK, 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 over claims to such as a computer terminal, which is also a clients. Let's open up the terminal, make us a little bit bigger. So we used the terminal more. Once we get to the node section of this course on, you don't need to follow along this 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. So we do this point time playing it cool. American Taipower. You are old, just like we looked at before inside the browser. So hey, https gold on twofold slashes and then www dot Wikipedia. That's Ogg and then hits Answer. And then if we scroll up to see a lot of information, is being returned back to us. This is all the hate smell, which is used for the Wikipedia websites. A lot. This will look common, such as he gives it was span tags on all the various classes, which added to these, so it can be a little bit difficult to read on. This is because a terminal doesn't know how to deal with this hate schimmel, which returned back to words so it's just displayed as a plain text. On the other hand, a Web browser knows exactly what to do with this HTML. So if I go to the browser right click and then goes of you paid 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. So the difference being the Web browsing those house to deal with this information and how to then converted into a Web page when will make a hey http request that is various request methods we can use, he would concede four examples called gets post put and elite. What is more in these form, but these are common ones together started when we want to get a Web page all the one to get some data, we can use what's called a get request. This is what was used in the browser. To get a webpage from Server Post will do the opposites on submits and data to the server for processing, such as adding a new record into the database. Next, we have the put request on 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. I'm replace it. This is used commonly for updating some data. The final one is the leads, and this is pretty self explanatory. This will delete the resource or the data, which would specify well we use from these methods juniors course, particularly in the final project when interacting with a database part. This response from server is also a starts cold. There are many different responses, but here are some examples. A code of 200 means the request WAAS successful aren't the requested resource. Is Sam back to the clients inside the body of the response. Next we have the free Owen response, which is a redirection message. This means the resource which we're trying to request is being moved permanently on. We usually get the new U R. I given with the response before a warm response means the client is unauthorized, usually requiring authentication before receiving the requested response. Bono for is a common one, which you may have already seen when browsing the Web. This is common when a page could not be found. So she's when a user miss types, you are all so a lot. 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 you return back to any Web page such as Wikipedia and then right, click and then inspect inside here we can go to the network top. You said that Stop here and then he refresh. A number can see we have a lot of different file names, which returned back to us. We have the main page. We have some various JPEG images, have some scripts, some PNG images and scroll and down with the all these returned back tables from the server . We can also see the stars cold to on. Most of these are code off 200 which we looked at before on this means the request was successful. If you look at the main page at the top, we can see a status code off three or four, but its home page. This means the pages not be modified since the last request. Therefore, the brows, you can use what is called a cached version. Cash is a temper. Storage on browsers will use the cash to store our webpages once we visit them, so that could be access faster and also reduced the need to keep making additional server requests. This is why, if we go up to the top and click on disable cash, it re lows when now it's seat at. This main page now has a status code of 200. This means we're now making a fresh request to the server, but it's where page rather and storing it inside the browser for quick access. So now if you wanna check this and then refresh, we can now see the stars code off three or four, meaning we're using the stored version inside the browser rather than making a new request . So this is an overview of how things work between the client and server even by having it, just a basic knowledge of these concepts will really help you understand what is going on behind the scenes on really help you as a developer. Next they'll prove looking at AP eyes and how we can use them in our websites or applications to get data from external sources. 43. What is an API?: this, a P I part of the course is going to be really exciting section. If you have not worked with any a prize before or generally any data from external sources , we're going to begin by looking at AP Eyes on this stuns for application programming interface, which sounds really complex. Both is just a way for us to connect our websites or application to another data source. It basically defines how our up can talkto over after services. Some of the biggest companies out there have a Navy I for developers, which you can connect with. For example, we could create our own music application exactly how we wanted to look and then use thes Spotify ing a B I to search for songs or albums or even access any user data such ours. And he saved tracks and then display them right there in our own application is also YouTube a P I, which we can use to search on display videos inside of our own projects. This also provides a way for these companies to allow developers to safely access the data which they allow. Some of these providers will require registration on also on a p I key first before granting access. Just like earlier in the course when we looked at using Google maps and when we had to register and provides an A P I key things to work. So how do we access this? AP I data? Well, not all AP. Eyes are exactly the same, but generally will make a request to a girl. This is a get request, as we learned about in the last video, because we want to get some data. This u R L is called on endpoints, for example. This is fortifies AP I endpoints he other top. This endpoint is usually extended to be more specific about the data we want to get. But example Weaken Graham. Some album information. We can get albums with a specific I D. We can perform searches on, even retrieve a user's playlist. Information to give you a better idea of how this works is a simple A p I, which we can use with information all about types off dogs. So let's head over to the browser on. I'm gonna go to the Dog CEO, which is www dot dog Don't CEO. Ananta grabbed the A P I would you forward slash dog Josh A p I It's answer. You can see this is the Internet biggest collection off open source dog pictures. So this one I was to search through the dog breeds such through the pictures and just generally gather information which you want to find. So this will give us some examples off the end points we can use to get different dog data . This is useful. Start with because we don't need to register or use any a p I keys to get started. So school and democracy, our endpoint ago, which is the first part off the Web address which we just visited inside the A p I work and then filter by breeds and then select the images and then select a random image. And then we return would some Jason Data. If we go over to the documentation, we can look at some more examples. Okay, So the first example will see is the list or breeds. So this is the Ural endpoints we need to visit to grab all these dog breeds in Jason. Former. It's so if you click on this copy and then paste is in the browser returned back towards is the information in Jason Former If yours looks a little hard to read or doesn't look quite like this, you may need a Jason browser extension the former this into a more readable structure. There's lots of different Jason for martyrs we can use, but I'm using a one called Jason for motor. So go to chrome Extension and then Jason Formosa. You can follow along with this link and then aren't this as a chrome extension just by clicking on the ads to crumble another top? I already have this installs. So I'm just going to close down this tub. No. So Jason stands for JavaScript object notation, and it's a syntax for exchanging data over the Web. It's formatted like a JavaScript object, but it's actually language independence, meaning it could be created on reds by over languages, too. You can see a object like syntax using these round in curly braces. We also have the name value per Sachar status, off success and then a scientist message. Here we have an object containing all the dog breeds, which you requested. We could 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 a bulldog isn't Array, which contains two different types. If we head back over to the A P and documentation and then if we go down to breeds list, you can click on the Jason information for any different type. All breed, which you want to check out our Mukasi, which images we have associated with these. So let's go on a boxer on to take on the Jason data so you can see by the u. R L endpoint at the top with filtered in a breed down by the boxer, and then we'll access in the images, Then click on any of these images to and then see which images provided to change the breed . All we need to do is change the sorrow rather than having boxer. Let's changes to be something else, such as Hound and never get a list off difference images for the hounds. Let's try one more. Let's go for Labrador on. He's a list of all images for the Labradors, so this is the Jason four months, and it's probably the most commonly used type something which used to be popular for data transfer to also former it's called XML. Here is an example of the same data, using both Jason on the left on XML on the right, XML is very descriptive. Using semantic tags, which looks a bit like HTML, you will still often see some a p I data supplied in external form arts. However, most now have a Jason version two or even just Jason by itself on more modern AP eyes. This is because Jason is a lot shorter on lightweight, as we can see over on the left with the same examples. So now we have some background into what an A p a is and how we can use the data. Let's now get back to our song find application, which has started early on the course. Earlier, we created the user interface, and now we're going to move on to grubbing our A P I data on showing a list of songs on the screen. 44. Fetching data and query strings: earlier in the course, we created a hatred ill structure for I was song Find the layout. We also challenged you to add some styling and layout, using the CSS grid to make things look even better in a section. We're going to be completed this project by using an A P I to pull in some really song data which weaken news from iTunes. We'll also be use any job script, fetch a P I, 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 of our song Find a project from earlier. So 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 or vaginal file. We created some sample data for other songs. We're going to be creating this section dynamically, using Java scripts and then grub in the song data from the iTunes, a p I. So now we can go ahead and remove the contents of this main section, but we'll just leave one in for reference. So let's go to the index page AnAnd scroll down to the main section with the idea of songs . I'm going to live in one of these articles and then remove the five extra ones in from below. So for five, right down to the bottom of the clothes and main suck and bring this up. So now we're left with just one song. Give that save and then refresh the browser. The next step is to craze our script file. So this is going to be a child script file. So right click New File and they call this the script dot Js. Then when it's linked to this in the index Ohno scroll down to the bottom on just before the closing party tank. That's odd. I was Script closes off then, as it the script sauce. This is in the same directory so we can just references by script, don't you? I guess if that save and 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 so head over to you. Google honestly was searched for the iTunes search a p I Okay, so let's scroll down So the one we need is the iTunes Search, a P I, which is on the Apple Developer website. Let's click on this. Okay, so let's start by selecting the search from the menu. It's a click, and then we can click on Construct a Search. When we discussed AP eyes in the last video, we mentioned that we usually fetch the data by connecting to a girl, which is called in endpoints. You can also see the A p I endpoints provided by iTunes, which is just here. So it's iTunes, the apple dot com forward slash search. And then after the end points, we can add some key value pairs to get the information we want Notice. At the end of this you are role is a question mark. This is just a separator to separate the girl from the queries which wants us. I will take a look at these in just moments. This u r l with the promises on the end is called a query string. If we scroll down, we can see some key value pairs in this table here to start with the search term. This is probably the most important for our use. It's a term which we're going to be searching for to find our songs from the database scrolling down. We can also search by media to looking narrow this down to search for on the music. Okun even include things such as movies or podcasts. We can also limit our search to so we don't get too many return values. It was cool down. We can also see this limit promising here. I will also uses limit to so we don't get too many. Search results returned. But it was so to see these work in in action, we can simply type these into the browser. Let's go up to the top. So this copy this, you are well and then it's on to this in a new Tom. Before press enter, we need to add some key value pairs, but its search to work. If you go back to the documentation, we can use any of these key value pairs, which we looked at before, such as a search term. So after the question mark, weaken our to term and then equal. Let's go for beyond, say and hate answer, but then have a text file, which is downloaded now, making open this earth on See the contents so we can be a little bit hard to read at the moment. But we conceded its heart. We have 50 results returned two hours, followed by an array off results with all the information about each song if wanted the limit this we can then add some extra values. And I'm pacing our query again. The term it will be on, say, a number. Conard, Mork Yvonne, You Paris This query string separated by the ampersand to the Amazon. Here a number can use limits, which we also looked at before and set this to three results. His answer. We have a new text file download in. Let's open this up and now have a result counts off free on a lot less data. We just have free individual tracks inside off the array. See this more clearly. Let's copy all the information from our text file and then close this. Go to Google and then let's search for cold Beautify. This is what we need when he called beautifying toe ogg. Open this up. Okay, so we're going to use the Jason viewer to see how this looks So on the left we have the Jase on imports, which you can paste in our information from the text file. And then we can click on beautifying in the middle and see the results on the right inside Click on the cross in the top corner to make this even bigger. And 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 1st 1 is an object which contains all the information about the song we have some you RL's for the artwork on will use these in our application to get the images for each truck . We also have the truck i d of the artist name of beyonc. We have a truck name on lots more information about the song. So this is all Jason data which we can use in our application. So now we know how to get his data using the U. R. L. We can now use fetched actually bring this data into our project. So now let's go back over to visual studio code and then into the script, Doctor yes, but it's helping going to access the fetch a p I and then inside that he with us in the URL , which wants access so paste in. But in fact, we need to go back over to I Joon's and and copy the A P I endpoints on spaces in between a quotations. So now if we give this to 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 a sign it's fetched to a variable on See what's happening with a console log. So says a constant called data on set is equal to or fetch below this weaken council log. And then it's passing the data, which is a data returned by this fetch, then over to the browser. And then, if we're right, click and in fact uncheck the sounds in the console. So let's refresh so we can see we have something that called a promise returned as a response, which appears to depending. Okay, So before we go into any more detail, let's try one more thing. Just after this console log. Let's do a job script set time old, which is going to run the same console log after two seconds. So inside here, capacity in a year. Six little function. I never copy this console log. Place this in Atacama on will run this after 2000 milliseconds. So give that save and then let's return back to the console and then reload. But if away two seconds when Now see there is a second promise. But this time it's resolved with a response. So these results, which will see inside the console because of two things first of all, when using fetch it will return what is called a promise on second of all because the request is what is called a synchronous. So don't worry. If you don't understand what either of these concepts mean at the moments, we're going to cover what both of these mean in the next video 45. Async code and promises: in the last video fetched some data using the iTunes, a p I. We all put it the same data twice in the council, one immediately and then a 2nd 1 after two seconds. This gave us two different results. Which of both promises? I will take a look at what these are very soon. The 1st 1 we can see heard a result off pending and then the later one has response off resolved. Do you understand why this is happening in the first place and why we need promises? We first need to understand what a synchronous Cody's. Some programming languages such as PHP at the opposite PHP is class stars. Synchronous this means when our cold is ready, is read from the top of the file to the bottom sing Chris code such as PHP. We'll 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 off JavaScript code works a synchronously takeover fetch for example, if the request for the data it takes a long time to return back to us, we'll be blocking the rest of the cord from room while we wait for this data to come back. So instead, what will happen is this line of code will still run 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. So now will you send the request for this data? We're expecting a response that sometime in the future, we don't know when this data will be returned back to words or if the data from iTunes will come back, Asshole. But this case, we have what is called promises on this is what was returned back towards from before. When we looked at fetch in the last video, we sent off the request for our data. We immediately run a consul log and this had the results or penned in which wouldn't see here. This is because the program run the council log before the data was returned. After waiting two seconds, our data must have been returned because this console log was then resolved so over to our code in visual studio. Close your sidebar dome. So let's take a look at how we can handle this promise. First, we can remove these consul logs on clean up our code, leaving dusty, fetch other top. And also, we can remove this constant here on a semicolon at the end. So 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're in the cold inside off dot then dot then could be chained on the end. Just like this. I want to make it more readable. You often see it on its own line. It's less and answer and drop us on the line below, then decided thought then we can add a function which you want to run. So I'm going to add a s six r o function just like this. This works was like functions we have already seen. It takes in the response inside of these prophecies as an arguments response insider here the names of two words. But response is fairly descriptive. So I'm going to leave it as this. The response is just a hate TTP response. Therefore, we need to extract the Jason data in the response body use need dot Jason Method. So inside here, it's a response. Don't, Jason. I never could go ahead on return this Jason data alternatively, when using arrow functions, if the function only has worn statements like in here, we can even remove the return key word on also the curly braces. So at this onto 19 so we can move the curly braces, we can remove the return key word and then pull this response on to the same line. So this will do exactly the same bookkeeper cold, a little bit more cleaner. We can also change as many dot than Casey's onto the end as we like. Then it's on one more, which will run after the 1st 1 has finished and then taking the Jason data so we can do it , some of them with it. So at the second dot then which takes in a function and again, this is going to be an Essex girl function which takes in the data on this data is passed to it from the line above, which is the extracted Jason. Okay, so back down. So our function, we can then console, log the data from all greatly I, the council, that log posse in our data. One last thing before we go over to the console will need to aren't a search term. So about 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 A once more. You can, of course, changes to be anything which you prefer. Give that safe and then reload the browser. Okay, so now have our response. With the 50 results could see returns was we have a result array with 50 values inside of there. Let's go ahead and open it up and then open about results. I'm a concede the individual data from each song again, just like before. When we open this up, we could see all the artist information on also some artwork which will get to use in our application soon. If you want to marry is down on, only show the results Inside the console, we can say data, the results you that save and then refresh. And now we just have our 50 results that I'm also going to remove is quick to spring from inside off the fetch. So could this out. I'm never going to create a constant called You are old. I've been stole his query string inside of here. Then all we need to do is pass in, the girl s over variable and then refresh and check. Everything is still working. Okay. Okay. Great. So there's about 50 results, which is the same as before, So everything is still working. Okay, So the daughter, then section off the promise handles what to do when a response is resolved. If we have an error on the responses rejected, we can go ahead and chain a dot catch on to the end to handle this outcome. So right at the bottom, we can say dot Catch. This is a function which we're going to take in the error. Criticize an Essex are a function which simply does a council log. And then inside he we can say so. Let's go for request. Failed then a calmer then after he would compassion our error message like this. So forgive that safe if we reload the brown so we don't see any difference because the request is working. So we're not gettin any areas passed back to us. However, if we create a type of mistake in the URL, let's delete the e from there and then reload When Now see our error message was being caught with the dark catch. Statements on this is running our text off request fails, and then we have our error pastoral function. Okay, so let's go back to visual studio on Reinstate. So you are, well, check everything is working fine on goods ago. Great when I'll have our data which were pulling in from a joon's aunt in the next video, or begins to use this data to create our elements to display our songs in the browser. 46. Map through results: Well, no, no, we have the data which we need to create our song listings inside off the main container of the index file was it index html on inside its main section. We have left in place one song list in and we can use this as a guide we constable looping through all the results which we get back from our a p i and and construct a new article section just like this one for each some results, creating all these same elements using JavaScript inside of the final Don't then section off all promise. Therefore, we know we have the data which we need to work with. So let's begin by commenting out this council long from the script. So let's go down to here comment this out and then we can store data dot results inside of a constant. So let's copy data dot results from here set a constant called off fists on set this to data results. Now we can go ahead and use Mup to loop through each one of these results. The blow here on again, still within the final dot Then section we're going to return artists, which is our constant use here don't muff. So then each result gets we want to construct a new song. So to do this, we need to create our elements. So back over in the hay html, which we've seen before. First, we need to create a article, which is a rapper when it's created image elements. We need two sets off P elements, one for the artist name. I'm one for the song name. And then we also need to construct a audio player, which is going to play the 1st 30 seconds off each song so we know how to do is already by using create elements. So let's begin by doing this now in the script. So in side off, Oma would say Const. So let's first start with the article on set is to be documents daughter create elements. Sounds the elements want to create is the article. So that's you. Pick a. This on this one is going to be the artist this time. It's going to be AP elements. So one little trick when we're creating multiple variables is rather than at in the constant keyword each time. Instead, we can remove this and just separate these with a comma. So just like that, and then blow over artists within Copy This based in again on this one, is going to be for the song. The song name is also a P element to So now it sounds for 4th 1 which is going to be for the image this week. Course wants a image elements just make us I am G. Okay, So now after the image, we also need to create our audio elements. And then finally, we also want to create a source elements honestly, going to be the audio source which is passed in its it audio player with the file path off the music once play so the land for the final one. Let's call this audio source on this could be so with the color from the ends. Okay, so now we have our six elements created using javascript and started inside a constants. We can now search the in hate smell for these text elements. So I've got to different sects elements here, so we want to set the inner html. We also want to set the source for the image on audio elements to. So let's do this. Just below other Constance. Okay, so now, for each results will get back. The information is stored inside of this result variable. So first of all, let's do a quick console log on, check out the information which is returned back to us on stored inside of results. So because I save and then over to the council and now you can see for each song we can open this up and find out all the information which is associate ID. We eat song. So starting with the artist who want to grab the artist name If we open up this object, we can see the artist name is start in the property called artist name. And if I could lives council log and just for the moments, we may need it soon. Okay, So let's begin by selecting the artist. So artist thought in html. So inside these p elements were going to and the name of the artist where no working accesses with results and then adults artist name, which we're seeing inside the console from here. Next up, we can also answer the in a hedge smell for the song name, which again is between the P elements stored inside its concerns called Song So Song Thought in a HTML this time is equal to results thought if you go back over to the browser , we want to grab the song name So if you scroll down, we can see the song name. It's stored inside of truck name, truck name insider here than the image sauce. So I m g source is equal to results. Start. I want to go up the artwork associated with this song. So let's go for our work. You are all 100 on this relates to the science. This is 100 pixels wide. So I'm going to copy this and paste this in. Okay, so we mentioned before we're going to have a audio player on this audio player is going to play a preview, which is the 1st 30 seconds off the song. We can find this audio preview if you scroll down to preview, you are ill, so scroll down on and we have it just here. This is a link which is passed in from iTunes to the preview, which you want to play. We can answer this preview u r l to the audio source so Let's do that. No. So all your sauce and then hot sauce is going to be equal to results. As we see before this, he is preview. You are oh so capital. You also when working with Haiti mill audio elements that is to appear on the screen. We also need to aren't the controls attribute to of Wise won't see anything to click on on the screen to do this Underneath the audio source, we can select the audio player and then we can use daughter set attributes. The name of the attribute wants art is controls on. This doesn't have a value, so can even empty string. Now I can answer these elements to be a child. Elements off the article Rapper just like we have with the example just to you. So back over to your script. We need to upend our artists our image, our song on also the audio to be a child off the article Let's go down. I'm can also remove this console long so we have our article stored at the top here, which is an article elements. So all these elements are going to be a child off this article the blow here would say, Osco, daughter, upend child. And then inside of here we can start. It's passing our child elements. First of all is the image. Let's pacing three more times. We also want art to the artist, the song on also the audio elements. And then finally, we also need to upend the audio source as a child off the audio elements. So that's like the old Leo Doors upend child honestly, going to be the audio source. So Anderson rates and now have an article with all the child elements inside. Well, no need to go ahead. And aren't this article to the main container? The main container is this main section here with the idea Songs on This is going to contain all of articles which were having the results so back over to our scripts. To do this, we need to start this reference to the main section inside of a constant Let's do this art the top. So we just after I would much who can say const on a call to see some container and said this to documents does get elements by i d. The idea want to grab Waas songs so this much is up weird at this section here. Okay, great. So now we have the song container. We just want that at all of these articles to this container. So down to the upend child section, we can select the song container again. Endorse a pen, child, An impasse in each available article. Now, if everything has one. Well, we should see our song articles, but each song returned by the FBI. So give that save on closes. We load the browser on. There we go. We now see I was song data from the a P I. We can also remove with demo one from a fall This article from insider here, bring this up and reload. Great. So let's see how this is looking inside of the developer tools. So right, click on this fact on if you go to our elements. So here we have the main section from before with the idea of songs. If we open itself nested inside, he will have all of our articles for each song which has been returned from our FBI looking open up our article on see all the elements which were hundreds using a pen child. So we have the image. We have the P elements with the artist Name P elements with the song title A name we have our audio player If we open this up nest inside is the audio source which we are needed well about the script. We added this all your source of the child to the audio elements and that's what we'll see just here. Also, we can see the controls attributes which were added to If we remove this, let's go back. Cummins out the set attributes and then reload. We can see we don't have any audio player years now on the screen. Let's remove this on this bucket. Okay, good. So congratulations. If this is all working for you, you successfully pulled in a p I data from an external source. This is a big part off our project now done in the next video will make use of this search bar so we could type in your search term to when I was a search for different songs rather than hard golden in a search term into the you are role which was done here 47. Creating our search query: Okay, so we now have a list of songs displaying on the screen, which is all being pulled in from our A P I data. At the moment, though, we're using a static query string i e. We typed in the search term in the u. R l just thought it stop here. So this is not what we want to use. Things will be a lot better if you could type in a search term inside of this search bar inside of our webpage. So to do this, let's head over to our script dot Js file and first, when you to set a veritable store all search term in. So let's go to the top of the Patria, make a little space on we use a let on call his term sort of again. Well, let's set this to be a empty string. Next up, Let's Christ a function which is going to be responsible for updating this search term each time a user types in it the input field. So, const, off dates, Um and it's going to be a Essex under the function on inside of human can update this search term. So let's update the term to be equal to documents. Doors get element by i d The idea want to grab Is this input from the top? So let's go down, Teoh. I was searching boots. Anise has an i D. Off search inputs. So of course we can use this over, you know, get element by i d. So that's our search import insider here, just like that's and then we want to grab the value by using thought value. Okay, so we're going to go ahead and figured its function very soon when the search Boone just on here is clicked, often are makin aren't. And if statements to check if the user has actually entered something inside this input. So just after this term, we can add. And if statements So that's Jack. If there's no term, Ah, the term is equal to an empty string. So if the user has not entered anything into the import weaken aren't on alert with some tax saying please and so a search term. Okay, so first we check in. If the user has actually entered something, they're makin RTL statements just after this. Okay, so this else statement is going to run once I were users type in a search term. We know all the cold from below is working on pulling in the data which we need. Therefore, we could all the way down from our constant of u R l. Let's cause all this out right down to the very bottom. So could that we command or control X inside off the curly braces for the else statement paste this in and it's just indebtedness. Let's make a little bit smaller on intense all this section from before. Okay, so now this is all in side of the l section. This should all run when we type in something in the search bar. So now all of all, fetching off the data are constructing our articles is now in jail section. So now have these search terms stored in a variable at the top. We can no passes into OU our role, So remove the term or fiance from here we can as a query strings, which was a dollar symbol, E. Coli braces an impasse in autumn. But it's to work. We need to remove these quotations from starts and ends only places with tactics and then finally to run this function, we need to add an event listener to the bottom. So in our index or hate smell, this is the boat on which you're going to trigger our search. So right down at the bottom of our script, Doctor. Yes, We can add a constant off search button. Also beat again equal to documents. So what's query selector? We want to select the button. I never can add an event listener to the search button, so search BCN dot aren't event listener. We want to listen Oh, for a click event. And then we want to run the function at the top, which is called Well, dates, um, which is just here. That's passing update term. I see coal block. So I think they should now be everything we need to get things working over to the browser on. We can check this out so reloads. And now see our songs have been removed because we don't have a search term anymore. Let's try it out in a search term. So let's go ahead. Shiran its search and we seem to have a problem somewhere. So let's go back over to the cold. I fact checked the console on no errors inside of this. Let's take a look. So search button, which is bigger and updates. ERM well, it's, um, on the way you all wrote. In fact, he would just aren't in the name of the search term has been before when he started term is equal and then passes in just like that. So it gives us a even then reload on. Try this once more. It's such on. There we go. So there's our results for Ed Sheeran. Let's just try one more that search on. We can see that there is a problem, so we still have the results from Ed Sheeran as before. But if you scroll down right down to the very end of the age, feudal moms, we can now see that the Queen editions have been added to the end. So if you search for more than one thing, the results are added onto the end off the last results. Rather than replace in what is already there sounds, this is something which will fix in the next video 48. Improving our search: in the last video, we made great progress by wired up our search Putin at the top of our website. We also uncovered a small problem. This is when a second search term is performed rather than replacing the original results, the added onto the end. This is what will be fixing in this video. All of our songs are child elements off the song container. So when it's check if the container first our songs. If it does, then we need to remove them before researching. So let's get started by moving our Some contain a reference to the top off script. Let's go back to our script, don't you? Yes. And then if you scroll down to old song container, which you just here, let's cook the sounds. Although month American pace is at the top of Allscripts now, this has moved to the top of our script. This will give this veritable a global scope, meaning can access it in multiple locations. So now if you go down to our l section, which is the section here before we ruin our search query. First, let's ruin a wild loop, which will check if the song container has a child elements. So at the top of the L section here, let's say, while some container dot first trials. So this will check if the song Container has any child elements. If it does, you want to go ahead and remove it. So it's a song container thought removed, child. Just like that's. And then inside removed child. We needs passing the song Container Daughter First trials. So as this is a loop, it will loop through all song container. Andi. Each time there is a child elements, it will go ahead and remove it until no child elements are left in the container. So once the container is empty, the cold can then move on to do in a new search. So let's give this a go in the browser, give that safe and then reload. I would have seen searches before So edgy Run. Okay, so now let's do a second search off Queen. It's search, and now our queen results will replace the original search. Great. So let's no finish off this query string by and in some extra parameters. First point set in the immediate to the music. Let's go to the U. R O which is just here. And then after you question Mark would say media off music. And don't forget that. And I'm son 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 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 of the type of media which you prefer. Finally, I'm going to restrict the number off, sir Chisels to be 10. So back to the question mark and I will say limits equals 10 of the, um piss owns. If that save reload the browser. That a search If I go So now how 10 results its search. And there we go. So now we have 10 results all restricted to the media type of music. Great. Our song find up is almost now complete. But there is one final touch we need to aunt We passed in the audio to the audio player to give. Is this song preview. So if you click on this, we now see that the audio preview is working. So this all works fine, but you click on a second audio preview. We see the both songs are now playing at the same time. Instead, what we want is the ability to click on an audio preview. And then it's the pause any over audio players, which you currently playing in. This is the last thing we need to take care of off for this application. A move. 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. Wilma click on a new one. This will avoid multiple previews, all playing at the same time. To do this down at the bottom off our script dot Js file. Let's go right down to the very bottom. We're going to listen out for the play events on the documents. So rather than as in any event, listener to one of 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, so it makes sense to add this to the documents rather than each individual bottom. Yes, well, it's now for the playback has begun on audio elements, and then it will run a function. So let's not. By selecting the document and then dot art event listener, the event listener will want to listen. All for is the play Vint, which would have figured each time the audio started playing demagogues, trigger a function which is going to take in the events. This will be a near six arrow function which will run each time a audio has played so inside its function with 1st 1 store, all of our audio elements into the constant. So So I constant called audio and then set these two documents dot get elements by tag name . The tech name we want to select is the audio time. So this will select all the audio players on the screen and store them inside a constant called audio within wants a loop through all these audio instances and check if any are already playing. To do this one creates a for loop. So for we're going to set the initial value of I to be equal to zero, we want to ski Rudin while I is this on audio. Don't then and then I plus plus. So now inside this loop, what want to do? We want to check if the audio player which is currently playing, is equal to the event dot target. Okay, so now inside of here, I'm going to create a if statements. So we're just time to salt first, and then we'll explain what each part is different. So if although I is not equal to the events, no targets and open up the braces Okay, so when we're inside off the browser on we click on play on any of these songs, the reference to the audio player which we have clicked will be available as information inside of the events. We can select this with event dot targets, which were looked at in the past. So back over in our loop, we're checking if each individual audio elements is not equal to the events dot targets. So therefore we filtering down the audio players, which is not the warn which we've clicked. So anything will run inside of the loop will apply to all audio players except the one we want. So any audio players which you currently playing with audio I would consent dot pause. This will pause all audio players, which you're not the one with clicked on. Therefore, only even one of these audio players playing at the same time. If we give this to save and go over to the browser, it will load on the form a search. So click on search when I click on any of these. So now if you click on to off the audio previews, we can see this isn't working just yet. it is to work. The final thing we need to do is on 1/3 parameter to the event listener. Let's go back to a function and then right down at the very ends just after the final curly brace. Let's aren't 1/3 parameter off. True, to understand what this will do personally to look at something called event capture on problem, he would see a tree like representation off the path right from the window down to the audio player. Remember earlier, we looked at how we receive a lot off information about the events when it's triggered, such as the event target, which just looked up before on even things such as the Mouse X and Y position. Well, no, only to receive information about the elements, which five events, such as an audio player. We also received information about all events in the tree above two. When the event is triggered, it begins. Aren't the top of the tree at the window objects, I'm creates a path all the way down. This is called the capture and phase. Then it goes all the way back up to the top on This is called the Bubble in face for the example would have seen in the project we attached over event listener to the documents 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. So admit city documents works better because we just need to add it wants. And then all the audio place blow it in the tree will notify you because off this events, information being passed open down both. There is a small problem, though some events don't actually bubble and you guessed it. The play event is one of these which dozens. So 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 country face by default. This is set to false, which executes the event handler in the bubble in phase Andi, as we just mentioned, the play events cannot bubble. So now we have the third value of through that's going to save and then go over to the browser on perform a search. And now let's go ahead and click on to off the audio previews. Okay, Great So now we click on a second audio preview. All of the existing audio players will stop. We can maybe understand this better by logging the events to the console back over to our script on just under the pause. Let's do a console log on this log, the value off the events, which is passed just to you and then over to the browser. And then that's open off the console, right click, inspect. Open up the console tab and then it's click on one of the audio players. Okay, so as soon as we find one of the audio players we can see inside the console, we have nine event listeners fired. Civil War to you. Free 456789 We get nine because we only get the ones back, which we have not clicked on. Remember, restricted the number off songs returned to us to be 10 have clicked on one Anamika, the remaining nine in the console because we checked inside the loop. If the currents audio player is not the event of targets, i e. The one which have clicked on. If we open up one of these so back to the console on. Then click on the little drop down here. We can see, as I mentioned before that the bubble events is set of false. Therefore, the play events won't bubble so excellent and well done for finishing this project. Working weird external data sources such as AP eyes on external databases, which will look at soon really opens up the possibilities of what we can do with our projects. So bye for now on, I will see you in the next section. 50. Thank you: congratulations on reaching the end off this cause I hope you. And now a lot more comfortable using JavaScript on working with a P I data. We started at the very beginning taken a look at jobs basics such as if else statements, operators strings on variables. Then we moved on to how well can manipulate the dom, add interactivity to our projects, functions on how we could work with events, recorded a raise different ways to loop over data on objects, all while reinforcing what we've learned with some fun projects. Finally stepped things up by working with a P Eyes promises on fetching data all while building a song Find for everything you have learned into practice. Remember, this is just the third part off 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 full stock applications. So bye for now on, I will see you in the next part of this course 51. Follow me on Skillshare!: huge congratulations from me for reaching the end off this class. I hope you really enjoy it and gain some knowledge from it. If you've enjoyed his class, make sure you check out the rest of my classes here on skill share on. Also follow me for any updates on also to be informed of any new classes as they become available So funky once again. Good. Look on. Hopefully I'll see you again in the future class.