Transcripts
1. Welcome To The Class!: Hey. Welcome to this class. As we all know, learning any new skill can be challenging, and JavaScript is no exception. JavaScript has such a wide range of features and things that can be useful, and this can often leave beginners in a difficult situation wondering where to even begin. This is why I've created this class. Working it from the very beginning, I will show you what JavaScript is, what it can do, and why we even use it at all. This class covers everything you need to know to become a competent JavaScript developer. If you've not taken one of my classes before, my name is Chris, and I've been building websites for over 20 years, and I've also been teaching these skills for over seven years, both video classes alongside leading web development bootcamps too. This is Part 1 of 2, and it will give you a great foundation in JavaScript of all of the basics including arrays, functions, objects, events and the DOM, web APIs, and all the details which you need to know in-between. All these topics are covered in a clear and structured way, all while building a practical projects as we go, including real-world example use cases, and also some mini challenges too. At the end, we also put all of these skills together by building a work-in video player, including fully custom controls, but also a fun shape drop game too, using the drag-and-drop API. It includes a project folder which we'll add to as we progress throughout this class, and it will also develop as a useful reference in the future too. Thank you for your interest in this class, and I'll see you in the first lesson.
2. Share Your Work On Skillshare!: When taking any course, it's really important to
not get in the habit of following along just for the sake of taking
off another lecture. Take the time to
process each lesson, review the code which you write, and think about how you might approach these
solutions yourself. With this in mind, this class is project-based and this gives you the opportunity to really make something
personal and unique. You don't need to get too
lost and divert away from the class and you can even take a step back after
you've finished the class, and come back and make some
project changes afterwards. This will really give you
a good chance to practice what you've learned a
way from the class. Also, remember to share
your project too here on Skillshare and only
will I check it out, but it will also inspire
fellow students too. More information on
the class project head into the project
and resources tab, where you can not only
upload your project, but you can also see
other class projects too. With this in mind, I look
forward to seeing what you create and upload
here on Skillshare.
3. Let's See What Javascript Can Do!: Understanding the theory side of JavaScript is really important, and we'll get to this very soon, but there is nothing like seeing exactly what it can do right in front of you. To see some of the things JavaScript can do, we're going to open up a web page. Here, I'm on the Mozilla Developer Network. This is developer.mozilla.org. This will also work on any other web page, so you can choose a different one if you would like to. I'm not going to show you how JavaScript can be used to control or make changes to any website. Now, just a quick word before we get any further in this video. There may be one or two things which look complex or unfamiliar, so if you're not used to coding or JavaScript, some of this may look a little bit intimidating, but just be aware, this is just to give you some guides on what JavaScript can do. We don't expect you to remember any of this, and we will cover everything we've been through as you progress through the course. Think of this as a little taster to get you excited with what JavaScript can do to a web page. To see what JavaScript can do, I'm going to open up the developer tools inside of Google Chrome, which is right-click, and then go down to Inspect. Let's just make this a little bit bigger so it's more visible. If you are using a different browser, such as Safari or Firefox or Edge, most of the developer tools are very similar, so you should be fine if you want to use a different browser too. But if you want things exactly the same, I would follow along with Google Chrome. First thing we see here is this Elements tab, which has access to all of the HTML structure which makes up this web page. We can either hover over any of these lines of code, and it will highlight over on the left which section we are currently working on, or we could also click on this arrow, which is the inspector, and select any one of these sections or elements on the page. For example, let's go for this level 1 heading and click on this. This will instantly highlight this level 1 heading inside the code, and when it's selected, you will notice over on the right you have this equals $0, and then we see this pop-up just below which says use $0 inside the console to refer to these elements. We can use $0 inside of this Console tab to select any one of our elements or sections, and then we can apply some JavaScript as well. Let's just confirm we have the right elements selected with $0, and then we get back our level 1 heading. We have selected this element, but what can we do with it? Well, the list is huge, and we're only going to scratch the surface here, and we'll cover a lot more during this course. If we again select $0 to point to our level 1 heading, and then a dot, we can see below we have access to lots of different options which we can use on this element. A common one, which we will use plenty in this course, is something called inner text. Inner text is a way to simply change the contents in between the opening and the closing tag. It will have this text of resources for developers. If we want to, we can set this equal to any new string of text. Open up the quotations. We can use single quotations or double, even one is fine, and then we can set this text to be anything else which you want to. Let's go for, I have changed, and then immediately we get back the newly returned text in the console, and we can also see the web page has updated too. Before we go any further, don't worry about doing any of these changes. This is not updating the live website. This is only inside of our own browser. All we need to do is to simply refresh the browser and this will be reinstated back to the original version. Also, we're doing this, we now reset our $0, and this will now return undefined. We will look at undefined in more detail throughout this course. But for now, we can think of it as simply no element has been assigned to this $0. Just like before, we need to go back into the Elements tab to select any one of these sections or elements which you want to work with. Let's go for one of these links up at the top. Again, use the arrow, and we can hover over any one of these buttons. Click on this. We have this button with the ID of Feedback button, which should now be assigned to $0. Let's select this, and we see our button is now returned. Again, $0 and then the dot will give us access to a range of features which we can apply to this element. One of those is the style property, and from here we can also add an additional style property which we want to apply to this particular button. Just like with regular CSS, if you've used CSS in the past, all of the same style properties are available to use inside the console. An example for this could be the text color, which we can set to any value which is a valid CSS color. Hit ''Enter''. Nevertheless, immediately update inside the browser. Press up, and we can also add a second property. Let's go for the font family. Again, we can change this inside the quotes to be a different font family of cursive. As expected, this will automatically update the browser. Just one thing to note when working with styles is, here we see we have the color property set to hot pink, and this works just like a regular style sheet. However though, when we have two words such as font and family, in regular CSS, we would keep this all lowercase and separate this with a hyphen, so we'll write it like this as two words with the dash inside. But instead, when using JavaScript, if we have two or more words, we need to change this into what is called camelCase, and each word after the first one begins with a capital letter. That's pretty much the only thing you need to remember at this stage. We have access to all of the same CSS properties, but we need to type these out as camelCase when using JavaScript. Another thing we're going to now look at is events. Again, we have a dedicated events section later on in the course. But for now, I just want to get you a little bit excited about what JavaScript can do when interacting with the user. To see an example of this, we can ask the browser to listen out for a mouse event such as when a mouse hovers over this particular element. We can again do this by selecting our button with $0, and then we can use an event called onmouseover. This will detect when the mouse hovers over this particular element. Then we're go to trigger what is called a function. A function is like a task which is going to run when the mouse hovers over this particular button. Don't worry if this looks unfamiliar, we have a lot more detail on functions coming up. But for now, all we're going to do is to select this particular element. Again, access the style property, and this time let's go for the background to be equal to any color, such as orange. Hit ''Enter'', and this mouseover event will now be activated. If we now put the mouse over this particular elements, the background is now changed to be orange. This is a way to quickly test things out in the browser. But when it comes to writing real JavaScript code inside of our text editor, $0 won't work, $0 only works inside the browser's developer tools. Instead, we need a way to access any of these elements from the page from the outside. For example, back over to the element's page, and what we're going to do is to select a different section. Let's go for the main, which has the ID of content. Of course, we could access $0 since we are in the developer tools, but we need to get used to accessing these elements from a text editor. The way we do this is by starting from the very top level, and this is by accessing the documents. We can see straight away that the full page will be highlighted. This is because the document is this actual web page. Then once we've selected the full page just like this, we need a way to filter this page down to the particular element which we want. JavaScript provides us with certain methods which we can use to filter down this page. As we can see here with this auto complete, we can select an element by the ID, by the class name, and also by the element's name too, but more than these later. I'm going to go for getElementById, and then inside of the brackets we can pass in the ID of the element which we want to select. Looking at the Elements tab, we see this main section has the ID equal to content as a string. Pass this in, and also note here that this is also camelCase too. Just like the font family above, each and every word after the first one begins with a capital letter. Hit ''Enter''. This then returns back our main with the ID of content. We are in the exact same position as when we use $0. If we press up, we get the same line of code. We can then use dot to access any of the same features which we used before. For example, set the style, and then let's go for the CSS opacity equal to 0.3. This isn't applied, we can still do any other thing which we had before, such as the background. This equal to anything. Let's go for red. There we go. The background for the main section has now been transformed to red. Let's just refresh and reinstate this back to its original state. JavaScript is not limited to only changing the elements in our page. We can also use it to do so much more. We have access to date features, we can access timers, and also some math functionality too. Let's, for example, add up two numbers. We'll say 5 plus 11 is 16, 7 takeaway 2 is 5. We have loads of other math features too, so we can select the math object and then dot, and then scroll through. We can see we have lots of different options, but a popular one is Math.random. Add the brackets just afterwards and hit ''Enter'', and this will generate a random number between zero and one. If we keep trying this, we get a different value each time. This is just a little taste of what JavaScript can do and how we can use it to interact with a web page. There is so much more to learn, and we'll find out more of these features as we progress through this course.
4. Download The Starter Files: Throughout this course, we'll be writing a lot of JavaScript code. To help us along the way, I've provided you with a folder called the modern javascript starter files. If you head over to github.com/chrisdixon161, and then into the repository which is modern-javascript-starter-files. From here, you can download this full set of files, which is the starter files which you're going to need for each lesson in this course. For example, when you go into the first section, and then we'll find a list of all of the lessons inside of this section. Each one of these folders contains the very bare minimum which you'll need to start with each one of these lessons. The purpose of these folders is to give us a starting point, so we can just jump straight into learning about JavaScript without, for example, needing to write all of the required HTML code. Another benefit of all of these files is it also gives us a reference for all of the lessons which we've done in the past. As we tick off each one of these lessons, we have a reference which you can look back to you if you ever get stuck in the future. This is all we need to do. Just go ahead and download the folder. You can do this on the main folder entry points. Click on the "Code" button just here and you can download the full ZIP file, which we're going to open up inside our Visual Studio Code. Once this has been downloaded, you should have a ZIP file which you can extract, usually by double-clicking the folder and then drag this over into your text editor. I'm using Visual Studio Code and you should see all of the available sections over on the left. This is it, this is our starter files all complete. We can now jump into learning all about JavaScript.
5. Where To Add Javascript: Welcome to the start of this section. We're now going to take a look at JavaScript and we're going to move over from the browser and actually into our own JavaScript files. From the previous section, we downloaded the starter files which come with this course. If you haven't downloaded these, make to go back to that video and download these from GitHub. Once this is done, you will need to unzip the package and drag this into Visual Studio Code to open this up. On the right, I've opened up Google Chrome as the browser. What we are going to do now is to begin right at the start and take a look at exactly where we can add JavaScript into our files. Earlier, we have typed code directly into the browser's console, but realistically, it's almost always wrote in our own files. Where do we start? Well, inside of Visual Studio Code in our starter files, head into our first section, which is the JavaScript basics and you will notice that the far numbers begin at 02. This is because for this particular lesson, we're going to begin right at the start and set things up ourselves, and then for all of the rest of the lessons, these will have some boilerplate available for us to access. We can just jump straight into writing our JavaScript code. For this one with the JavaScript basics selected, click on this icon here, which is to create a new folder, and then this can be 01. I'm going to call this where to add JavaScript. Again, make sure this is inside of the JavaScript basics folder and then with this first folder selected, click on this icon here, which is a new file, and this will open up inside of here. We'll call this the index dot HTML. Hit Enter. It should be inside of our new folder. Within it, add some basic HTML structure to open this up inside the browser and Visual Studio Code comes with a plug-in or rebuilt in called Emmet This will give us some code completion and some simple shortcuts. One of the most useful ones is HTML colon five. Hit Enter. This will give us all of the basic HTML starter code which we need. Again, this is all going to be available in all of the other folders so this is just for this lesson only. The title, where to add JavaScript. Then we need the elements to actually work with such as a page heading. Placing anything such as h1 and some text inside of here. Having these elements in place here means we can use some JavaScript to access these elements, just like we looked at in the console earlier. All you need to open this up inside the browser is to save this file with Command or Control S. Then if we right-click on this filename just here, go down to Copy path, and then we can paste this inside the browser. Alternatively, if you want to, you can go inside of the main folder just here. You can then follow through to the current folder and double-click on this index page. This will then open this up in your default browser. To be able to access these elements using JavaScript, one of the ways we can do this is to add AID. I'm going to give us an ID of title. Remember that each particular ID should be unique to this HTML page. Make sure we only have one ID of title inside of this HTML file. This makes it nice and easy for our JavaScript to be able to select the particular elements which you want. Then below this and just above our closing body tag, we can insert our script tags. We have an opening tag and also a closing tag too. This is the location where we can place our JavaScript code. Just above the body is one location where we can add JavaScript and is also over locations which we'll look at soon. Earlier when we were inside the console, remember we looked at selecting each particular element with dollar symbol zero. Also remember we said that this is unique to the console. We need a different way of selecting our elements inside of the text editor. Well, inside here we're going to do the exact same thing we looked at in the console. We will first select the document. The document is this full HTML document which we are currently working in. It's going to select this and then we need to filter down these documents to the particular element which we want to select. Remember we looked at a method called get elements by ID. Again, this is CamelCase. Each and every word after the first one begins with a capital inside the brackets, and the quotations will then pass in a unique ID which you want to select. In our case, we're going to grab the title. Move this into here. We looked at changing the inner contents or the inner text of this element with.innertext. This is a property where we can add a new text string in between the single or the double quotations. Let's just change this to JavaScript for now and save this file. Then if we go over to the browser and reload, this has now selected our level 1 heading and changed the inner HTML. Let's just close down the side bar to get a little bit more space. All of the same properties we looked at in the console video still apply to, such as adding different styles. Again, we can access the same elements with get element by ID, and we can also change the styles for this particular element too. Let's change the text color to be equal to orange. Refresh and this will all apply. Another way of adding JavaScript is to add this inline. Adding this inline means we add it directly inside of our elements and we add this inside of the elements opening tag. We'll add this just like we would add some inline CSS. In an earlier video, we looked at events very briefly, where we looked at the on-mouse-over event. Here, let's take a look at the on-click event, which will be triggered when the user clicks on this particular element. All we're going to do inside of this on-click event handler is to trigger an alert. An alert is a pop-up inside the browser. Let's just add this with the text of clicked. Give this a save and refresh the browser. Move the mouse over to the elements and click. I will now see a page alert. This is probably something which you've seen when browsing the web in the past. All we need to do to remove this is to click on the Okay button and this will then be closed. Let's just remove this. Also just be aware that it is generally discouraged to keep our JavaScript in line just like this because it mixes up our HTML and our JavaScript and makes things less readable and organized. If possible, keep it all separate, just like we have here, and we'll also look at how we can add this into a separate file in just a moment. This is contained inside of a script tag and we can add as many script tags as you want. It could also be located anywhere on this page too, including up inside of the head section. This works in exactly the same way if we grab all of this script section and then Command or Control X to cut this out of place. Place this inside of the head section with command or control V to paste this in and also the browser. Inside here we can see the original page title is reinstated. Now since we've moved the script tag up to the head section, none of this JavaScript seems to be applying. So let's take a look inside the console and see if we can spot any errors. Right-click and inspect. Click on the Console tab at the top. We see we cannot set the property innertext of null. When we do get an error, it's often a good idea to head into the console and it will often give us a pointer to exactly what the problem is. The current problem is caused because HTML page is loaded from top to bottom. So the script inside of the head section is loaded before it even knows this title element exists, which is then causing an error. If we do need to add a script inside the head section like this, it can often cause problems if we need to access any of our DOM elements. This is why we often see JavaScript at the end of the body section. It allows the elements to be loaded fast and doesn't block the HTML from loading onto the page. You will, however, see some third-party JavaScript libraries which need the script to be loaded inside the head section for the library to function correctly. Also, these third-party libraries, along with our own code, is usually separated into its own script file. Moving all of this JavaScript into its own file will make this HTML documents much more readable and maintainable. To do this first, open up the sidebar and then inside of the where to add JavaScript folder, click on the new file icon, and then we can give this a name of our choice. I'm going to go for script 1. Then it needs to have the dot js extension. Hit Enter. Back into our index page, we can copy the contents between the script tags. Grab these two lines of code, put these outs. Paste these into our new script file. This script file doesn't need the surrounding script tags since we already know this is a JavaScript file from the dot js extension. But what we do need to do is to link these two files together. Currently, these are two separate files independent of each other. Over in the index file, we need to point to this new script file. We can do this inside of the script tags rather than having the code located inside like we did before. What we can do is to add the source attributes. The source attribute is basically the location of this file relative to where we currently are. This works exactly the same as adding a style sheet. Since this file is alongside each other, we can point to this with the source of script 1 dot js. If this was located inside of a JavaScript folder, for example, we'll need to go into the JavaScript folder and then forward slash into our script. We don't have this, so it's simply script one dot js. Make sure both of our files are saved and then over to the browser, refresh. we see the same issue inside the browser. We can not set the property innertext of null. This makes sense because we are still loading up the script tag inside of the head section. We're trying to apply this to an element before it's even been loaded. We could write some custom code to wait for the HTML to load first or we can look at some more modern techniques in the upcoming video.
6. Async & Defer: Inside of our starter files, we're going to close down this file from the last video so there's no confusion. Then head into lesson 2, which is async and defer. Double click on the index page to open this up. Since we're now in a new file, we need to copy this or copy the path to this and then paste this inside of the browser. We see straight away that we still have the same error as the previous video. This is because this is pretty much the same file or the same ending code which we had in the last video. We have our script and then we also have our level 1 heading and the same contents inside of the script file. You will need to do this for each video we go to. We need to open up the index page and also make sure that this is the right page title. In the last video, we discovered a problem when loading up our JavaScript files too early. This can cause two problems. First, we might need to access HTML element before it's even being created, just like we see here, and second of all, we may have a lot of JavaScript code located inside this file. This could really slow down the loading of the rest of our page. If the script 1 was a really huge file, the user wouldn't see any of the HTML loaded on the page until this script had finished executing. We're now going to look at two ways we can use to fix this whole async and defer. Async and defer are both attributes which we can add inside of the script elements. First, let's take a look at async and close down the sidebar for some more space. Make sure this file is saved and refresh the browser. Straightway, we see that the error has disappeared. The JavaScript has been applied to our element and we don't see any errors over inside the console. Let's try defer. Place this and refresh the browser and we have exactly the same result. Everything is working perfectly fine. With these both working, what exactly is the difference? Well, first we have async, and async is short for asynchronous. This is a term we'll come back to later on. But for this particular use-case, async will download this script alongside the rest of our HTML content. But to understand what async is actually doing, we need to look a little bit further ahead. Now imagine, rather than having our script in our index page inside of the text editor like we do here, imagine this was a live website. If this was a live website, our scripts and our index page will be stored on a web server. When the user visits our page for the first time, the contents of these files will need to be downloaded. When we mark this as an async script, this JavaScript code will be downloaded alongside our HTML content. This means rather than blocking our HTML code, the HTML is still downloaded and then rendered inside the browser, so it shouldn't cause much of a slowdown with our content. Then it will run the contents of our script as soon as it is all finished downloading. This has its advantages. It's really useful since it's not blocking the loading of our content but there's a drawback. You see this, I'm going to link to three separate scripts. Let's copy and paste this two more times. This can be script 2, and script 3, and of course we need to create two new files inside of our Async and defer folder. Second one, scripts2.js. Also script 3 into our script 1. For clarity here, we can change this to be number 1, and then save this file, and copy this line of code into our script 2. Paste this inside here and we can change this to number 2. Save this on the same for number 3. Now with our three scripts linked just here, in theory, what should we expect to happen? Well, probably we would expect this to be the number 3 inside of here, because we loaded script number 1, which will change the contents to be number 1. Then script 2 which we'll change this to be number 2, and then number 3 will override this to be number 3. Well, let's check this out. We can save this file and also the browser, refresh. We see number 3 as expected. Let's try refreshing a few more times. If we keep refreshing multiple times, we'll eventually see a different number. We eventually see this value of 2 because we are requesting all three of these scripts in order. But even though we are requesting these three scripts in order, it doesn't mean that you're always going to come back from the server in this particular order. But you may be thinking, why should I even care about this? In exactly the same way as script1.js relied on the contents of the HTML to be present, sometimes one script may rely on another script too. For example, our third JavaScript file may rely on some code from the first two files to be available first, and if this is downloaded first before the previous two, this will then cause an error. Certain JavaScript libraries of frameworks will also have multiple scripts which we need to download, and these will need to be downloaded in order. For example, in earlier versions of the Bootstrap framework, we used to always rely on the jQuery framework too. For the first script, we would need to download the jQuery library. Then only after this has finished loading, we would then download the Bootstrap library, which was then making use of the jQuery features. When we need our script files to run in a particular order, async may not always be the best option to go for. Defer, on the other hand, will run the scripts in the order which they appear and it will do this after all of the scripts on the page and also the page content has loaded. Let's change this to be defer in all three of our scripts. If we keep refreshing as many times as we want to, we should only ever see the last value of three. If you are new to JavaScript, I don't expect you to remember all of these, and you may not need them all that often. But you will also have this video and also the project code here if you need this as a reference in the future. Also remember more commonly too, we also have the option to place this script right at the end of the body section, so it doesn't lock up the loading of the rest of the HTML. Just as a recap before we move on, we have the async and the defer keywords which you can add as attributes to our scripts. When using async, this will download the scripts alongside the rest of the HTML content and the browser will attempt to render the page while downloading this. One of the advantages is it won't block the rest of the content from rendering, and as soon as the file has finished downloading, it will then run the script inside. We also need to remember if we're using multiple async scripts, there is no guarantee that they will run in the order which we expect them to. Async is still a good option if we have multiple scripts which do not depend on each other to load in a particular order. Defer, on the other hand, will load multiple scripts, and we know that the order is going to be preserved. If our scripts will run as soon as both the page contents such as the HTML and these scripts have finished downloading, then this all means that we should prefer to use a deferred scripts when we have multiple scripts that would need to run in order. This is the key takeaway that async could be used when we have multiple scripts that don't need to run in a particular order. We should use defer when we need these scripts to run in a particular order. Again, you may not need to use these two key words very often, but it's also really important to be aware of all of these parts of JavaScript in case you come across these in the future. Next, we're going to move away from the loading of JavaScript and take a look at how we can work with strings.
7. Working With Strings: Let's now jump into Lesson 3 of this section which is Working With Strings. We should know what to do by now. We can open up the Index page. Then if we open this up inside of the browser, copy the path to this, and then replace the current one inside the browser. So far when we've been setting the inner text, and we'll take a look at this example here, which is just like the ones we've looked at in the past. We select this title, just above, set the innerText to be equal to something else which wasn't originally there. Here we started with working with strings and then we replaced this with something else, which we see inside the browser. So far we've been adding these in-between the single quotations and in JavaScript, this is what is known as a string. A string is basically some text, it can be a single character such as single letter like an A, it can be a single word, it can be a sentence or even a paragraph. We can also place this inside of the single or the double quotes, it doesn't matter, both of these will work perfectly fine for an example just like this. However, though there will be an issue if one of the words inside contains the same character, such as a single or double quotation. If we revert this back to single quotes, just like this, and then we can change this to be maybe, let's go. This also has an apostrophe which is the same symbol as the surrounding quotes, immediately we can see the text editor has highlighted this and changed the color to let us know there is a problem. What is effectively happening here is we're matching a string from the first two quotations. We can see this is the original color, and then afterwards we see an error. We can see this if we save this file and refresh the browser, we can see in the console we'll have an unexpected identifier, since it's expecting all of our string to be just contained in between these quotations. There is a couple of ways we can deal with this. First, we could change the outer quotations to be the opposite and make them double. So add the double at the end and also at the beginning too. Now, this string will be contained between the double quotations and the apostrophe will be completely valid. Save and refresh, and we'll now see the apostrophe inside the string and we see no errors inside the console. Alternatively, we can use what is called escaping. If we change these back to the single quotations which was causing an error, we can make use of a backslash just in front and this will then escape the character which you want to then display. This will tell the browser to then render this as part of the string. Let's try this. This works exactly the same too. Escaping like this also works for other characters too such as the double-quotes. If we escape it like this, we shouldn't see any problem. Let's say this, and that's completely fine. But what if we actually wanted to display this backslash as part of the string too. For this, we need to add a double backslash to escape this. The first one is rendered as part of the text, but the second backslash is used to escape this double quotation. If we have lots of text rather than just a couple of words like we have here, we sometimes want to break it up into multiple lines. To see an example of this, we can go outside of our script and we can generate some sample text inside our Visual Studio Code. To do this, type in the word Lorem, L-O-R-E-M, hit "Enter", and then this will give us some sample text to work with. Let's copy all of this, in fact, we cut this out of place and we'll paste this in between our quotations. Now if we save this and check this out in the browser, since we have lots of text here, the browser will automatically wrap this onto new lines depending on the width of the browser. However, though as a developer, if we did want to control exactly when this broke onto a new line such as this word just here, we may want this to start on a new line. To do this, we can use a backslash followed by the letter n as many times as we want inside of here. Let's find the word we were looking for which is this one just here and we can use the backslash followed by n. Give this a save and refresh the browser. This will then break this onto a new line, and you can use this inside of this string as many times as you would like to. Something note to be careful of is, we can't have a string over multiple lines. What I mean by this is rather than using this backslash and n, if were to just hit "Enter" and place this onto a new line. We can do this as many times as we would like to , just like this here. We can see that the text editor is warning us of an issue. For string of texts like this, we can't break this onto multiple lines and we can see this in the browser if we refresh this, we see an invalid or unexpected token. We do have a couple of different ways we can approach it to fix this. One of the longer ways to do this is to convert each one of our lines of text into its own string. We can do it like this and you can see this is a pretty long way way doing this. Then we would also need to use the plus symbol in between each line to join this onto the next one. For simplicity, we'll just make this as free lines, refresh and this all work just like before. Or there is a more modern way which is to use what is called a template string. This replaces the quotes with backticks. Let's just undo this and reinstate this back to the original error. What we can do rather than have any single quotes at the beginning and the end, we could replace these with what is called a backtick. The backtick is located on your keyboard and it's a symbol just here. In my particular keyboard, it's located next to the left Shift key. Immediately the text editor will now remove the errors and we can save this, and this should all work perfectly fine inside the browser. You can see you're also preserves the line breaks, so just after Lorem ipsum, we have a break, we then have our second line which is this one just here, and then have each line preserved just below this. These template literals were introduced to JavaScript in ES6 or ES2015, and allow us to write multiline strings along with some other benefits such as inserting variables, which we'll take a look at later. After this course, we'll take a deeper look into strings too and discover some of the available properties and methods which we can use.
8. Storing Data With Variables: That's over for this video, headed into the next folder. We're going to look at number 4 which is storing data with variables. So let's open up this file and also copy the path for the browser too, paste this in. We'll see the title of variables put at the very top. Oops. Now in this course we've been setting or changing values, such as updating this title just here. In JavaScript the most other languages too, we regularly have the need to store our data. JavaScript provides us with three main ways of doing this. Let's begin by looking at the traditional way of storing data in JavaScript, which is the variable. We can create a variable by using the var keyword, just like this, followed by a name for this variable. So let's call mine new text. This is a way to reference this variable in the future. Adding a name like this is called a declaration since we are declaring a new variable. You can think of a variable as a storage container and this name we give to it, it's kind of like the label on the front so we can easily find it in the future. It also makes sense to be descriptive when naming variables. It should reflect the data which it contains. Also, this name cannot contain spaces like this. It must also begin with a letter, an underscore or a $ symbol. If we add something which is not allowed, such as a forward slash, usually a modern text editor like this will pick up on this and warn us of this error. We can then use this equals symbol to add a value which you want to store inside of this variable, such as our string of text. Since this is a string, we add this in the quotations, let's say new text from variable. So what we've done here is we've used this equals to assign this value over on the right for this variable name over on the left. Adding a value to our variable just like this is referred to as initialization. You don't need to remember these keywords, but I just want to make you aware that these exist. So this is initializing a variable and before we just had the variable declaration. Then to make use of this text, all we need to do is to pass in the variable name, just like this, you could say save and refresh. There's our new text which we stored inside of the variable. Well, what if we also wanted to change this value which is stored inside this variable. We can easily do this too. Since our variable is already created. What we need to do this time is to access the variable name without the var keyword. The program already knows this is a variable since we declared the above, so the var keyword is not required. Again, using the equals, we can update this with a new value. Let's say updated text. Give this a save and check this out in the browser. There's our updated text now showing. So the order here is important too, since the code is read from the top down to the bottom. So the first line, we create our variable line till we update it. Then the title is changed to our new updated text. If we were to do something like this and move the update to be above where we declared our variable. Let's see what happens when we save and refresh. We no longer see the updated version inside the browser. This is often why we will see variable declarations over the top of the script. So it won't cause any problems if we start to update this later on in our file. Variables can also hold other data types too, not just strings, and we will discover more data types very soon. But for now there is two more types of variables alongside this var keyword, which we're going to look at. Both of these were introduced with ES2015. The first one of these is the let keyword. On the surface, let work just like the same as var. It can contain a value and we can also update this value when required. So if we change var to be let, save and refresh. We now see the updated text, just like we did with the var keyword. There is a difference still between the let keyword and var. This all comes down to something called scope. Scope relates to how we can access these variables and you add some restrictions on how we can access the values stored inside. There is more information on scope later on in the course, where you'll learn all about this in more detail. But we do need to learn a little bit more about JavaScript first before these will become really clear. Next up, we have the const keyword, which is short for a constant. You can think of this as holding a constant value which won't change. If we save this and refresh the browser, we see this will throw an error inside the console. We see the message of assignment to constant variable. We get this because just like var and let, this can also store a value, but it's more of a read-only value. The contents inside is not intended to be updated, which we are doing just here. So if we were to remove this line just like this and then refresh the browser, this now gets rid of the error and we still see our variable contents. So the console error message before was assignment to a constant variable. So just before we try to update this, we've seen the message was assignment to constant variable. It is assignment keyword here, which is the key. Assignment is just a fancy word we get to a variable over pass it a value just like this. We'll have this era because we're trying to reassign it with this value just below and having this const now introduced into the JavaScript language is a really good thing because it means we can store our values, which we know we don't ever intend on changing. This can stop any errors or bugs in our code. If somebody accidentally changes a value later on in the code. But there is something which can be confusing for beginners and it surrounds creating something called an object using const. If we remove these two lines of code, we can create a new constant called a Person. We'll have more detail on objects very soon. But for now you can think of an object as a collection of pieces of data. So a person may have multiple pieces of data such as an age, a name, a height. These can all be stored inside of these curly braces. All of these pieces of data is stored inside of multiple properties called key value pairs. So the key is the name of the data, such as a person's name. The value is actual name. Separated by a comma we can add a second key called likes, and then a value of a favorite food. We can keep going with as many values inside here as we would like. We can then access any of these properties by first accessing the constant name and then using the dot to select any one of our properties such as the name or likes. Let's try this, refresh we see the name of Chris and then person at the likes is a way to access the second property of pizza. So although this object is a constant, it's not strictly immutable, meaning it will never change. We can actually update the property just like this. We can access the person constant and access the key called likes. I set this to anything such as bananas. Lets save this and we still have the person at dot likes rendering out to the browser, refresh. Now we can see we've updated our constants with a value of bananas. We could also add additional properties. So once which already don't exist, we can say person dot hair and set this to a color, then display this inside the browser. So we can see here that we can update the properties inside of an object. But what about if we tried to completely change the person to be a different datatype, such as a string. Let's just change this to be a name such as Chris. Refresh this. We now see the same error message which we had before, which is assignment to a constant. So as you can see, a constant holding an object like this can still have its values mutated inside. We just cannot reassign its original value to maybe a number or a string. For this reason, it is often advisable to avoid the confusion by only using const for simple values such as a string or a number. Then we know for sure that this value will never change. So just to recap with everything we've learned in this video, we have three different keyword called var, let, and const, which all allow us to declare a new variable which is kind like a storage container for our data. When using the var and the let keywords, we can optionally assign a value to these names. The values inside can also be updated or reassigned with a new value. There is also some scope and hosting considerations which we'll cover later on in the course when we have a little bit more understanding. When using the const keyword, this will also create a new variable or storage container, but the value cannot be reassigned. As a beginner, it can also be confusing when using const and an object because object properties can be updated, or we can also add new ones too. We've also mentioned some key words in this video too. You don't have to remember all of these at the moment. First of all, we had a declaration. This is when we create or declare a new variable without passing it a value. So for example, we could say var name. We then initialize this variable when we pass it a value such as equals Chris. Assignments. This is when we pass or assign a value to a variable, such as this example down at the bottom, where we assign the value of 37 to the age variable. So these variables are going to be something which we use a lot. So you will get lots of practice with these through this course. Next, we're going to stick with variables and take a look at how we can mix these with strings.
9. Mixing Strings With Variables: We now understand what a string is in JavaScript and we also know how to store them into containers called variables. But what if we wanted to combine these two things by adding a variable into a string? This is completely possible using JavaScript and there's different ways to do this. Let's go over to our files, which is number 5, mixing strings with variables. I'm going to open this up inside of the browser. Inside of this index page, we have our level 1 heading up at the top with the ID of title. We then have two constants below, we have this name and also a likes constant too. Finally, we select our title and update the inner text. What if we wanted to update this title and also mixing these two variables? The way to do this, we may want the string of text to say my name is. Then after this, let's say we wanted to also insert this name variable. If we save this and refresh, we see my name is name, so we see the text of name rather than the inner contents of this variable. The reason this happens is because since all of this is inside of the quotations, it's all considered to be part of the same string of text, not read as a variable. We need to break out of this string and add or append the variable name to the string. We do this just like we looked at in an earlier video with the plus symbol. What we need to do is to remove the variable name from the end, use the plus symbol and then outside of the string, we can add this variable name. We could also leave a space at the end of the string, so we have a space between the string and also the variable, then over to the browser and refresh. We can see our name is now been updated with the value of the variable. We can also add the second variable onto this string too, just like we did here. But then use the plus symbol, open up the string at a space, and we'll say and I like, I then have a space at the very end, and then the plus symbol to add the variable of likes. Let's check this out. My name is Chris and I like pizza. That's all working perfectly fine, we've got our variables mixed into a string. There is also another way to do this too, which was introduced in ES 2015. This is to use the template strings. Template strings are just like what we used in a previous video when we combined the text over multiple lines. What I need to do is to replace these quotations with the backticks. Let's remove all of these quotations and we can also remove the plus symbols, leaving only the text inside. Then what we need to do is to place all of this inside of the backticks. The second step is to mark which part of the string is variable. We know from earlier, if we just save this and refresh, we don't see the contents of these two variables but what we need to do is to place in front of this a $ symbol and then the variable name inside of the curly braces, the same for our likes, $ symbol, and wrap this inside of the curly braces. Now this should be read as the contents of our two variables. These template strings in between the quotes can also be stored into their own variable too. If we were to cut this out of place, create a new variable, let's say string is equal to this value we've just cut out. We could then pass in the variable name of string. This all works just as before but this time, all combined into a single string variable.
10. Data Types: Numbers: In any programming language, we have what is called data types. Data types, as they sound, refers to the type of data which we are dealing with. So far, we've mainly focused on the data type of string. But there are also others too, JavaScript is a loosely typed or a dynamic language, which basically means our variables don't care what type of data they contain, they can contain a string or as we'll look at during this video, something else, such as a number, and we can also change the data type of a variable to when we reassign a new value. This is unlike some other programming languages such as Java, where we need to specify what type of data our variable will contain first. Inside of this current lesson we have the data types, numbers, video, which is Number 6. Also make sure to open this up inside the browser too. When dealing with a language such as Java, we may need to declare a variable like this. We can give our variable a name called number, and set this equal to a string of five. When we write code just like this, this is Java code, this is what is called a strongly typed language, since this data type must be declared upfront. However, though we use in JavaScript, which doesn't care about what type of data this variable contains. Unlike Java, we don't declare what type of data we are going to contain, we just simply say what type of variable this is going to be. We say let number equals 5, and this of course is a string because it's surrounded inside of the quotations. But what about if we were to do this? Let's say on the next line, we then reassign this value of number to be equal to a real number such as five. This is how we set a number in JavaScript. We don't surround in any of the quotations. Now we can use this number inside of here. We can now put the number on the screen. Let's say this and see what happens. Refresh, and now the value of this is five. This number variable has changed even though we use in a completely different data type. This data type of number can be a whole number just like this, and we can write this with or without decimal places. We can output this. If you are coming from a different programming language where there may be multiple number types such as double float, or integer, this is not the case here. JavaScript numbers are always stored as a double precision floating point format. If you do want to find out more about the technical details behind this, you can find the link here on the page. When working with numbers, JavaScript can also calculate the value and store this inside a variable too. For example, if we were to assign this number the value of 5 plus 10, you should now output the value of 15. We will do the calculation first and then assign this to the variable. But what do you think will happen if we were to add together a number and a string? Well, let's find out. We'll say let Number 1 equal to be a string, and then let Number 2, this can assign the value of 15. Now instead of outputting the value of number, we'll output the value of Number 1, add it to the variable of Number 2, over to the browser. We see our two variables, we have the string of 5 and then the number of 15. Is this a number or is this a string? Well, when I discover a number and a string, in JavaScript the result is a string. Even though we have a number here, this is classed as a complete string. We can prove this by using operator called typeof, put these out of place, and we use typeof. Then inside the brackets, paste these back in. We will see what type of data is returned from inside of these brackets. We can use this with any other data type 2 and it will let us know what type of data we're dealing with. Save and refresh and we see this is a data type of string. However, though, if we were to just output Number 2, the result is still a number. This typeof is a really useful tool if we are unsure what type of data we're working with. Also bear in mind even if we have a number stored inside of quotes like this, which has a Number 5, this will also be classed as a string 2. So anything in quotes is a string, any number which is not in quotes, is classed as a number. Both the data type of string and also number is considered to be what is called a JavaScript primitive type. Primitives are data types which are not classed as an object. They also don't have any methods which are actions that can be performed on an object. But don't worry about objects and methods just yet, we'll have plenty more detail on these throughout this course. The main thing to understand for now is that primitives are the most simple data types in comparison, and these include things like the string and also numbers. Just as a recap of what we've looked at in this video, we have data types which is the type of data which we were working with, and currently we've looked at the data type of string and also number. We also mentioned strongly type, which is a data type which we need to declare upfront when creating a variable. In other languages such as Java, we would need to declare that a variable is a certain type of data such as a string or a number when we create it. JavaScript on the other hand is loosely typed, so the variables don't care what type of data they contain, and we can also reassign this data with a different data type. For example, we could create a variable which is a string, and then change or reassign it later with a data type of number. Primitives, this is what we just looked at before, which is a data type which is not classed as an object. Primitives are generally a more simple data type, and we will discover the other type of object in some later videos. This is a basic introduction to JavaScript numbers, they are a real important and fundamental part of JavaScript.
11. Data Types: Boolean, Null & Undefined: In the previous video, we covered somewhat primitive JavaScript dates types which include the number and also the string. We're now going to look at some more primitive data types available in JavaScript. This is going to be a Boolean in null value and also undefined. Make sure you head into the current lessons folder which is number 7, and the data types Boolean, null and undefined. I already have this open and also open in the browser too. When playing around with codes like this, we have something available for testing called the console log. In between the script tags all you need to do is type in console.log and then open the brackets, just like this. We briefly worked in the console earlier and this log will allow us to output a certain value to the console inside the browser. For example, we can say is 10 greater than five and if we save this and then right-click and inspect to open up the Developer Tools, click on the Console tab, refresh. This returns the value of true. The console log will output any value inside this console image, great testing and quickly finding out the result or the value. We also have a new operator which is the less than, save this. This would be the opposite, which is false. These true and false values are the dates type of Boolean. With Boolean a true and a false is the only two outcomes, so it's really useful for checking things just like this. For example, in the Speedy Chef project which you have coming up, we're going to have a variable called gameStarted. Before the game is started, this Boolean will be set to be false and then when we start the game, we reassigned this variable to be true. This allows us at any point in the game to be able to check if the game is started and have certain features available. For example, we would have something like this, we could set up a variable. I'm going to give us any names such as gameStarted this is equal initiate to be false and then inside of our console log, first of all, we can check the data type of this variable using the type of property. Refresh and we'll see Boolean just inside of here. How can we use this in a real situation? Well, Boolean values are often used together with an if statement. An if statement looks like this, we'll have the if keyword, open up the brackets just like this, and then open up some curly braces. Now you will see this pattern followed a lot inside of JavaScript. We have a certain keywords, we have some round brackets and then we'll have some curly braces where we want to run our code, so you will see this a lot as we progress through the course. But in particular for this if statements what we're going to do, we're going to check if something is true or false. In our case, we want to check if gameStarted is equal to true or false. What we do, we pass this inside of here and if this results to true, the code inside of here will then run. In my case, I'm just going to put in a simple console log with the text of gameStarted. Now if we save this, then refresh the browser, we don't see anything inside the console because this is not true. However, let's flip this over to be true, refresh, and our console log has now run. Of course, we'll cover if statements in more detail soon but this is how they can work with a simple Boolean value. But if we have also a second variable, well, playerName. Say let playerName is equal to Chris and then we change our if statement to check this player name. We have a playerName set, we're going to log to the console. The message of username is set. Let's just take a step back and think about what we're doing here. We check in. First of all, last time we'll check in if the gameStarted is equal to true. This was a simple Boolean value, however though for this playerName, this is equal to a string. Do you think this will result to true or false? Well, let's save this and check this in the browser and we see that this runs inside the console. Well, the reason we see this inside the console is because generally an if statement or a Boolean will result to true if a value exists. Here we have a value of Chris, so this definitely exists. Let's see what happens if we remove this name and leave this as an empty string, save and refresh. Now, this must be resulting in false. One thing to note here that having an empty value such as our empty string, just like this, should not be confused with not having a value at all. A variable without a value is another primitive data type called undefined. If we have no value at all assigned to this variable and if we were to remove this string just like this and then instead, we'll do a console log for the playerName and we'll also remove this if statements, so we couldn't run this console log first time, save and over to the browser we see this value of undefined. As mentioned before, this is another primitive type such as string, number, and Boolean and this undefined is displayed because we have a variable which doesn't have a value assigned to it. This was like earlier when we looked at $0 inside the browser. If we initially type in $0, when we don't have any elements selected on the page, we get back the value of undefined. The final data type which we're going to look at in this video is also primitive and this is the value of null. Null also indicates that something is missing too. If we set our variable of playerName to be equal to null and then refresh the browser, as expected we get back this value of null. We had a brief look at objects in an earlier video, and null is related to these objects. It indicates that this object is empty and often when working with databases or back-end services, a common example of this is when requesting some user data. If the user is logged in, we get back an object containing all of that users information. If they are not logged in however, we'll often see null since they user object will be empty. We looked at three different data types in this video, we've looked at Boolean to begin with which is a simple true or false value. This primitive data type is really useful and often seen combined with an if statement. We have undefined, again a primitive data type which indicates that something is missing. In our example, we took a look at a variable which has null value assigned to it. Finally, we also discovered null, which is again a primitive data type and it's more specific than undefined and it refers to an object which is absence of any values. You can see at the bottom here that undefined is a more generic result and null is more specific to an object.
12. Comments, Semi-colons & ASI: If you've worked in JavaScript before, or if you're looking for code examples online, you may notice that semicolons are sometimes used and sometimes not. JavaScript programs are made up of multiple statements, which are read from the top to the bottom of the file. Statement is basically an instruction, such as creating a variable declaration of the code to run inside of an if statement. Although semicolons in JavaScript programs are required, if we choose not to manually write them, the JavaScript parser will add them in photos automatically, where they are required, the semicolons are added at the end of each statement, and the process is called automatic semicolon insertion. This doesn't mean we can simply forget about using them altogether. There are cases when we still need to add them in manually. For example, let's add some variables and check out the results. You'll notice that I'm in video number 80, which is comments, semicolons, and ASI, and also have this open inside the browser. Go down to the script section. What we're going to do is create two constants. The constants doesn't really matter at the moment. I'm just going to add a name, then a second constant, which can be learned in JavaScript. This is a Boolean value of true. Then inside of the console log we've outputted single variables in the past. But we can also add a comma and output the value of both of these variables. Save the file and head over to the console. Refresh and we see our two variable values. Nothing unexpected here, we get probably what we expected, which is our two variables. We'll log them to the console. But what about if we added these variables onto the same line? Let's try this. Place these on the same line, and make sure any semicolons are removed from the end of each statements. First of all, we can see that the text editor has highlighted an issue here as soon as you do this. If we were to save this and refresh the browser, we see a syntax error inside the console. We have an unexpected token of const, because the JavaScript parser doesn't expect to get to this stage here, and then see a new const declaration. If you have multiple statements on the same line like this, we need to declare that these are two separate statements, by separating these with a semicolon. Place the semicolon in-between. Now the text editor is not highlighting any issues. We can test this out. Save and refresh. This is now all working fine. You can also see that my text editor has automatically placed these on separate lines, since these are two separate statements. Along with the semicolon, some other gotchas are when we begin a new line with brackets, or often referred to as parentheses. Let's take look at an example just after these two constants. Create a new variable, would let's call score. You would say random numbers such as 97.34, a constant of damage, and again, a random number, 10.42. Just as a side note, I've created this as a let. Since a score can generally be updated, we can output the result of the score with the damage taken off. Now if we save this and refresh, this is the correct value inside the console. We know it can perform a calculation inside of these brackets, as we've just seen inside the console log. But what about if we took this console log away and did something else with this calculation? For example, instead of resulting in 86.92, what if instead we wanted to round this to say 86 or 87? Well, to do this, JavaScript has a inbuilt method which we can use called toPrecision. We can change this on the end with the dot, lowercase to, and this is camel case, so precision starts with a P. To use this within parsing the length value two to make it two digits long. Now let's see the effect of what would happen if we were to forget to put in any semicolons. Now Visual Studio Code will automatically insert these in follows when needed. But if we were to leave these out just like this and hit "Save", would instantly see what would happen when the JavaScript engine read through this code. We can see that this line has been inserted directly after the statement just here, because we don't have any semicolons to separate. Let's save this and refresh. We see an error, we cannot access damage before initialization, and this is because this line just here begins with these brackets. Now this may not mean much if you are completely new to JavaScript. But if you've done a little bit of JavaScript in the past, this is actually how we declare a certain type of function. Rather than interpreting this section of code and this section of code as two lines, it's actually reading from left to right and continuing this through as one full line of code. To fix this, as you may expect, we need to separate these with a semicolon. Then if we refresh, this will then now get rid of the error, and everything is clear in the console. We can also directly see the results of this calculation by cutting out this line of code. Create a console log and paste this back inside. Save this and refresh the browser and our value has now been rounded to two decimal places. There is also of a math functions which we'll look at later, which can round these values up and also round them down too. Just to recap, using semicolons in JavaScript is optional. It's completely down to you if you want to use them, or rely on them to be inserted automatically. But do be aware there are some cases when we start a new line of code with the brackets where we need to make sure we insert these manually, so it doesn't cause any errors. To round off this video, we're going to take a quick look at using comments. Comments are simply a way for us to make notes inside of our code, which won't be read as any JavaScript code. We can also use it to comment out our code too. This means that particular line of code is still there in our program, but it's not read when the script is executed. To insert a comment or a note, we begin in JavaScript with the two forward slashes. Then we could type a note such as, must have semicolon in above statements. If we save this and refresh the browser, we don't see any reference to the comment inside of here. But what if we had a longer comment which spread onto multiple lines? For example, if you had a comment just here and then said control the length of number using toPrecision. Well, like most of the time, the text editor will give us a clue to wherever we are doing something right or wrong. Immediately these changes color and we have this red underline below. We can see that this is not the way it's expected to be wrote. For this we can even begin each new line of code with the double forward slashes, or instead, we could convert this to be a multi-line comment, which is a forward slash, and then a star. We can then remove the second line comment and then go to the end of our comment just here, and we can end this with the opposite which is a star and a forward slash. As mentioned before, we can also comment out lines of code too. If want to leave a certain code in place for reference, or if we want to reinstate it later on, or when it's due is exactly the same. For example, if we wanted to remove this constant of Chris, we just add the two forward slashes in front, this line of code will then turn gray, and is no longer available to access inside of our program.
13. Operators: Assignment & Comparison: Operators are something we use all the time in JavaScript. In fact, we've already used some of them already during this course. You will notice for this video I'm already in the correct file, which is lesson number 9, Operators: Assignment and Comparison. Also open this up inside the browser. Scrolling down to our script section, we already have some simple variables already setup. You'll notice the common thing between all four of these variables is they all use the equals operator. This is the assignment operator because we assign the value on the right to the variable name over on the left. But there are other assignment operators too, which you can see up here from this comment. We've looked at this equals. Let's now move on to this plus equals symbol. Let's say we wanted to add together the value of number 1 and also the value of number 2, and then store the newly returned value. Well, we could do it like this. We'll call this the new number. Set this equal to the value of number 1 plus number 2. If I scroll down a little bit further, we have this getElementByID, which is already setup, which is just this level 1 heading up at the top. What we're going to do here is I'll put the value of new number. Add this into here, give this a "Save", and now we can "Refresh" the browser. We see this newly returned value of 20, which is the 15 and the five added together. There's no surprise with this one. But JavaScript also provides us with some shorter ways of doing this, rather than adding the number 1 on the number 2 variables together and then assigning this to a variable. We can instead do it like this. We can remove our comment out this line with the two forward slashes. Also, if you are using Visual Studio Code on a Mac, you can use command and forward slash. This will toggle this automatically. If you're using Windows, this will be control with forward slash. This will do exactly the same. Instead a short option. If you wanted to amend the number 1 variable or update this, we can use the plus equals operator and then pass in number 2. What this will do, it will add both of these numbers together and assign a new value to the variable over on the left. Both of these same lines will still come with the same result of 20. The difference being the top one is being stored inside a new variable, and the bottom one is updating this existing one. We can check this by updating this to be number one. "Save" and "Refresh". We still see the same value of 20. Also up at the top with our variables, we have this forename and the surname. If we wanted to display the full name on the screen, we may come up with something like this. First of all, we could set the forename and then using Command or Control C to copy and then Command or Control V to paste. We can then also output the value of surname. "Save" this, and over to the browser we only see the value of our surname. This approach doesn't work because the surname is last known code and therefore it overrides the forename. Instead, what we can do is make use of the plus equals operator to add this to our elements rather than replace the existing one. If we "Save" this and "Refresh", we see the value of both of our variables. We could also add an empty space between each one of these words using some of the techniques which we've used in the past, pass in an empty string with a space. Then the plus operator to add this just before our surname. "Save" this file. Now we have a space between our two variable names. This is adding values and then reassigning the new value. But we can also do the opposite with subtraction. We can see it is just up here. This works exactly the same, but we use the negative symbol rather than the plus. We can use this with our number example from below by doing the opposite with a subtraction. Let's remove this second, getElementByID. Replace the forename with the value of number 1. "Save" and "Refresh", and we now have the new value of 10. Just to recap, what we've done here is we've taken the number 1, which is 15. We've then taken away the value of five to give us 10, and the new value of 10 has been reassigned to number 1. We also have multiply exactly the same. We can change this, "Refresh", and we have the value of 75. We can also use divide, which is the forward slash. This is 15 divided by 5, which will reassign number 1 to be equal to 3. An interesting one is this last one we can see here, which is the percent symbol. This percent symbol is the remainder assignments after the division. What this is doing here, we have our number 1 and our number 2, which is a result of 15 divided by 5. Five goes into 15 three times and therefore there is no remainder. If we were to save this, there should be a remainder value of zero. But what about if we change one of these numbers? Let's say four. Four goes into 15 three times with the remainder of three. Another type of operator which we have is comparison. Currently we know when we're setting variables just like these bonds, when we use a single equals, we assign the value over on the right to the value over on the left. Here, number 1 was originally 15, and now if we set this equal to number 2, it should now be the value of four. But sometimes this can look a little bit strange for beginners. Because if we were to read this as a beginner, this may look like we're checking if number 1 is equal to number 2. As we know, this is not the case. This will assign number 2 to be equal to number 1. But if we did want to compare if these two values are the same, we do this with the double equals. We're going to install this inside of our value, let's say results. Then output this to the browser, "Save" and "Refresh". We see the value is a Boolean of false. We know this is false because number 1 is equal to 15 and number 2 is equal to 4. We can also do the exact opposite, which is to add an exclamation mark inside of here. This will check if the values are not equal. You will find this a lot of the times with JavaScript, if we use the exclamation mark, this will do the opposite of the original case. "Save" this, "Refresh". The opposite of course, is true. Something, however, to watch out for is if we are comparing two different data types. For example, if both of these were five, but one of these fives were surrounded inside of the quotations to turn this into a string. For this example, it doesn't matter if we're using the single or the double quotations. It changes back to the equals. Let's see what the result is inside the browser. If we "Refresh" this, we see this is a value of true. Even though we have a string of five and a number of five, the double equals will only check the values and not the data types. Number 1 and number 2 is considered to be equal even though one is a string and one is a number. However, though if we did want to also check the value on the data type, there is a way we can do this using the triple equals. The triple equals means strict equality. "Save" this, "Refresh". Now since they have different data types, this now returns a false value. If we are using the strict equality just like this, we can also still use the exclamation mark just like before to return the exact opposite. Change this to an exclamation mark. Now if we "Refresh" the browser, this is the opposite value of true. Comparison like this is often combined with if statements, which we'll again cover later. But some other comparison operators include the less than and the greater than symbols, which are the left and right arrows. We did briefly look at these in a previous video. All we need to do is we can change our two values to be different. Let's first check if number 1 is greater than number 2. We know this is true, so we expect to see this inside the browser. The opposite is the less than symbol, which, of course, will return the value of false. Finally, the last thing we want to take a look at in this video is we can also combine these less than and greater than symbols with the equals. We can check if number 1 is less or equal to number 2. This one will be false. But we can't change these variables to be the same. These are both equal. This should be a value of true. We also have access to the greater or the equal to version as well. Operators like these are useful for things such as games, where we can check if a player's health is zero or less, which will then end the game. Next, we'll stick with the subject of operators, but this time we'll take a look at logical and arithmetic.
14. Operators: Logical & Arithmetic: Welcome back. Along with assignments and the comparison operators, there are also logical and arithmetic operators, which we can take advantage of in JavaScript. As ever, we've headed into this lesson's folder which is number 10, and also open this up inside of the browser. Just like the previous video, we have some comments, which has a list of all of the available operators. The first set is the arithmetic operators. We'll get onto the logical ones just afterwards. With the arithmetic operators, a lot of these are just common sense, such as the, addition and the, subtraction. A lot of these are also very similar to the previous video with just not combined with the equals operator. For example, this is one which we looked up previously. This plus equals, will then add up both of these numbers and then reassign the new value to be number 1. We know these are 15 and also five. These results of number 1 would then be equal to 20. However though, if we were to remove this, equals and just have the plus symbol on its own, as you may expect this will just simply add both of these values together, meaning we could directly output this into the console, or we could also store this inside of a variable to make use of in anywhere inside of our code. Just below [inaudible] this line of code where we grab this page title. Then we can set the inner text to be equal to our result. Let's try this out over in the browser. Reload this. We'll get the value of 20 because we've added together both the, number 1 and the, number 2. This works for not just adding it to get the variables like this. For example, let's do a console log. We can add simple numbers just like this, so 5 plus 3. Open up the console and there is our value just here. We can also use it to add together strings too. Above we have a constant of forename and also surname. We can use this operator to add the forename to the surname. As we've looked at previously, we can also append as many strings as we want to. This will also add a space in between the forename on the surname. "Save" and "Refresh". It has the full name now displayed, just remove this console log and we're going to cut some more of these operators just above. As you may expect. We can replace this with subtract, this will give us the results of 10. We have the star which is the multiply symbol. This will now be 15 multiplied by 5, giving us the results of 75. We also have the remainder operator, which is this percent symbol just here. Remember from previous videos this will do a division and output any remaining numbers afterwards. This one five goes into 15 three times, leaving a nice round number and zero remainder. But if we were to change it to be four it would be 4, 8,12, and then we would have a remainder of 3 to make up 15. These are very similar to the assignment operators we looked up previously. Because as you can see here at the end there is two other additional operators which look very different to the previous video. This is the increment and decrement. The first one, which is the double plus this is increment and this will increase the original value by 1 or the decrement, which is the double subtraction. This will decrease the value by 1 each time. To see this as an example, we need to change this to be let so we can update these results and change it to be a multiply so the result is going to be 60. So 60 is now stored inside of this result. If we go down to the next line, then we select this result and add the double plus afterward, which is the increments. Refresh. This is now being increased to be 61. We could also do this again by copying and pasting, and this would now be 62, so it increases by 1 for each attempt. This operator is useful for many situations. For example, in one of our upcoming projects, we'll use it multiple times, such as each time a new order is placed, we increase the order number by1 for each order. Also, we have the completed pizzas variable, which will increase by 1 each time the chef completes one of the pieces. We can install all of these numbers and display them at the end of the game. The opposite is to use two subtract symbols, which is going to decrement the number, which means it will decrease it by the value of 1 each time. Remember the original result was 60, then we'll reduce it by 2. Refresh, and this leaves 58 lowest. Below this, we also have the logical operators, and as you can see, there's only three of these on the screen. These logical operators often combined with if statements which we'll cover later. But they're also useful on their own too. If we wanted to check if multiple conditions were true, we could use the logical AND operator, which is this double ampersand. For example, if we wanted to know if number 1 was equal to 15, and also if number 2 was equal to 4 before performing any code. We could do this by, let's remove this example. I'm just going to move this below as well. We'll recreate our results. Now we can use the logical operators to perform a check. We want to check if our number 1 variable is going to be equal to 15. The triple equals, this is equal type and value. Now, this will store a true or false value inside of result. Like I mentioned before, what if we also wanted to check if number 2 was equal to 4. Well, the way we could do this is with this AND operator we can also perform a second check. This time we check if number 2 is equal to 4. Let's say this and refresh the browser. This is true. Both of these checks, this one and also this one is both true. This is why we get the result of true. It would change any of these to be a different value such as number 2. Since one of these is now different, this would then result in false. That's great, but this of course relies on both of these conditions to be true. But what if I wanted to know if only one of these was true? For example, if number 1 was equal to 15 or if number 2 was equal to 4, we may want to get a value of true back if either one of these is a result of true. Well for this we have the OR operator, which is these double pipes. Let's change the double ampersand for the double pipes. Now we know that only one of these values is true. We should now see true inside the browser. The same if we change this back to before. Now we know that both of these is going to be equal to true. This would also be true since remember, we only need one or more of these conditions to be true to get the results of true returned. Last but not least, we have the exclamation mark, which is the NOT operator. This basically does the opposite and will return a true value into false or vice versa. Remember that currently inside the browser we are seeing the value of true. If you wanted to check the opposite, all you need to do is to add this exclamation mark before the result and say this, this will give us the opposite result, which is false. Checking the opposite like this may seem a little bit strange, but it does have plenty of uses inside of JavaScript. For example, in one of our upcoming projects, we do have a variable called game started. This is a true or false Boolean. We can then check if the game has started or if the game has not started by using the exclamation mark before we run any particular code. It's also useful for plenty of situations too such as checking if no user exists, and so many more. But reference to all of these operators covered in this video and also the previous one too. There are slides available with this course. Check them out if you need a reference.
15. Introduction To Arrays & Object Types: For this video, jump into lesson number 11, which is the introduction to arrays and object types. Also open this up inside the browser. In JavaScript, there are two groups we can place our types into. It is both primitive and object types. The previous data types which we've looked at such as a string, number, Boolean would define the null, all fall into a group called primitive types. There is also big int and symbol too, which we have not yet covered. We're now going to discover the object types. The first one is an array. The previous primitive values we've looked at store one single value such as a string, or text, or one number. But an array can hold multiple values. If you think of a shopping list, a to-do list, or generally any list with multiple values, an array is ideal for this type of data. Let's take a look at our first array inside of the project folder. Head down to the script section. We're creating an array with these square brackets. Arrays can hold any data type such as a string, just like this, separated by comma, we add multiple values inside of here. We can place in numbers. We can place in objects which we're going to look at next, or you could also nest inside an array too. To do this, we just create a new set of square brackets just like this. Then we continue to add our information inside. If we wanted to place in two strings, we would do it just like this. Or if we wanted to use an array for a list, let's say, a list of pizza ingredients, we would just do it by adding multiple strings separated by a comma. Let's say dough, cheese, sauce, and also some pepperoni too. Now, how do we access any of these values? Well, just like we did with any other values, we can also store this inside of a variable. We'll say let pizza to be equal to this new array. Then down at the bottom we have our documents. We select a new title and then suddenly in a text to be equal to this string. Instead, we can replace this string with the value of our pizza array. Refresh the browser, and then we see a list of all of our ingredients. Reading individual values from this pizza array is simple too. Array values are numbered from position 0, and this is called the index position. The first one of dough is index position 0. This is 1, 2, and 3. We can use this inside of the square brackets to access any one of these ingredients. Position 0, which is the dough. We can access this individually and also any one of the other values too. Arrays also have something which is called a property. As we get into much more detail about these object types, you will discover that object types such as an array will have multiple properties or methods available. These allow us to perform certain actions, or also access some information too. First of all, let's take a look at a property called length. Rather than accessing it, just take the value here. We can chain onto the end the length, refresh. We see there's four values contained inside of here. We could do this anyway which you wanted to. For example, if we wanted to place this variable inside of a string, we could open up the backticks. We say this pizza has used a template string. We can pass in a variable with the $ symbol, then the curly braces. Pass in the pizza.length. Then ingredients. Let's just say this pizza has four ingredients. Over to the browser, and there we go. Arrays also have some built-in methods available too which we can use to perform some common tasks, such as pushing a new item to this array. We can remove values and also check if the array contains a certain value too. For example, let's check if our pizza contains the value of pepperoni. To do this, we first access our array by the name. We then use dot includes; an inside of the brackets, we can pass in a value which you want to check. In our case, we want to check if this contains pepperoni. This will then return back either a true or false value if this is contained. We can also store this inside of a variable too. Let's call this hasPepperoni. Then below we can replace this inner text. Let's remove this template string and replace it with our variable. Give this a save. If you do see a jump just like we had there, this is just the text editor saving and reformatting the document. Make sure this is saved and over to the browser. This is true because the value of pepperoni is contained inside of this array. We can change this to be an incorrect spelling and this will be a false value. Or if we did have the correct spelling, we could also use the exclamation mark just in front of this, like we looked on the previous video. This will then return the opposite value, which is also false too. There's also many more of these methods available too. There is also a dedicated array section coming up to go into these in more detail.
16. Introduction To Objects: Another object type along with array. Well, it's an actual object, arrays which we just looked at contain multiple values. I'll reference a single value inside of the array by accessing the index number, which is the position beginning from zero. We briefly looked at objects earlier, and these are also a collection of values. However, an object value is referenced by a key. [inaudible] starts files and into the introduction to objects. We want to begin by creating an object. Let's say let user, and say this equals to our curly braces. Remember from earlier that we can add a series of properties which is a key and value pair. We have a key, and, for example, our user may have a First Name. I'm going to set this equal to a string, so we have the key and we'll have the value and it's this key which we use to access any of these values inside of here, separated by comma. Let's add a little bit more detail, the second name. We place in as many of these as we would like to, such as the occupation, web developer. For this example, we'll add a Boolean value of logged in, set this to be true. Finally, we can also add some fields inside of here, and this can also contain nested arrays too, just like a regular array we'll open up the square brackets and we can add inside of here as many values as we would like to. If we save this, and you'll notice here we have the level 1 heading. We access this heading, I'm going to set this is equal to our user object, so replace this string of text with the user variable. Save this file and refresh this inside the browser. As soon as we do this, we see the value of object Object. This is what happens when we try to display the full object inside the browser rather than an individual property. It converts all of this object into a string. An object, object is the default value which is displayed inside the browser. With arrays, we use the square brackets to access the values index number, but for objects, we instead use the square brackets to access each one of these keys. Instead of displaying the full user, open up the square brackets, and then inside, we access the property name inside of the string, just like this. This is going to reference our user's first name, and if we save this and refresh, this is now being replaced with the value. We can change this to be anything else such as the occupation, and this also works perfectly fine too. Another way we can do this to achieve exactly the same thing is to also use the dot notation. This is called the bracket notation because we are using the square brackets, but the dot notation is also a way to access any one of these properties too. We can say user dot first, this works perfectly fine too. During development, if we did also want to access the full object and see all of the available properties inside, we can make use of a console log, passing our user object and rather than displaying object object like we've seen inside the browse, if we were to go over to the browser and open up the developer tools inside of the console, we'll see the full value of this object. Once we click on this arrow just here, we can also expand any other object types inside, such as this array, and see all of the contents nested inside that too. These console logs can be useful for debugging and generally check-in what values are contained for any datatype. Also as well as this console log if we wanted to see the structured inside of a table format, we can change this to be a console dot table. Now we can save and refresh, and this will then display our object in a table-like fashion, which may be a little bit easier to understand all of the data which you have inside of an object. These console logs can be useful for debugging and generally checking what values are contained for any data type. If we had multiple objects, we can also place them inside of arrays too. This will be useful for storing lots of users or products. Instead of having this object here, we could change this into an array and then this would allow us to store multiple objects. Our first one, and since this is an array, we separate each value with a comma, and then each one of these objects we can add as many properties inside as we would like to. Sticking with the same thing we could add in the first name, and then separated by a comma, the last name. Let's just copy the details from this one, place this into our second object. I'm going to change the names, and of course, now we have multiple users. We could also change this to be users. If this was a real-life application and we were to make a database call for a list of all of our users, our data may come back like this, but now we'll have multiple objects inside of this array. Can you work out how to access both of these first names? Or remember that since arrays are indexed, we can access each object by the position inside of the array. This first one is index position 0, and the second one is index number one, so what we need to do is we can remove this. This is now called users. Open up the square brackets and we can access our first user with position zero. Remember from before when we were accessing the full object, just like this. It will display object object inside the browser. What we need to do is to access any one of these individual properties by the name of the key. We have the two keys of first and last. Let's go for the first, save this, and refresh. This has given us an error since the user is not defined. Let's take a look at the problem. I choose this console table here. We're trying to log out the user, but this has been changed to users, then reload the browser and we now accessing our first name. Let's go for the second object, so position one. This is how we access the values contained when we have multiple objects stored inside of an array. Along with users are also many, many other use cases for this kind of setup. For example, if you had an e-commerce store with all the collection of products and also the shopping basket could be an empty array, then each time the user adds a new product, the object will then pushed to this array. As you can see, there is many use cases for this and also so much more to discover with objects and arrays too. We'll go a lot deeper into these in the upcoming sections.
17. Introduction To Functions: Let's now take a look at JavaScript functions. A function is like a task or a set of tasks grouped together. For example, in our upcoming speedy shaft project, we'll have many functions which perform a certain task. Such as generating a new pizza, we'll have one for creating a new order, and also one to check if the event is full. These functions can either run immediately or more often when we call them at a later stage. Just like arrays and objects, which we've looked at in the previous two videos, we will have a more detailed functions section coming up in the course. But for now having a basic function knowledge will really help us with some of the steps. Also just like these arrays and objects, which we just looked at, a function also falls into the same object type Group 2. For this lesson head into the last folder inside of our JavaScript basics. This is number 13, introduction to functions. Open us up and also in the browser too. What we're going to do is first of all, we have two arrays just here which we can ignore and we can go just below these. We'll come back to these in just a moment. Although we'll take a look at how a function works and we begin by using the function keyword. The function keyword is then followed by a name, which we want to give this function. Just like a variable above, we then assign a name and for this example, let's go for random number. This is a name which we call a function by each time we want to run the code inside. Immediately after this name we pass in some brackets, which is called parentheses. Inside of these brackets we can pass in some extra information to the function, but more on this in a moment. The last part of this type of function is the curly braces and this is the function body. These braces inside of here contain all of the code which you want to run when we call this function by its name. These braces can also be thought of as a set of gates that contain all of the function code inside. This is what is called a function declaration. Inside we can place in any code which you want to run. Now let's place in a simple browser alert. Save this and over to the browser. If we refresh, we don't see this alert running inside of here. It actually run this code. Just like we mentioned, we need to call the function by its name, followed by these brackets just here. Just below this, call our random number, add the brackets or these parentheses. This should now call our function code and then display the alert inside the browser. Another good example of a function would be a calculator to convert a dog age to a human age. Let's start again. We'll go back to our original function keyword. This time we'll call this dogToHuman, add the brackets or the parentheses. Then the function body. Just above create a new variable, which is going to be our dogAge. Let's set this to any values, such as three. We can then access this variable inside of our function and then do a multiplication to convert it to human years. To access this variable all we nee to do is to access it by its name., so the dogAge. Then multiply this value to 7 to give us the human years. We can also store this inside of a constant. Let's go for humanEquiv. For now, looking at this function, all this is doing is grabbing our dog age variable, multiplying this by 7. But we also need to tell a function to actually send back this new value. The way do this is to use the return keyword. We can return our humanEquiv variable, just like before. We then call this function, which was the dogToHuman. If we save this and over to the browser, refresh, we don't see anything different inside the browser. We don't see anything different because in the first function we looked at, it contained an alert. This was a visual cue that the function was running. But this one, we don't have an alert, we don't have a console log, we'd not set in a Level 1 heading with it in the text. All we're doing is returning back a value. To actually use this value, if we wanted to, we could wrap this inside of a console log and see it return value inside the console. Or more commonly, we could store this inside of a constant called result. This result will then contain this return value, which is the dogAge multiplied by 7. If we wanted to, we could do a simple console log with the value of the result. But let's go one step further and convert this into a string. If we use the back ticks, we can also make use of this result variable. We'll say, My dog is aged. Remember to pass in a variable, we use a $ symbol, the curly braces. Then insert the variable name and then continue the string to say in human years. This should say My dog is aged, and in our case, this would be 21 in human years. Over to the browser and open up the console. Refresh the page and there we go. There's our new string with the variable contained inside. Just to recap, we've created a function. This function is going to access our dogAge variable of three. Multiply it by 7, we then store this inside of a variable and then return these results back from the function. We then call this function below and store this returned value inside of our results. Results can then be used anywhere inside of our code, such as just here when we insert it inside of a string. Also do be aware that this return keyword should only be used once inside of a function, since it signals that the function should stop running. There are however some exceptions, such as when using this inside of an if else statement, which we'll learn about later. But generally return is the end of the function and any code which you place after it will be ignored. We could see this if we add an alert. Then run this in the browser, refresh the page, and we see our console log. But we don't see any alert on the page because this falls after our return statement. This effectively ends our function. Let's remove this. At the beginning of this video, we mentioned that these brackets just after the function name, we can also pass in extra information to this function. In the bracket, we set up one or more parameters, which you can think of as variables. Instead of our dogAge just above, we can comma this out. We can pass in a variable or a parameter called dogAge directly into our function. We can also pass in multiple values separated by a comma. Then we could access this inside of our function, just like before. But this dogAge had a value of three assigned to it. How do we actually pass this value to this parameter? Well, we do this when we actually call a function just here. Let's go for a different example this time of five. Its actual value which you pass from a call function is called an argument. You don't need to remember this at the moment, but this is an argument and this is a parameter. Let's try this out. Give this a save and over to the browser. Now we see the different value of 35 inside of our log. As we've gone through this video, there has been a few key words involved. You don't need to remember all of these at this stage. People do often confuse parameters and arguments and also use them interchangeably. It's not a huge problem. But just to clarify, a parameter is the variable or the placeholder inside of our function declaration. We can then access them inside of our function body, which is inside of the curly braces. We then have arguments, which are the actual values we pass in when we call this function, such as our number in this example. Let's take this a little bit further by using our two arrays at the very top. Let's clean this up and move all of this function code. We're now going to make a function which is going to check for any allergies inside of these recipes. The function will take in it the recipe, such as bread and brownies. Then we can also pass in a particular ingredient which a person is allergic to. The function will then loop through all of these values and check if this is contained inside the recipe. Just like before, create our function. Give this a name of checkAllergies, the parentheses, and then the curly braces. For this function to work correctly, it needs to take in it two things. First of all, the actual recipe to check against. We'll call this the recipe perimeter and separate it by a comma. It also needs to be passed a certain ingredient, check if it's contained inside. Open up the function body. The first step is to access our recipe, which is either the bread or the brownies array. Since this is an array, we can then make use of the includes method. We did quickly take a look at the includes method earlier and this will check if a certain value is contained inside of this array and then return a true or false value. We want to check if this ingredient is contained, which is passed as a parameter. Although we have these variables, we have the recipe and the ingredients, this is exactly the same as if we were to access our bread array just above. Then call the includes method, just like this. Then we could check if the flour is contained inside. If it is, which is the case here, this would then return the value of true. If it wasn't found inside of the array, we'll get back the value of false. Both of these lines of code do exactly the same. The difference is we can pass in at different values to our function. Next, store this inside of a constant called hasIngredients. They should only ever be true or false and then we can return this back from our function. To see this return value, we can create a console log. Then inside of here caller function, which is called checkAllergies, add the brackets or the parentheses. Then we need to pass in two arguments. First of all, the recipe, which is either the bread or the brownies. Let's go for bread. Then pass in our ingredient which you want to check if it's contained inside of this recipe. Let's go for flour. We know this is contained inside of bread, so this should return a value of true. Let's save this and refresh the browser. Now we see our value inside the console. Let's try a false value. We'll go for eggs. This is false. But we know eggs is contained inside of brownies. Let's try this one and it should once again be a value of true. Just as a recap, if this is all a bit much at the moment, we are creating a function called checkAllergies, where we're going to check if an ingredient is contained inside of a recipe. We then access this recipe, which is either the bread or the brownies. We check if includes this particular ingredient. If it does, this will return back a true value. If it doesn't, it will return false, which will then display inside of the logs. Hopefully you should start to see the power of functions. But there is a lot more to functions, which we'll soon discover. One of the big benefits of functions is they are reusable. If we have codes in our programs which we repeated multiple times, we could grab all of our code and move into a standalone function and then call the function in place of this code. The function can also be passed different values in the form of arguments, which we've just discovered here. You can also think of a function as a building block for all program too. Each one is assigned a particular task, so we can make our code more organized. Functions can also be in many of the forms too. This example here is a more traditional form of a JavaScript function and there are other types available too, such as arrow function, which we will cover later on. As a general guide though, if possible, it is beneficial to try and keep all functions as small as possible and only focusing on one task. This makes it much easier to know what a function is doing, makes it more reusable. It also helps with debugging because if there is an issue, we can focus down this problem onto one particular function, so it's much easier to find.
18. The Array Constructor: Inside of this JavaScript folder, we now onto Section 2, which is this array section just here, and then lesson Number 1, which is the array constructor. Let's select this, and open this up inside of the browser. We learned in last video that arrays fall into the object type group and that they are a special type of object, which is like a list, and we can access any of these values by the index position. Inside this script, we have previously created arrays just like this. As you can see by the comment, this is an array literal. We declare we want an array by using these square brackets, and then we can set any initial values which we want to place inside, we can also confirm that this pizza array is an object type by doing a console log. Inside of the console log, we can make use of the typeof property, which we looked at earlier, we can check the type of pizza, and then inside the console we see this is an object type. There's also another way to create an array, and this is by using the array constructor. The array constructor can be used to create an empty array which you want to add to later, an array with empty spaces, or we can also add some initial values to it too. To do this, let's first remove our console log, let's just also place in a comment, this is the array constructor. The way we can use the array constructor is by using the new keyword, followed by array, which has a capital A. We can access and work with this later. We can also store this new array inside of constant, then let's do a console log, passing in the value of our new array which is ingredients, then let's see what this returns back inside of the console. What we have here is these square brackets and we don't have any values inside, we can also see the length property has a value of zero. Alternatively, if we did want to initialize this with some values, we could also pass in the values inside of these brackets. Let's go for dough, a second value of cheese, then inside the console we now see these two values inside of the array, and the length is now two. This way is just exactly the same as the literal method above, and the result is exactly the same. If we wanted to we could also replace these two values, and setup the initial length of the array. Here, we could remove these and we could declare we want a new array with five empty spaces. We can also see these inside the console, we see the empty times 5. This is just an empty array, which is going to be initialized with five empty slots. For me though personally, I prefer the first approach, which is the literal version. For me, it just seems a little bit more clean and descriptive, but it's completely up to you which one you want to use. It's also worth noting here that even though we've set up an array with five empty slots, this is just the starting value, we can also add to it by using a push method. The way to do this is to first access our ingredients array, and then we can chain on the end a push method, which is going to push a new value to the end of this array. Let's go for peppers, save. We now see we have six values stored inside of the array. The first values are five empty slots, followed by the new value, which we just push to the end of this array. We don't always want to keep this slot as empty. What if we wanted to replace one of these empty slots with a new value? To do this, we can make use of a method called splice. Let's say we want to replace the third empty slots with a new value, what we can do is to call the splice method and splice takes in up to three values called parameters. The first one is the position which you want to go to. Remember, since arrays begin at index position 0, the number 2 will access the third slot, separated by comma. The second value we want to declare how many items we want to remove, and in our case, it's just one. This will remove one item at index number 2, which is our third item. Let's say this and refresh the browser. Now we see we've removed a single value, leaving us with four empty slots. But if we didn't want to just remove this value, if we wanted to actually replace it with a new value, we add a third parameter, so let's say onions. Refresh this, and there we go. We have our first two slots, which is still empty; we have our third slot which has been replaced with the onions value; and then slot number 4 and 5, still remains empty. In this video, we've looked at the push and also the splice method. Both of these are really useful when working with arrays, and we'll cover a lot more during this section. Just for clarity for the remainder of this course, I will be creating arrays using this literal approach just above. But it is also really important to understand that different approaches exist, especially if you come across them in other people's code or other guides.
19. Introduction To Properties, Methods & The Prototype: I've mentioned so far various words such as object type, properties, and methods. It's useful to have at least a basic understanding as to where all of these are coming from. Jumping to our starter files which is lesson number 2 of this section which is properties, methods, and the prototype. Inside of our script, you will see three separate arrays. I have the margherita, the vegetarian, and also the pepperoni pizza array. So far, we've briefly looked at some examples of what we can do with arrays. These are how we can access properties and methods. The properties or the only property we've actually looked at so far is the length. Properties, we've looked at things such as the length which will access the array, and then chain on the end about length. This will give us the length of the array, so here we'll have three different items. Also we've looked at methods too. The methods which we've looked at so far is the push method and also splice. Again, these are also chained onto the end of an array, so this will be margherita.push or margherita.splice, and then we pass in certain values into these brackets. We've at looked at methods and we've looked at properties, but what exactly is the difference and where do these both come from? First, we'll take a look at where these actually come from. If we think about this, we already have three arrays inside of our script here, but we could have hundreds or even thousands on a larger program. Each one of these arrays also has access to all of our methods and also all of the other methods available too. This array could use the push. This array could also use push, and so could this one too. What if each and every array which we created also carried around the weight of these methods, it's a lot of extra code or information to attach to each array. It would make sense to be able to create multiple arrays like we've just done here. We'll have all of these extra things such as the methods in one central location to access whenever we needed rather than having them attached to each one of these arrays. Well, this is actually what happens with object types in JavaScript. JavaScript has a concept called prototypes, and this is a way for each object to inherit the features from another one. Let's take a look at something in the console by doing a console log, and then pass in the value of array. This array with a capital A is just like the array constructor we looked at in the previous video. It's like a template for any other arrays which we create such as this pepperoni just here. This will inherit any of the methods which live on this. Do you see these? We can log to the console, the prototype, and let's head over to the console to see the value of this prototype, refresh and open this up. A lot of this may look unfamiliar at this stage, but two things to point out here is we can see push and we can also see splice. Remember these are two things which you've already seen before when we looked at previous methods. This is how our new arrays have access to all of this information, its prototype which we've just looked at the console, is a property which points to another object, in our case, the parent object, and therefore inheriting all of its methods. We can also see this with things like an object too. Object with capital O if we save and refresh, open this up, this time we head into the constructor and this contains a list of all the methods which is available for this object. We'll take a look at these in the object section later. Just to recap when we create a new object or a new array, which we have done here, these new arrays will automatically get the prototype property added which will allow us to access methods from another object. In our case, these are all inherited from the parent array constructor and this is why we couldn't use certain methods on each one of these new arrays such as the push and splice, and as well as these inherited methods which is available, we can also create our own customer wants too. Now if we log one of our own copies of this constructor, in our case, pepperoni, over to the console and refresh. Open this up. At the bottom we see this proto, and if we open this up, this isn't linked to all of the available methods for this array. This is how this copy of this array gives us access to things like push and splice, which we've just looked at. If we close down this proto section, we've see alongside we have this length property. This length is not included inside of the prototype. Here lies the difference between a method and a property. Since any of the methods can be used on any of our arrays, they can be shared via this prototype. This length property, however, is specific to this one single array since each array can have a different length. It makes sense to not share this on the prototype and just have this available on each individual array. We'll go deeper into this later on but at least for now, you have an idea of where these methods are coming from and we'll discover lots more of these methods in the upcoming videos.
20. Modifying Arrays: Although array methods are not strictly grouped into any form of category, some of them share some characteristics. For example, some array method which we'll perform, involves something called iteration. We will look at this in a future video, but you can think of this as repeating the process, for each item inside the array, just like a loop, if you've used them before. Also, some methods take our original array and modify it, and some, will leave our original array intact and return a new array of value based off the original. What we're now going to look at is modifying arrays. We have already looked at some array methods, which modify existing arrays, such as push and pop. We've used the push methods as a new item to the end of an array. There is also the pop method which will remove the last item from the array. Not only do we need to be concerned with modifying the original array, the value which is returned back can also be important too. Over to the project folder, head into this lesson which is modifying arrays, and also open this up inside the browser. Inside the script, we'll have three lines of code already setup. One is used a pizza array with three values. We then select this, push a new value to the end of pepperoni, and then we'll log this to the console. If we go over to the browser into the console. We see here, we got the new array value of pepperoni pushed on to the end. Well, what about the return value we get back after running this method? See this, we can store this inside of a variable. Let's say, const, call this returned, and set this equal to the value which is returned after this method has been performed. Then if we grab this and place it inside the console log, refresh, we now get the value of four. The returned value after we use the push method is a number of items inside of the array after this new item has been pushed. In our case, we now have four values. We get this value of four returned. As you can see, not only is the array methods useful in itself, but often returned value which we get back can also be useful too. Next, we also have the pop method to remove the last value from the array. Let's comment out this line just here. We'll select our pizza once more, access the pop method, and then we'll do a console log for the original pizza. As you would expect when we use the pop method, this will remove the cheese value, leaving only the dough and sauce. Again, what would the return value be after running the pop method? Well, let's check this. Again, we'll store this return value and then log this to the console. Let's check this out, refresh, and we'll get the value of cheese. Rather than the length of the array which we've seen before, after we use pop, we get back the value which has been removed from the end of this array. Both of these methods which we just looked at, the push and the pop, will affect the end of the array. Do the opposite and affect the beginning of the array. We also have two other methods. I'm not going to type this out since these work exactly the same, but unshift adds a new value to the beginning of the array, and shift removes the first value. The return values also mirror push and pop. When we add a new value using unshift, we'll get back the land of the new array. When we remove an item with shifts, it returns the value which has been removed, which would be dough. Next up, we have the splice method, and this is something which we've already looked at to remove and replace items at any position in the array. These previous ones we looked at, we'll work with the beginning or the end of an array. Splice will select any item which you want to. It can take a multiple parameters and it's really flexible. This example here has three parameters. First, we have number 1, and this is the array's index number to begin with, which for us is the sauce. Next, the number of items to remove. In our case, one will only remove this single value of sauce. The third parameter, insert a new value at this position, resulting in the new array we see down at the bottom. Let's take a look at some more examples over in Visual Studio Code. We can comment out this line just here. Down below, select our pizza. Then we'll take a deeper look at splice. If we just add in the first parameter which is the starting position of one, and then we'll log the pizza after this method has taken effect. Let's see what happens inside the browser. Refresh and we only see the value of dough. This is because we've started with position 1, and then remove all items which follow right to the end of the array. A positive number like this will start at the beginning of an array. We can also use negative values to start at the end of the array. Let's take a look at negative one. This will remove the last array item of cheese, even our dough and our source. If we change this to be negative two, this will remove the final two items, leaving us with only the dough. As we know, we can add a second parameter, we'll just start this again on number 1. We can add a second parameter to only remove a certain number of values. Let's say we wanted to replace the regular sauce just here with some barbecue sauce instead, just like we've seen over in the slide. What we need to do is to remove this one and only item I placed in one, and then replace this with a optional value. Inside the quotes, we can replace this with barbecue sauce. Save. Refresh. Now, our second value, our index position 1, has been replaced with our barbecue sauce. If you wanted to also insert another value at the same position, your stuff towards, all we need to do is to add this at the very end, separated by a comma. Let's go for peppers. They should add just after our barbecue sauce. As you can see, this splice method is really flexible for adding and removing values at any index position inside of an array. Next up, we have sort which will sort the array values alphanumerically. Basically, in alphabetical order. These will also be in ascending order, and also, the reverse method which, as it sounds, reverses the order of the array values. We also need to be careful when using sort with numbers. We'll take a look at why in just a second. First of all, what we're going to do is to comment this out and access our pizza. Then it just call the sort method on its own. Log the pizza, and let's see what happens. We have dough, sauce, and cheese. Let's see what happens over in the browser. Refresh. These are now in alphabetical order. This all works as expected. However, though, this is fine because we're using a string of text for each array value. But if this was an array of numbers, it would cause an issue. The reason is because even if our array contains numbers, all of the values will be converted to be strings, and then arranged alphanumerically, so the series. Let's go back to the editor. Instead of these strings, we're going to go down, and instead, it creates an array of numbers. These can be any values inside of here. I'm going to go for 12, 1,000, and then three. Now, we need to access the numbers array and also log this to the console. Just like before, we call in the sauce method. But let's see what happens now, these are all as numbers. Say this, and now, we get the value of 1,000, 12, and three. What we should get back is three, 12, and 1,000. This is all completely wrong. But the reason this happens is because all of these numbers are converted to strings and then sorted as these string values. In just the same way as if all of these numbers were words, the sorting begins at the very first character. Here, we see the value of one and also the value of one, which is why these two numbers begin at the start because one is lower than three. Three is placed at the very end. But then, why is 1,000 lower than 12? Well, this is because again, just like with text, if the first character is exactly the same, just like these two ones, it will then compare the second character. With 1,000, this is the value of zero and this is the value of two, meaning that two was a higher value placed on this after the 1,000. Obviously, this is not a good way for sorting arrays of numbers. For this, the sort method can also take in a comparison function. Remember, from earlier, we took a look at how a function works. A function looks just like this, we have the function keyword. Then we give this function a name. We use the brackets or the parentheses, and then the curly braces to run some code inside. Optionally, this can also take in some values, and I'm going to, for now, pass in the values of a and b. Don't worry about these for now, we'll take a look at what this is in just a second. What we can do is we can cut this function out and instead, place it inside of the sort method. Place this in. If we wanted to, we could also optionally remove this function name since it's automatically going to be called from this sort method. Then inside of this function body, what we're going to do is to return a takeaway b. Now, this may look a little bit confusing but what's actually happening here is we're going to call this function for each value inside of this numbers array, we pass in a and b, and these can be any names of our choice. It doesn't matter this is called a and b, it could be number one, number two, it could be anything which you want to. But the key factor here is we're going to compare two numbers at a time. When this first begins, the sort function will replace a and b with the first two values of 12 and 1,000. This will be exactly the same as returning 12, take away 1,000. Then the second time, it will be 1,000 of three, and this will keep going until the end of the array. For the first one which is 12, take away 1,000. This is obviously going to result in a negative number. This will be pushed back to the start of the array. It will then go through and repeat this for each pair of numbers, sorting these in the correct order by comparison. Now, if we remove this line, we still console log in the new array value, save and refresh. These are now in the correct order. As you can see, this is really useful if we have an array of numbers. We don't want to rely on the alphabetical conversion, which we've seen in the previous example. Finally, we're going to take a look at reverse. Reverse, by comparison, is pretty simple compared to this. All we need to do is we'll comment out this example, access our numbers, and then call the reverse array method. Save this. Now, instead of having the value of 12, 1,000, and three, we now have the value of three, 1,000, and 12, which is the reverse order.
21. Returning New values: In the previous video, the methods we looked at all had something in common and that was we modified the existing array even if they did return some in any way, like a true or false value, the original array was still modified too. This video is going to continue with some more array methods, but the difference is this time, the original array will stay intact, and something new will be created or returned. An example of this is something we've already used, which is the includes method. Includes will return a true or false if a particular value is included in the array; therefore, it doesn't modify the original array. We also have the join method, too, which takes our array values and joins them together as a string. Inside of our project, in the Returning New Values file, down to the script, we have this example just here. This is an example of includes. We're checking if this pizza array includes any dough. If it does, this will be returned value of true; if not, it will be false. We then output two values. The first one is the pizza array; and therefore, we can check if this has been modified and then isIncluded, which is the return value. Save this, and open this up inside the browser. Refresh, and we can see the original array is still unmodified, and then we get the value of true. As you would expect, if we were to change this to be something else, this would then be the value of false. We can see this includes method will leave the original array intact as does the join method too. Join will also leave the original array as it was and returns back a new string containing all of the array values separated by a comma. Let's comment out this line just here, set up a second constant called string, and this is going to be equal to pizza.join, which is going to grab all of the values inside of our array and join them together as a single string. Change this value to be string, refresh, and there's our new string separated by commas. If we didn't want to use commas, if we wanted a different character to separate these values, all we need to do is to pass in a new character as a string inside of this join method. For example, if we wanted a dash, we could use this and also just like with any other string, we could also add spaces inside of here to add some space around each one of these words. Next up, we're going to work with the array's index position. Since array values are stored numerically, we often need to access a value in a certain index number, but if we don't know the exact index number to begin with, we can use a method called indexOf to find this for us. In this first example, we pass indexOf the string value of source, then we get back the index number, and since arrays begin at position 0, sauce is position 1. The second example shows lastIndexOf, and it may sound like this is for selecting the very last array value. However, it's to find the last occurrence of a value. This array has the value of dough place inside twice, so it looks for the last occurrence of this word, which is index position 3. Back to our editor, let's take a look at some examples. We can remove this string and this time, we're going to search for the index number of a particular item. For example, if we were looking for the sauce if this was a really long array, we wanted to find exactly what position this was at. For this, we can set our constant equal to pizza.indexOf, and then find the index number by the name of sauce, and this would then be stored inside of this constant, pass this into our console log and save, refresh. As we know, this is the index number of 1. We can go for cheese, and this will also be updated, and then once we have the index number of any array value, we can then do anything we want with it, such as selecting it, we can remove it, and also even replace it too. Next, we have lastIndexOf. Make sure the I and the O is capital letters. Remember, as mentioned with the slides, this doesn't find the last index value of our array, instead it will find the last occurrence of a particular value. By this, it would mean if the word cheese was placed in twice, so let's also add cheese at the beginning of our array. We now have two occurrences of the same value. lastIndexOf will return the last occurrence of this word, so rather than this being position 0, it will return index number 3. Let's check this out. Refresh, and there's our value of three. If this was moved to just before our sauce, the last occurrence would now be index number 2. Also, for this one, the lastIndexOf and also the indexOf, if it doesn't find any matching values, it will return a value of negative 1, so if we change this to be a value which is not in the array, the returned value would be negative 1. The last two methods we're going to look at is going to be slice and concat. Slice is a way to slice out some value from the array, and this example shows passing into values which is 1 and 2. The first value of 1 is the starting position, and for this example, this would be our sauce. The second value of 2 is the optional end position, so it will slice all values up to but not including this position, so this results in only the value of sauce being sliced. If the n value was number 3 instead of 2, it would slice out both the sauce and the cheese. The second example is concat, and this joins together the values of two or more arrays. We have the pizza array and also some optional extras. If we wanted to combine these into one single array, we'll call one of these arrays such as the pizza, we add the concat method, then we'll pass in the extras array to join all of the values into one single array. Let's take a look at these over in our project folder. We can remove the lastIndexOf, and take a look at how slice works. We'll access our pizza.slice and inside of here, if we only add one value just like this, this would be the starting position; so therefore, this would slice all of the values out of the array from position 1 right to the end of the array. We can store this inside of a variable, then log this to the console, initiate slice. All of the values from index number 1 right through to the end of the array. We have dough, cheese, and sauce. Refresh, and there we go. As with all of the methods in this video, we still see that the original array is still intact. Instead, we can return back a new array with these slice values. Also, just as we've seen inside of these slides, we can pass in a optional end position. This will start our index number 1 and end our position at number 3, but remember, this third and final value will not be included, so this should only return the dough and the cheese, and this is what we see in the console. In these last few videos, we've looked at the slice method and also a similar one, which was splice. On the surface, both of these methods do look pretty similar, but the difference is splice removes or adds to the original array, and the splice method keeps the original array intact and instead returns a new one with the selected values. The use case of both of these depends on if we want to keep the original array or if we want to modify it. Finally, we're going to look at the concat method. To do this, as we've seen inside the slides, we need a second array to merge in. This would create a second array called extras, which will contain some additional toppings. Let's add in some peppers and also some onions. We can then comment out the value from before. Create our newPizza, and the newPizza is going to be equal to both of these arrays merged together. To do this, we'll first access one of our arrays, such as pizza, we then call the method which was concat, and then merge in the extras. Save and over to the browser. Oops, we just need to log the new pizza. Refresh, and into the console, and like with all of the methods in this video, the original array stays intact. We're logging the pizza just here. We have a newly returned newPizza array, which is a combination of the pizza array and also the extras too.
22. Iteration Methods: The final group of methods I'm going to show you in this video is methods which will loop over each one of these array items and then run a function for each one. Over in the starter files head into the iteration methods, which is in Section 2 and number 5, these iteration methods which run a function for each one is really useful when we have lots of array items and I want to repeat a process for each one. Inside of the starter files index page, you can see up at the top we have three user roles inside of the comments. If you use something like WordPress in the past, this will look very familiar. This is a common setup. You can see here we have all roles and an array and this will really common if we had multiple users on our site and we wanted to give the users different levels of access. For example, if we had a use object with the name and all the rest of the use information. We could also add an array just like this. We could inside place any roles and permissions which that user has. Then we could check against this before they do any actions on our site. Such as, if they're about to publish a blog post, we may want to loop through all of the roles inside of the array and check they have the correct permissions before doing so. Just like with WordPress about the top, we have the admin, which is the full-size access, and it has all the permissions, do pretty much anything on a single site. We have the author and the author can't publish things such as their own blog posts. They can also edit them. They are effectively in charge of their own content. Well, this will have a subscriber which is generally the default settings with a WordPress site. They can't manage our side, they can't edit any content. All they can do is basically manage their own profile. What we're going to do here is to simulate a blog post site where a user might be able to create their own blog posts. As soon as the user has logged in and created a blog post, when it then go ahead and click the Publish button, we first want to loop through the user's roles and check they have the correct permissions. In our case, we want to check if they are an admin or an author. If they are, they can then go ahead and publish. If not, they will need permission before this is live on our site, and to do this, we'll create a function. Because remember these iteration methods will run a function for each value inside of our array. This function will call this canPublish and this is going to return a true or a false value. For this, also check the roles we need to pass in a role to the function and then we want to check if the role is equal to the admin or equal to the author. We can use role, the triple equals to check if the row which is being passed in is first equal to the admin. All user needs [inaudible], which is the or operator which we've previously looked at. We can also test if the role is equal to the author. If is, we're going to return this value, which will be either true or false, and to see this return value, we'll create a console log, just blow and this console log is going to call this function. Passing it canPublish and we'll first begin by passing in the admin. This admin string is going to be converted to this role and we check this role is equal to the admin or to the author. Over to the console. Refresh this page, and this is of course true. Let's also try the author, which is the second condition just here and this should also be true as well. Finally, subscriber and this one is false. Our function is working correctly. But at the moment, it's very manual. We have to manually pass in each one of our strings and check inside of here, each one one at a time. This is fine when we only have three separate roles. But imagine if you had to repeat this for say, 50 different roles on our site, this will become a long and tedious process. Well, to help with this, we're going back to the whole purpose of this video, which is to look at iteration methods. This will save a lot of all manual work by looping over each one of these roles and checking if it contains a particular value. The first iteration method I'm going to look at is some and just like other methods too, we'll begin by accessing the array by the variable name, and then we call the some method afterward and this is going to check if some of the array values are a much, but a much for what? Well, using this same example, we can move this function into the some method. Grab all of this code just here, put this out, and place this just inside of the brackets. We can't remove this function names since we don't need, role is manually. It will instead be called once for each value inside of this array and this is often referred to as a callback function. This function would now be called three times. The first time role would take on the admin string, it would then be author, and then the third time would be the subscriber and for each one of these roles, it would then run the code inside of the function. Just like with all this function is still returning a true or false value and we can capture this return value inside of a variable. Inside of the console log, we are still calling canPublish. But this time this is not a function so we can remove the parentheses and you simply log the value of this constant. Now gives us a save, refresh and this value is now equal to true. This is true because at least one of the roles inside of here is a match. If none of these was a match for admin or author, I just changed this, we can go for moderator and let's say guest, save this and refresh, and this is now the value of false. Looking at this slide, this is the same method we see up at the top. Just to recap, it will return true if one or more of the array values are much for the call-back function. But what about instead if we wanted to get a true value only if all of the array items are a match? Well, for this use case for how the every method, and we can see an example below. This is an array of this year's test scores. Then we run a callback function for each value in the array. For every two return true, all of the array items must be over 95. If a single one is under 95, it will cause it to fail and return a false value. We use these methods if we want to if return similar values or every value. Instead of just having a stand alone array just like this, it's more common to have this attached to a user object. Imagine we had a site with multiple users, and these were all stored inside of an array. Then inside each one of our users has its own user object. Open up the curly braces for an objects. First we'll just have a user ID of one, separated by a comma. The second property of role of admin. What I'm going to do is to add a comma at the end of this, and then copy. We'll paste this in a couple more times. User 2, this time a different role of author. User 3, this one can also be author two, and then finally, number four can be the subscriber. Using a iteration method means we can live through each one of these user objects and filter by a particular role. Let's imagine we wanted to grab at this particular user, which is the role of subscriber. Since this is an array to do this, we may also need to find the index number before we can grab this information. For this, we have something called find index. This example also has an array of user objects. We then call it find index method, and it will run a function for each one of these values. Each one of these values is stored in the functions user perimeter. In the return statements, we access the user, select the role, and check if it's equal to admin. It will then return the array's index position of the first match. For this example, it's the first value which is position zero. Let's give this one a try ourselves. Back to our index page, I'm just going to clear things up. Even just this user array. Then at the bottom we're going to access our users, we'll then call the method which we just looked at called find index. Like all of the rest of the methods, this is also going to take in a function and we also need to pass in the user. Just like before this function will be called once for each item inside of this array. The first time it loops through it will be user 1, user 2, and so on. Then what want to do is to access the user , I'll just move this over. Then we want to access the individual role. If we wanted to find this subscriber role, we could check if this is equal to the string of subscriber. Then return is value which is going to be true or false. Then store this returned value inside of a variable. Let's check this out by doing a console log. Means to log this variable of index, refresh the browser and we get back the index number three. This is index number 0, 1, 2, and 3. We now know this is all working correctly. As we can see, this returns the index position. But what about if we wanted the actual value such as this full object? Well, for this we have a method available to us called find. Find will select the first match inside of our array. For example, if we had multiple subscribers, the find method would be useful for finding the very first one, which it comes across. This example also has an array of user objects. We then call the find method, and it will run a function for each one of the values. Here we check if the role is equal to author and then find will return the first object, which is a match. In our case, it's the user number two. In this case, we just change this to be find. This time we'll check if the user's role is equal to the author. Both we have two author roles inside of the array, and this find method will select the very first one. We'll rename this to be the author and also log this to the console. Save and refresh, open this up. This has selected user number two, which is the first of our two author roles. This is really useful for finding the first match inside of our array. But what about if we wanted to select both of these users which were a match? Well, for this we also have a method called filter. Using the same example as before, all we've done here is to change the find method to be filter, and this will return all of the matches instead of the first one. Meaning we get back a new array containing user 2 and also 3. All we do is change find to be filter, and instead we get in back multiple authors so we'll add an s onto each one of these. Save and Refresh. We're now see an array containing two separate objects. If we open this up, inside of here we can see we have user number two and also number three. It is all really useful methods for selecting values inside of an array. Also some things to be aware of as well is since ES 2015, we also have a different type of function syntax which we can use, and this is called a arrow function. Arrow functions have some behavior differences to this traditional function, which we'll look at in more detail in a later section. But for now, we can also use them to shorten our function code. The way to do this is to remove this function keyword, and then just after these brackets we then place in an arrow. An arrow consists of the equals and the right angle bracket to create this arrow function effects. As it stands, this code is completely valid. This is fine to use. If we were to save this and refresh, we still see the same two results, but we can also shorten this function even further. We can place all of this code onto one single line by removing these curly brackets. We'll move both of these and place this all onto a single line. Bring this up just like this. Then we write an arrow function just like this on its own line. We can also remove the return keyword to, since this will be automatically returned for us. Again, this is all perfectly valid and if we refresh the browser, we still see the same two results. Finally, if we only have one single parameter past this function, we can even remove the surrounding brackets just like this. But you be aware, if we do have multiple parameters, we had to pass in a second value inside here, we would still need to add the surrounding brackets. A syntax is often used to keep things like this, which are more simple and add all of our code onto one single line. It's up to you, which type you prefer to use in your own code. But it's useful to know both of these styles exist because you will see lots of examples online. These last few videos I've shown you some of the more popular array methods, and there is still a few more too, but they all generally work in a similar way. There's also more of these iteration methods too. Coming up, we'll take a look at these in more detail.
23. Reducers: We're now going to cover a technique to reduce an array down to one single value. I'm going to do this using the reduced method. The reduced method, like previous ones we've looked at, will take in a function and run this function for each array value. It's more simple. We could add together an array of numbers, and then return back the total of them all added together. Of course, we can go much more complex if we need to as well. Let's take a look at some examples over in these data files. Head into this one which is the reducers. You can see, inside of a script we have a simple numbers array containing five different values. If all we want to do is to add together all of these values and return the total, the reduced method is perfect for this. As with other methods, just below we can call the reduced method onto the array's name. Which in our case is numbers. Call reduce, add the brackets, and then we're going to run a function for each value inside of this array. This function could be passed directly into the brackets just like we've done previously, or just as with all of the methods, we could also keep these separate if we wanted to. This also has the added benefit of, it's more reusable, if we want to use it elsewhere too. Either way is completely fine. But for this example, we want to show you the alternative approach, which is to create the function separately. Create our function just below this. Since this will add together all of the numbers and return back the total, we'll give this a name of total, add the parentheses, and then the curly braces. For this, this is going to take in two parameters inside of the function's brackets. This is going to be the total separated by comma. The next one will be the current value. Then inside of the brackets or inside the braces, we're going to return the total, added to the current value. I'll explain what this all does in more detail in just a moment. But for now, since this function is separate from the reduced method, we also need to call this inside of the brackets. Again, just to clarify, this is exactly the same. Let's place this directly inside of here. Back to this function, and this is called once for each one of the array values. For this example, it will run five times. This is where these two parameters will come into play. For each loop, the current number over on the right is pretty self-explanatory. This is the current array value such as 72 and 33. But first, we have a total row over on the left. This is the total from the previous loop, often called the accumulator, since it accumulates the previous results. Just to clarify what's going on here, we'll take a look. We'll add a quick comment inside here. The first time this function will run, this will be the loop number 1, and the total, which is this one here, will be equal to zero, since we've not added together any values just yet. The second value of current value, this will be 72, since this is the very first value inside of the array. Then move on to loop number 2. First of all, again, we have the total, which is these two values added together. These two values added together will be equal to 72. Then the current value for this one is number 33. Again, exactly the same for loop 3. This time we'll add these two values together, which will give us the result of a 105. Then the current value this time is a 108. You can see a pattern here for each loop we're going to add together both of the values. This time on loop number 4. These two added together, for loop number 4, will be 213. The current value for loop number 4 is 222. Then finally, loop number 5. These two values added together for loop 5 is going to equal 435, with the current value being number 6. Of course, so don't take my word for this. We're going to log into the console, and check what the values are. Remember, we are returning this final value back from the function. We can store this inside of a variable. Say const result is equal to this return value, and then a console log. Just so you know too, that Visual Studio Code will run a console log, or a shortcut to this, if we just type the word log and then hit "Enter", pass in the result. We can check this out over inside the browser. Inspect, into the Console, and we see the value of 441, which is the final two values added together. This is added to get the all five of these numbers, and then return the final value inside of this function. We can also do anything else we want to with these two values, such as subtracting. Let's change this to be a negative. Give this a test, and we get the return value of negative 297. This will do exactly the same, we'll run through five times, but this time we'll deduct the current value from the total, which is why we get this negative value. I'll just reinstate this to be plus. This adds up our array values from left to right as we've just seen with this example. We also do have a similar method which will work from right to left. This is very simple. All we need to do is to change reduce to be reduceRight. Give this a save and refresh, and we get the same value of 441, because we're adding together the same numbers, but this time it's just in a different order. To double-check, this is going from right to left. We're completely sure even though we've got the same value just here. We can also add in an optional index number. Add this in as the third parameter to our reducer. Then just before we return this, we can do a console log. Log the value of the index. We should see the index number going from the highest to the lowest number. This is the last number which is index number 3, all the way down to zero. Both of these functions, the reduceRight, and also the reduce are useful for lots of reasons. We may want to keep track of a user score or points this way, and then total all of these values together at the end. This information can then be used in other ways too, maybe to find the average score. To do this to find out the average number inside of this array. Just below our reduceRight method here, I'll create a new constant. Just all this in call the average, and set this equal to a calculation. The calculation which we want to do is to grab the full results, which is the value of all of these added together. This is step 1, and then we need to divide this by the number of items inside of the array. Again, we can do this pretty simple. We need to access our full numbers array, and then the property, which is length, which we've looked at in the past. We can then console log the average, head over to the browser and refresh. We can now see the average is 88.2.
24. Map & forEach: I want to now show you two more array Methods. As you can see by the title, this is Map and forEach. These two methods are also iteration methods like we've looked at previously. They will loop over each array item and then it run a callback function. Lots of the array methods which we have code so far, and much more specific, such as sorting an array, we can do filtering, we can check if one value exists, but these two methods, which are MAP& ForEach, are much more general. The use for their purpose is only limited to the code, which we write inside of the function. Open up the Map and ForEach file. Then inside of this script will have two arrays. We'll have a simple numbers array and will have an array of blog posts, which we'll take a look at in just a moment. But now we're going to start by accessing the numbers and then as always, we call the method with dot or by the name of ForEach. We could write a function that just like we've looked at previously inside of here. Using the more traditional function syntax or also for the practice, I'm going to convert this into an arrow function. An arrow function, which we've looked at previously, begins with the brackets just like this. We then write an arrow with the equals and the greater than symbol. Then we have a couple of different options. If we wanted to, we could add multiple lines of code inside of the curly braces. We could write our code inside, and then we could use the return keyword to return a value back from this function or alternatively, like we've looked at previously, we could emit the return keyword and place this onto a single line. If we place in this onto a single line, we can also remove these curly braces, and this will directly return the code. Let's do a console log, as the return value. Remember that since we're looping over each value in the numbers array, this is also going to take in the number as a parameter. Now, we'll have the freedom to do anything we want with this parameter, such as a simple console log. We can now put the number, multiply by two. Check this out over in the console refresh so we see 144, 66. This is just all of these numbers multiplied by two. The index number is also available too, if we want to insert this as a parameter. Remember a comma and the index, then we can use this index in any place we want to in our function. Let's remove this. I want to add in the template string with the backticks, so we can insert a variable. We'll have the text of number available, which is a $ symbol, and the curly braces, pass in the index, then a colon, so what we're going to say here is number one and then a colon. Then also insert our number. If we want to, we can do something similar to the previous attempts, which is multiplied by two. Let's save this and over to the browser. There we go. We can access the number zero, number one, number two, and see each one of the individual values. Again, if we wanted to, we can also manipulate this. If we want this to begin at index number one, we could add the value of one. Then this time, rather than beginning at number zero, this will begin at number one. As mentioned before, we can write any code inside of this function and taking our post array from above. Let's take a look at an example with an array of objects. What we're going to do this time is to loop through all of our posts and then run a function for each one of these objects. We'll select the blog post title and then it transform the text to be uppercase. For practice, we'll start again, will access our posts, call for each, open up the brackets and then we can insert a function with any syntax which you want to. This video, I'll stick with the arrow function, which is just like this. Then again insert a console log. This time we're looping through all of the posts. This function will take in a parameter for each post. Also, if you remember, if we just have a single parameter just like this, we can also remove the surrounding brackets, make this a little bit shorter. Sometimes though, if you do save just like this, the text editor will reinsert these back-in, but that's completely fine. What we're going to do now is access these individual posts inside of our console log. Then since this is an object, we need to access one of the keys, such as the title or the body. I'm going to go for title. Then I'm also going to insert a method called toUppercase. So far in this section, we've been using lots of methods which we'll call on an array, but toUppercase is also a method too. But this one is used on a string of text. Let's try this out. Over to the browser and refresh. There's our three titles so we call the function three times and for each one we select the title and transform the text to be uppercase. This is the ForEach method, but what about Map? Let's go over to our editor and all we need to do is change ForEach, we Map, save and refresh, and we get back the exact same values inside the console. Between Map and ForEach, they look very similar. What exactly is the difference? There's a couple of reasons why they are different and one is the return value. To see this, we need to store this returned value inside of a constant or a variable. We'll say new posts and set this equal to our return value, changes back to be ForEach. Then instead of the console log will just return the value of this transformation. Remember we may have a single line with an arrow function like this. This will automatically return this value back for us. To see this place in a console log with the return value which is stored inside of new posts, save over to the developer tools and we see this new value of undefined. We get back undefined because nothing is returned back to us. ForEach, we'll run a function for each one of these array values and then directly modify this original array without returning anything back. Map, on the other hand, if we change this, save and refresh, we now get back a new array with free of the transform values. This is the key difference between Map and ForEach. ForEach, we'll modify the original array. When you use Map, this will leave the original array in tact and instead return a new array with the modified values, so this is one key difference. Another key difference between these two methods is when is a Map, we can also chain on multiple methods. To see this more clearly, I'm going to place this on multiple lines and the Map section onto its own line, remove the semicolon, and then we can chain onto the end a filter method. Keeping with the same style will add an arrow function which takes in the new value, sets up our arrow and then we can filter out any of the blog posts where the particular value or title is equal to be" How to be a ninja part two. " This also needs to be uppercase, since we've already transformed this with the Map just above. Now, as we already know, this title is included, so this will filter out our one single post. If we go over to the console, we can see this if we refresh. Now, we'll have a new array return back to us with this one single filtered value. Alternatively, if we didn't just want a new array with this one single value, we may want to just check if this title is included inside of our posts or we could do this, by changing filter with the some method. This will return back a true or false value, as we already know, its titled is already included. Now, if we refresh this, we get back the value of true. If we change this to be something which is not included, this will return the value of false. This is really useful for getting back the exact data which we need. We may also want to grab the index position of this array elements. We can do this by changing this back to one of the recognized titles or part two. Then instead of still making changes to be find index which we've used previously, save. This is going to be index number two and there we go. You can see with these examples that although all of these methods may look complex to begin, many of them are structured exactly the same, but just return different values. Back to this Map and this ForEach, none of this chaining or adding a new method onto the end is available when using ForEach. We can see this if we change this back over, refresh, and now we see an error inside of the console. This training is not possible when using ForEach because as we've seen before in one of our tests, before each method will return undefined rather than a new value. Just for a recap, we use ForEach if we want to modify the existing array and do not need a new one returned. We use Map if we want to leave the original array intact, and return a new array with the values. It's also good for chain too.
25. Array Destructuring: Yes, 2015 introduced destructuring, which is a simple way to pull out arrays or object values and store them into variables. To start a project, which is array destructuring contains an array of blog posts, just like we had in the last video. If we wanted to store each array value into a new variable, we can do this by adding destructuring. We can do this on the left-hand side of this equals. Instead of storing all of this into a single post variable, what we can do is add the square brackets just like this, and then we can create a new variable value for each one of these array items. The first one we can call post1, post2, then post3. These separate array value should now be stored into these three variables. Let's test this. Your console log with the value of post1. Refresh, and there is our single blog post. Let's try number 3. There we go. We can see each one of these three values is now unique, is destructure, and can also take place separately too. We could also set up exactly the same result like this. We could create a new variable and then store our values inside of these square brackets. Just like before, we can store post1, post2, and post 3, and set them equal to all posts. Again, with one of our single posts already selected, we can check this out. Post3 and also post2, so this is the same thing we just wrote in two different ways. Doing it in this style also means that we have access to these three destructured variables, we also maintain the original reference to this full array, if we wanted to also do some fun with this later on too. You can think of this destructuring as a shortcut. Doing this is exactly the same as something like this. We could set them up individually by creating post1 and set this equal to our posts array, selecting the original index value. Let's duplicate this two more times. Post2 will be equal to our first index position, and then post3 is equal to index number 2. Now with post2 already selected, over to the console. It still works just like before, but we'll have a longer way of doing things. Let's remove this. Something else we can also do is to make use of the JavaScript rest syntax. The rest syntax is a way to access a single value or multiple values, and then a way to grab all of the rest of the values to the end of the array. For example, if we just wanted to setup a variable, again, we need the square brackets. If we just wanted to access our first post and keep this with a separate variable name just like this. Then we may want to grab all of the rest of the remaining values, we can do this by separating this with a comma using the three dots, and then store the rest of the values into a separate variable, set this equal to all posts array. Let's confirm this inside of our console log. Post1 is this one just here. There we go. That's our first blog post just here. Then inside of this others variable, we should have the contents of the remaining values, which is blog post2 and 3. Changes to our variable of others, refresh. This is a new array with our two remaining values. This destructuring is really useful for creating shortcuts, to store different variables. Destructuring can also be used with objects too, and we'll cover this later on in the course. One thing to make sure of is when using rest, that we also add this as the last variable value. We couldn't, for example, place this at the very beginning, because as the name suggests, this will grab all of the rest of the remaining values. If we do this, and then save and refresh, we see an error inside the console. This happens because as the name suggests, this is used to grab the rest of the remaining values. Therefore, it makes no sense to have this at the beginning. Destructuring can also be used on objects too, and we'll take a look at this on a close look at rest in the rest of the course.
26. Unique Values With Set: Head into this lesson's folder, which is Unique values with set. Inside of the script section, we have a categories array with multiple values inside. If you look closely, we can see this value of bags has been duplicated at the beginning and the end. Arrays as you can see here will accept any values which you add to it, even if they are duplicates. But if we wanted to avoid this and just have unique values stored inside, we could instead use something called set. Even though set looks a little bit like an array, it's instead what is called a collection. Just like arrays, you can store both primitive and object types. We have two options, we could either create a new set from scratch, or if we wanted to convert this array to be a set. Just go, create a new variable and this one is going to be called unique categories. Set this equal to a new set. We've seen this new keyword in the past when creating things like new arrays and this is going to create a new empty set. We can pass in our categories, which is the array just above. Below this creates a console log. Log out the value of unique categories and also the browser will see what is output inside the console. Now I have a set with six entries and upon closer inspection, we can see the bags' value is only included once. It removed any duplicates since our original array had these bags' value in twice and seven different values. What we've done here is we've created a new set which is cloned the categories array and stripped of any duplicated values. Set also has some built-in methods which we can use to modify this collection. Then add new value. We have the add method which we can use directly on our variable. Access the unique categories, only add method and inside we can add a new value, let's go for jeans. Save and refresh. Now, our set now has seven values with the jeans pushed to the end of this collection. Duplicate categories will not be accepted even when using this method. If we go for hats, which you already have, refresh this, and we're back now to six different values because the hats has been duplicated. If we also want to remove a single value, we have access to the delete method. We change this over and then we can remove any one of our existing values. Let's go over hats, refresh. This is now reduced, our set down to be five values with the hats now been removed. This removes one single value but if we wanted to remove all of the values in our collection, we have access to the clear method. Since we are removing all the values, we don't need to pass anything inside. Refresh and this will wipe all of the contents of our set. We can also check if a particular value is included in a set by using the has method. Since this returns true or false, it also needs to be stored inside of a variable. Let's change this to be has, we can check if this has a value of shoes. If we were to just save this and refresh, we still get back the full set. But instead, if we access the return value, install this inside of a constant, let's say hasShoes, this equal to the return value and then we can log this to the console. This is true, let's change this to be something else. As expected, this is now returning false. Just like when we use arrays, we have access to a land property. Find out how many values are contained inside of the array. When using sets, we have access to something very similar, but this time it's called size. As you move this line and restore the uniqueCategories, access.size, save and refresh, and the returned value is six. Set is really useful if we don't want to have any duplicated values inside of an array. If we wanted to, we could also do this with an array and also chain on the filter method to remove any duplicates. But of course, it's much more simpler to use this set than writing all of the additional code which should be required if we were to store this inside of an array.
27. Two Dimensional Arrays: Regular arrays, as we know, store values in order from left to right, starting at index position 0. But we can also use arrays in a two-dimensional way to create a grid like structure, just like you can see here in the slide. Seems complex, right? Well, this is not as complex as it may seem. Or we really do need to create in a new array for each one of these rows. The first row is an array, the second row is an array, and so on. Then we place all of these inside of a outer array, which is like a wrapper which creates an array of arrays. Accessing these values is also pretty simple too. We just need two index numbers. First of all, we select the row and then we select the value from that particular row. Using these two numbers, we can select any of these items which we need. Taking a look at this example just here over on the right, we can see this is at index position 0 and then 1. It begins with 0 which accesses the first row or the first array and then from left to right, index position 1 is the second value across. Using the second example again, we do exactly the same, but this time we'll go down to our fourth row, which is index number 3, and then across to our last item in that row, which is index number 4. Unfortunately, JavaScript doesn't have a built-in way of creating two-dimensional arrays. Instead, this is why we need to create them as nested arrays. Let's give this a try over in our editor, head into this file which is the two-dimensional arrays or I can get this to go down in the script. Open this up, and let's create our first array called grid. This one is going to be our wrapper. We can place these on two separate lines to make this more clear. Then inside we're going to add three rows. The first row, as we've just seen, is just a simple array. Let's add some numbers, 11, 12, 13 and as with all array values, we separate them with a comma. Row 2 is a new array with 21, 22, 23 and finally our third row is going to be 31, 32, and 33. Let's log this to the console and see what we get back. Place in a grid variable, refresh and we can see we have an outer array, which then in turn contains three separate arrays and each one contains three values. We can see this more clearly if we expand our first row, our second row, and our third row. We could also format this in a table with the console.table. This makes it a little bit clearer. Let's see what's going on. We can see we have the index number, first we select the row and then we select the index position of each row. This one would be index 0 1,and just like we're seeing in the slides, we can access these with two square brackets. For this, we'll go back to a console log. I'll put the grid, open up the first set of square brackets, which is the row. For this one, let's go for our third row, which is index number 2 and then just after our second square brackets, let's go for the middle one which is 32. This is index number 1. Save and refresh. next our value of 32, which is this one just here. Creating a two-dimensional arrays is not really much harder than creating a single array. Instead, all we need to do is to think about the coordinate position that access each one of the values in our grid.
28. The Global Object & Built In Functions: Inside of these starter files, we now have this new functions section, which is number 3, and then head into the first lesson, which is the global object. Open up the Index page. Make sure this is also opened up inside of the browser. In between the script section, we have a similar example to what we've looked at in the past. We have two different arrays, we've got our bread ingredients and the brownies, and then this function just below. This function will take in the recipe and also the ingredients, and this will check if this particular ingredient is included in that recipe. It will then return a true or false value, depending on if the ingredient is included. As mentioned earlier, this is called a function declaration in a console log. Just below, we can then call this function by its name, which is checkAllergies, parse in the recipe, such as bread, and then we can check an ingredient, such as salt, save and refresh. We now get the value of true since this ingredient is included inside of this array. We know we can call this function by its name because, well, we've created it just above in the same file. Well, what about if we call this function from a different location, let's say a different JavaScript file? You think that would work? Well, let's take a look. We're going to now create a new JavaScript file inside of this lesson 1 folder. So click on this and then create a new file, and then this is going to be called the script with the.js extension to declare this is a JavaScript file. Make sure this is still inside of this folder alongside our Index page, and then close down the sidebar to give us some more space. Inside of our new script.js, we're, again, going to do a console log. We'll do exactly the same. We'll call our function, which was checkAllergies, and then parse in any two arguments. This time let's go for the brownies, and we can check if the brownies contains any sugar. As discussed earlier, we also need to link this script to our Index page since this is an external file. Therefore, we're creating our script inside of the Index page, so it's automatically recognized. But since we now have a new script file, we can create a new script tag, and then we need to place in the source, which is the location of our new file. Since this new file is alongside of our Index page, all we need to do is to add its name, which was script.js. So effectively, this is the same as just above. All we're doing here is pulling in the code from an external file, rather than adding it between these script tags. Now we have our console log still in place just here, and then we also have a console log called from this separate file. Let's go over to the browser and see which one will work. Refresh. We now see our two console logs. We see over on the right that one of them is from the Index page and one of them is from our script.js, so both of these are working, and they are both from two separate file locations. Well, this now leads us on to the question, if we go to our script file. Here we're doing a console log, and we are accessing a checkAllergies function, which doesn't exist inside of this file. Why does this work? Well, when we create a function, just like we've done here, it becomes part of what is called the global object. We've talked a lot about objects and object types, but the global object is the big one. The global object is the main object where globally available properties and functions are all accessible from. This may sound complex, but you can think of it as the main object which is created, and then we can access parts of it from anywhere in our code. JavaScript works inside the browser, and we can access this global object using the window. You may have also heard of something called Node.js, which is a way to run JavaScript on the server. Since Node.js is running on the server, rather than in the browser, it doesn't have access to this browser window. Instead, we access the global object using the global keyword instead. But you don't need to worry about this if you've not heard of Node.js. So you see this window. Let's head back over to the console into the browser. What we're going to do is to type the word window, hit ''Enter'', and then we can see all of this information, which returned back to us below. Since window is a global object, it contains all of these properties, which we can see here. Some are functions we can use. There is also properties on objects inside too. This is a list of things we have global access to. Some of these we've already seen. For example, I'm going to press "Command" and "F" to find a particular thing inside of here. If you're using Windows, this will be more than likely to be Control and F2. First of all, if we search for the console, we can see this highlighted inside of here. We can open this up. This is a console object, which we've already looked at. If we open this up and take a look just below this, we can see we have access to the log function and also the table function, which we've used in the past. This is why we have access to them in our multiple files, because these are placed on the global object. If we wanted to, we can also refer to the window object when calling these properties. For example, we could write window.console log, and this works exactly the same too , so window.console log. Save this and refresh. Our console logs will still work exactly the same. Let's remove this and, once again, we'll enter our window object inside of the console. If I expand this, we can also see our custom function here, which is checkAllergies. This is here because as soon as we created our checkAllergies function inside of our code, it was then added to this global object, and this is why we can access this inside of a different file. Also, any variables which we create using the var keyword are also placed on the global object too, but not any variables we create with the const or let keywords. But more on this one later. Of course, this is a function which we created ourselves, but JavaScript also has many functions which we first don't need to create. These are automatically built into the language. These can be referred to as built-in functions or global functions since they are available to call anywhere in our program from this global object. An example of this, if we go down to the search, is a function called parseInt. We can see this included here, and we can see by this f, that this is a function. We can use this, if we go over to the code. Just quickly before we do this, we'll remove this script.js, remove the script link, and we can also remove this file from here too. Now back to our Index page, we'll take a look at this parseInt function. The way this function works is it will take in a string and then it will convert this to be an integer, which is a whole number, so to see this go down to our console log, and we can call parseInt. This is also camel case, so this has a capital I. Open up the function brackets. Then as a string, we'll add in the number of 10. Save this, and over to the browser, refresh and we now see the number of 10. Rather than take my word for it that this is a number, rather than still a string, what we can do is we can cut this out with Command or Control-X, install this inside of a variable called Int, paste this in. Then this time we'll do a console log for the typeof our Int to see what type of data we are holding. Refresh, and we can now see that this has been converted from a string to a number. Since parseInt converts a string to be an integer, which is a whole number, it won't include any numbers after a decimal place. So if this was, say, 10.09 and I remove the typeof, this will then be converted to a rounded or a whole number. We can also flip this and do the opposite with a string function, so this time we'll call this a number, and instead of having a string just like this, we'll place in a number, and we'll convert the number this time to be a string using the string function. We'll, again, log our variable of number. We'll see the value inside the console or five. But once again, we can do a typeof check to check that this has been converted to a string. There we go. As you can see, JavaScript is really flexible. We can either create our own functions or access some built-in mounts, which is provided with the language. We can then access these built-in mounts on the global object. As we've seen, when we accessed the window object before, there is lots more other functions available too. I'm not going to go through all of them since there is quite a lot and there are also some pretty specialist ones too. But we will use many more of these globally available functions, properties, and objects as we move through the rest of the upcoming sections.
29. Function Expressions: We've created functions so far using a syntax called a function declaration. There's also a slightly modified way to write functions too, and these are called function expressions. Jump into the starter files for this lesson, which is inside of the function section, and then into lesson at number 2. You can see inside of here, if we go down to the script section, we have an example of a function declaration. This is the type of function we've looked at previously, and it looks just like this. We use the function keyword, we create a function name, we pass in any optional parameters inside of here, and then we'll write our code inside of the function body. The alternative, which is a function expression which we now are going to look at, also looks pretty similar. The first difference is the way we name the function. To transform this into a function expression, we can first remove the function name. I'm going to write this just below so we can see a comparison. We'll also use the function keyword, but this time we'll jump straight into the brackets or the parentheses. We'll compare this to the one above, we'll pass in the recipe and also the ingredients. Then immediately after we add our function body inside of the curly braces, let's just copy these two lines of code because they're going to be exactly the same as this example. Then since we don't have a name like we have just above, what we need to do is to assign this to a variable, create a constant or a variable, and then we can give this a name such as checkAllergies and set this equal to our function. Leave now. Our function name like this is again optional, but this is now an anonymous function because of the lack of name. What we want to do now just to avoid any confusion is to comment out this original function. We can also check if it's working by doing a console log. Just like earlier, we pass in the function name, but this time, this is the variable name. We can still use the brackets just afterwards to passing any optional arguments. The recipe, we can go for anything such as bread, pass in an ingredient check such as yeast, then over to the browser, open up the developer tools and head into the console. We see the value of true, changes to be incorrect. Now this function works completely fine. Storing this function name inside of the variable is an obvious difference between the function declaration above and this function expression. Another difference is something called hoisting. Hoisting is something which we'll cover later in more detail. But for now, you can think of this as we can call a function before we actually create it. It behaves like our function is declared at the very top of the file and it's always available to use. What we're going to do is to now cut out this console log and move this up to the top of the file, or just anywhere above the function is actually fine. What we're doing here is we're calling our function before we actually create it. JavaScript programs are read from the top to the bottom. We possibly call in a function, before we even knows the function exists. Do you think this will work? Well, let's say this and try this out inside the console. Refresh. We now see an error inside of here. We cannot access checkAllergies before its initialization. This means for a function expressions which is the new type which we've created here, we have to call them after they have been created inside the program. Effectively blow. But what about this original function declaration? Well, let's try this out. If we uncomment out the original one, comment out the expression. Now this is the same function name, so we're now calling this before it's being created. We can see what happens inside the browser. Refresh, we don't see any issues. Our function will now run perfectly fine. This is another difference between the two styles of function. This function declaration can be called anywhere inside of our program even before we've actually created it. The reason is original function declaration is available anywhere, is because it's on the global scope. Just like we looked at in the previous video, we can access this via the window. See this? What we're going to do is we want to make both of these functions now active. There's no confusion. We'll change this to be checkAllergies 2. We can comment out a console log. This doesn't run inside the browser. Now we'll have both of these functions now active. Let's head over to the console. What we're going to do inside of here, we'll refresh the cleanness and then we'll access the window objects. Remember, this will access all of the available window. But if we want to, we can also use the dot notation. Narrow this down to a particular property as well. We'll go for our first function which is checkAllergies. Hit "Enter", and here we see a reference to our checkAllergies function. However, if we do this again, access the window, and then this time we go for checkAllergies. Number 2, hit "Enter" and we now get back a result of undefined. This backs up just what we looked up before in the examples, the original function, which is check, is now available on the global object, meaning we can access this in any part of our code. However, though, checkAllergies 2, which was the second one, which is the function expression. This is not available on the global scope. This is why we have to call it after we've created the function. This can be an important consideration because we don't always want to produce a global scope, unless we need to. An example of this can be a callback function. A callback is a function plus two, another function, like we looked at earlier with our array methods. Let's take a look at another example. I'm going to comment out these two functions here. Then I'm going to create a new function. This function is just going to be called to toUpper. This is going to convert any string passed it to be uppercase. We need to pass in a string, and I'll call this value. Then this is going to return the new string. What we need to do inside of here, is to access the value. Then we can call a string method called toUpperCase. This will transform a lowercase string to be uppercase. This will be sent back from this function. Then, to check if it's working we'll do a console log, call our function, then we can pass in any string inside of here which we want to convert. Let's try this out with the string of flour. Refresh the browser and this is being transformed to be uppercase. Nothing we haven't seen before. We just created a function to transform the text. We can also see inside of the window object, that we can access our function inside of here. Since this is having access to our function, we know, just like we're seeing with this one here, that this style of function is available on the global object. This style may be perfectly fine if we wanted to use it in multiple parts of our application. We'll refer them back to something like the array methods which we mentioned before. We don't always need to make this function available globally. For example, if we call one of the arrays which we have at the top, such as breads, and then we can call map to loop through each one of these values. Then on each one of these values we can call the toUpper function. To see this, we'll pass this into our console log. Save this, and now if we refresh the browser, we see that each one of these values has been transformed to be uppercase. For an example like this one, we don't need this function to be global and we just simply want to pass it to a method such as map. This could now be a good use case to transform this function to be a function expression. To recap, a function declaration is constructed using the function keyword, a function name with optional parameters, and all of the code inside of the curly braces. The function expression which we have just looked at is stored into a variable. We can also have a optional function name too. This is the difference between these two types of functions. If this is all new to you don't worry. You don't need to remember all of these different names for now. I just want to make you aware that there is different styles of functions available, because you may need to use them one day, or you may also see them in other examples too.
30. Immediately Invoked Function Expressions: The title of the previous video was called function expressions. Now we're going to look at something called immediately invoked function expressions. It may sound complex, but it's not really too bad, it just takes our original function expression from the previous video, and we can run or invoke this function immediately. Let's take a look at how this works inside of these data files. If we take a look inside of this script section, have a simple function which creates a browser alert. I know this is a function declaration since it appears by itself, and it's not stored inside of a variable. But what we can do is we can remove the name. Again, this is optional and we will look at this very soon. Remove the name of the function. Now since this function has no names actually call it by, we can now remove the function call at the bottom. This lack of name means it's called an anonymous function. How do we call a function with no name? Well, this is where our immediately invoked function expressions comes into play. We first need to begin by wrapping our full function inside of brackets. If we cut this out, open up the brackets and then paste this in, this contains all of our function in between these brackets and then it's actually run the code. We then place in a new set of brackets just afterwards, just like we would do with a regular function call. Now if we save this and refresh the browser, we now see our alert inside of here. This means our function is running. We can see the code contained inside. This just means we've created a function and run the function code as soon as the page is loaded. If we didn't surround this function code with these original brackets just here, it would cause an error since JavaScript would think this was a regular function which would require a name. But using these surrounding brackets can also cause a problem too. If we have some code above, for example, such as a variable, this can cause an issue. Create any variable just above, I want to go for language, and set this equal to JavaScript. Notice here I'm not adding a semicolon at the end, and if we save this file, the text editor has automatically formatted these photos. We can see straight away that this is not how our code was intended. Let's go off to the browser and see what effect this has if we refresh. There we go, we'll have an error. JavaScript is not a function. Now if we go back to the text editor and examine our code more closely, this error is understandable. Where we've laid out is code is pretty similar to the function expression which looked at in the previous video, it thinks. We have a function name of JavaScript. Then immediately afterwards we have the contents inside of these brackets, just like this. Remember earlier we looked at how semicolons don't always need to be used. Well, this is one of those used cases when we do need to add them in. If we now add a semicolon after our variable name, this will now separate this from our function. We test this in the browser, refresh, and again, our function is working correctly. Alternatively, you may also see some developers add a semicolon at the beginning of the function expression. This is to avoid any problems if the line above doesn't end in a semicolon. It's also especially useful if we are importing the contents of another file. We don't always know if that code is going to end in a semicolon, or if it's going to cause an error. This is how we use them. But why do we need to use an immediately invoked function expression? Well, apart from the obvious that we may need to run some code immediately without calling the function. Since this is a function expression, it also doesn't pollute the global object. As we looked at in the previous video, when we create a function expression, it's not always available to use in any part of our file. We must first create the function before we can actually use it. Also, this is another good way to keep variables of the global object too, if we only intend on using them inside of a particular function. For example, if this variable was only ever going to be used inside of this function, we don't need to add this to the global object, just like we are doing now. We can see this if we change our alert, and we'll log the value of the language. Then outside its function, we can also log this to the console. Save and refresh. We see our alerts, and also into the console we see our console log. This variable is accessible from both inside and outside of the function. But as mentioned before, if we didn't want this variable to be available globally, we could instead move this down to our function. This means this valuable is now only accessible from inside of this function. Over to the browser, refresh, we see the alert will run and this has access to our language variable. However, though inside the console when we try to log the value of language, this is now not accessible from outside of the function. This means that any variables which you create inside of the function are also isolated too. This is really useful if we want to restrict a piece of data to only be accessible from a particular function. But even though this variable is only available inside of our function, we can still return a value. Instead of the alert, we can return back the language, and install the returned value of malfunction inside of a variable. Log this to the console, save and refresh into the console. Now we get back the returned value from our variable.
31. Anonymous Or Named?: In the past couple of videos, we've talked a bit about function expressions. When we've created these, we've left out the function name and therefore refer to these functions as anonymous. But is provided no function name the best approach to creating functions. Well, creating function without a name is certainly shorter, involves writing less code. We can also still run these functions when we want to. Why do we even add one name? Well, let's take a look in the starter files which is less than number 4 for anonymous or names inside of the functions section. If we scroll down to the script section, we have two different arrays. We also have a example of a named function which is a regular function declaration which we've looked at. This involves creating a function, then we call this function whenever we want by this name. Then blow an anonymous example, and this example is referred to as anonymous. Since we don't pass the function and name directly. Instead, we created without name just like this, and then we store it inside of a variable. We also have some examples, blow this we'll come back to this later on. But what we are going to do is open up this file inside of the console, right-click, Inspect and then into the Console tab. When we have access to a function, functions have a property which is called name, and this is a read-only property. We can use this by first all accessing of function name which is number of ingredients. Then we can access the name. Hit Enter it is pretty simple and unsurprisingly, we ask for the name and we get the function name back. But what about instead, if we remove all this and we call our second function which was checked outages. As we know, this isn't directly a function name because we haven't passed it inside of here. But all we're doing here is storing this inside of a variable. What do you think we'll get back? Well, let's try this, bring this over. Then also called the name property. We can also see for this example, we get back the name of check Allergies. This may go against what you would expect because this doesn't have function name. The reason this happens is because of something called inferred function name. Since the function is stored inside of this variable, JavaScript has basically guessed that this is a name which you want to use for our function. As we start to understand functions and the way we can refer to them can take on many forms. This inferred name is not always reliable in some situations. There is certain times or edge cases when the name is not inferred. Other reasons you may want to add a specific name to the function is for debugging areas inside the console the series. But let's create a error inside of this function. Create an error here with includes and then just blow this, create a console log which has gone to log the value of check allergies. Then we also need to pass in the recipe and the ingredients. Just like the earlier examples, this is going to refer to our two arrays at the top. So we can access any of these. If we now say this and see what happens over in the console, we can see straight whether the Chrome Developer Tools has detected an error and take notes directly into the Sources tab. This has a lot of information and we can open this up to expand this. It points to lots of different parts of our code. But one of the things to watch out for is something called this call stack. This call stack is a way for the browser which is running the JavaScript to keep track of the functions which had been called and also they order to. It's pointing here to the check allergies function allows know exactly where the issue lies. But when we think about it in a slightly different way, check allergies which we have here, was intended to store the return value of this billion. Check allergies was never intended on being a function name. It was only ever intended on being available which holds a true or false value. This may start to confuse things especially in a bigger project. What we can do instead, we can create this constant to be a more descriptive name. We'll say includes bad ingredients. Then this is always going to be the true or false value and instead, we can pass in a function name just as normal. This splits up our two sections. We now have a function reference which will always point to all of this code just here. Then we have a true or false value which was originally intended as our variable. Now we've changed this variable name. We also need to copy this and change the name inside of our console Log. If we save this, and then refresh, again we've taken directly to the Sources tab because we still have this error. But now, if we take a look at the call stack, check Allergies now points to the function name rather than the variable. This is not any hard and fast rule. We don't have to add in a function name like this. If you may want to do this if you want some clear separation between the function reference and our variable name. Let's now scroll down to our second example inside of the comments. If we uncomment out all this section, this is the same example we used in the previous video to look at array methods. We have all blogposts, which is re-contained objects. Then below this we call it two separate methods. We have the map function, which is going to loop over all of the posts, transform the title to be uppercase, and then return the new value, chain onto the end defined index function, which is going to return an index number if a match for this uppercase title is found. There's quite a bit going on inside here. This section contains two anonymous functions. If there was an error inside of here, debugging may start, become a little bit difficult, especially if this section was even longer. Just before we check this out, I'm going to comment out the console log from above and also remove the error. This, we now have our single console log, which is get index, refresh. Just like with all were taken directly to the Sources tab because we have an issue. We can see it down in the call stack that the function name is anonymous. This is where the issue lies. Since both of these two function names are anonymous, we don't know exactly which one of these functions would be causing the issue. Of course if we look around all of the rest of the sections, we can get some additional clues to where the error lies with the pointers and not always obvious. It would be nice to immediately see which function is causing the issue. The issue lies here in the first function inside of the map. The problem is to uppercase needs to be a capital U. If you point exactly to this function inside of the developer tools. We can add a name to this function. First, we call this one transform to upper. Then a descriptive name for this anonymous function. Let's go for get Index from title. Now if we go back over to the developer tools again we see an error. But now straight away we can see we have a clue to which function is causing the issue. We can narrow this down to this section here. It's like RNA label to our function to help identify it. Lets fix this, changes there capital U. If you don't see any errors inside of the console and instead we see this returned value of two, which is the index number which matches this section just here. As with a lot of things, the choice of naming functions are leaving them as anonymous is completely your choice. Often it's not an issue to leave the name off and slightly reduce the amount of code which we write. But if you prefer to be more descriptive and want some extra pointers when deep again, you can add them to your functions to be more descriptive.
32. A Function Or a Method?: JavaScript has a lot of terminology which can take a while to get used to, such as the function expressions and function declarations, which we've looked at during this section. Something else we use quite a lot is the words of function and also method. They can appear to be the same and they pretty much are, but there is a key difference. Over the starter files, which is a function or a method. Jump down into the Script section. This is all familiar from the previous sections, we have our two arrays. We now have our function to check if an ingredient is included in any of these. Well, let's also create a new function and this one is just going to check how many ingredients a particular recipe has. We'll also need to pass in a recipe. Then inside, all we're going to do is to return a value which is the length of the recipe. We've looked at this length property previously, this will tell us how many items are stored inside of an array. We can test this blow with a console log, passing the number of ingredients, and then any one of our arrays. Save this and open a pre-console. We can now see that the bread array has four different values. But let's say we were creating even more functions related to the same array. You may have lots more functions to do lots of different checks on our recipes. If all of these functions were related, it would be good to group all of these functions together. How do you think we group together lots of related values? Well, for this, we use an object. We've looked at objects so far. An object we've looked at has been something like this, we've had a user, moves that this equal to our curly braces. But I'm passing the properties which are a combination of keys and values and each one is separated by a comma. Object are not just used for storing simple primitive values like our strings here. They can also store over object types too. We can place in over objects, we can place in arrays and also our functions. Since these are all related to our recipes, we're going to name this object, "checkrecipes". Since we currently have two functions, we're going to place in it two properties. The first one is going to be check allergies, and the second one is going to be number of ingredients. We also need to pass in a value to these two properties. Of this, we can cut and paste our functions as well, check allergies as in the just after the first line. As with all other properties, we then need to separate these with a comma. The same for our second function, which is number of ingredients. Put this out in places just after our name. Something else we can also do, is to transform these to be anonymous. Since we have a property name of "checkallergies" and "numberofingredients", we have a way to access these functions, so we can remove the function names on both of these. Now since these two functions are placed on an object, they're both now considered methods and now any of these methods can now be called from the object name, which is "checkrecipes". In fact, this should just be a capital R. So now, if we go down to our console log base in the object name, which is "checkRecipes". Using the dot notation, we can then call any one of these properties, so just check allergies or number of ingredients and we can also see this with the auto-complete inside of the editor. Let's go for a number of ingredients and just like above, we also need to pass in this recipe, so the brackets or the parentheses. Let's go for bread and then scroll up we'll also remove this console log. There's no issue it's just there. Save this and reload browser, and we still get back returned the value before. But this time, it's been called as our method from the object rather than the original standalone function. This is in fact how all methods work in our object types. If we take a look just above, we've created our two arrays just here, and as we already know, arrays are a special object type. Since both of these are an object, this is why we'll also have access to these array methods. If we go into the console and type brownies and then dot, just like with any other object, we can use this dot notation to access any one of the properties or the methods which are available on this object. This is where all of these come from behind the scenes, is exactly the same, our array is an object just like this. Then we access individual properties or methods which we see inside of the browser. Back to this object, even though we've had two separate functions or methods passed inside of here, it can also be mixed with any of the datatypes too. We can also mix in primitives such as the maximum number of recipes, and we can store this as a simple primitive value, and this technique is a great way to group together lots of related information and functionality. Just like with the methods, we can also access max recipes with this dot notation. Since this one doesn't relate to a function, we don't need the brackets, we'll just call it by the property name. Refresh and we now see the value of 1,000. We now know that a function placed as a property on an object is considered a method in JavaScript. Sometimes though, we need these methods to also refer to other properties on the same objects. For example, we may also have a property called "currentRecipes" and this is the total number of recipes which is currently on our site. Then we may also want a method which accesses both of these properties and checks that we have not exceeded the maximum number of recipes before a new one can be uploaded. To do this add any property, at the bottom of this object will say "recipesLeft", and as it sounds we'll calculate the number of recipes we still have left at to our site. This is relatively straightforward, all we need to do is to return the value of our max recipes. Takeaway the column recipes. Now, we can try this out over in the browser. Let's log this but this time we'll log the return value of recipes left. Save and refresh. We've taken straight to the sources tab because this will then trigger an error. We see that the maximum recipes is not defined and in the call stack, we can see this has been caused by "recipesLeft". The reason this happens, it may not be immediately obvious, but this is because to access other properties on our object, such as these two here, we also need to use this keyword so at this before each one of our property names. Now inside the browser, if we head into the console, this now all works completely fine. Obviously, you may want to know what the value of this even points to. Well, let's go over to our object and take a look into this function based on a console log and we can output the value of this, save and refresh. We can see these points to our current object and it has all of the available properties which we've just created inside of here. This keyword can be a really complex thing to understand but in this current context, this keyword will point to any one of the properties available on this current object. There will be more information on this as we progress through the course. Next, we're going to take a look at the arrow function, which we briefly looked at previously, and how it also acts differently to inside of this object.
33. Arrow Functions: In ES2015, we were given a new optional way of creating function expressions. These are called arrow functions. These were a shorter way to write function expressions. But it's not just this shorter syntax which is different, they also behave differently to regular functions too. At the top of the starter files, head into the arrow functions file and at the top here, we have a regular function expression. This is a function which is anonymous. Then we store this inside of a variable. What we're now going to do is to transform this into an arrow function. We looked at these briefly earlier and the way we need to do this is to first, remove the function key. Then after the brackets we add in our arrow, and it's consisted of the equals and the greater than symbol. Call this and run the alert when it's called by it's variable name, followed by the function brackets, save and refresh. Now function will now run correctly. At the beginning of this video, we started by saying how arrow functions were a shorter syntax, but this doesn't look much different at the moment. This is still classed as an arrow function, but we can also make it even shorter too. If we only have a single line of code nested inside, we can remove these curly braces and we can bring it onto the same line. Refresh the browser and this still works exactly the same as before. If you only have a single line like this, we also don't need to add in the return keyword as this is done automatically. If we did have multiple lines of code though, we would need to return something from the function and also wrap the multiple lines inside of the curly braces. Arrow functions can also take in parameters too just like a regular function. We can pass in as many of these as we want to separated by a comma. If we only had a single parameter just like this, we can also remove the surrounding brackets. This is how an arrow function looks. Let's refactor one of our methods from the previous video. We can remove these two lines of code, and then below this will have the same example as we've looked at in the previous video. I'll comment out all of this code to make it active. Remember, previously we created our check objects and it contained various properties, just like our primitives here. Also since we moved the standalone functions to be part of this object, these are now referred to as methods. What we're going to do inside of this object is to transform this recipesLeft method and I'll make use of an arrow function. Just like before, we can move the function keyword since this is just one single line of code. We can also remove the curly braces, bring this onto the same line, and remember that single lines are automatically returned back follows. We also need the arrow. Let's try logging to the console and see what happens. We still have the console log of recipesLeft. Refresh the browser and we get an unexpected token, which is the semicolon. This is just this one here. If we remove this and refresh, we see the value of not a number. Obviously, this method is not working as it did before. This is because of the way arrow functions handle the this keyword. More precisely, arrow functions don't have their own this, and this is why we don't see the number inside of the console. See this we can also place in a console log inside of this method. So move these onto a separate lines, log the value of this. Then since we are now on multiple lines, we also need to wrap these in the curly braces, making sure that this comma is also removed. Let's try this. Refresh and now we see this points to the window object, unlike in the last video, where the value of this referred to the parent object which was checkRecipes. Arrow functions don't have their own this. This means that this refers to the global object, so it is often advised to not use an arrow function when creating methods like this because it cannot access over properties on this object. Although like when we use the arrow functions in a previous video, that can be useful to combine weird things like array methods because of the shorter syntax. If we take a look at an example of this, down at the very bottom. If we access the brownies or map, and then with the regular function syntax, it would look just like this. We pass in a function. This function would then take in each ingredients and then inside we could return anything which you want to. Let's go for our ingredients, which has been transformed to uppercase. This is a way of writing this with a regular function and in fact, it's still my preferred way of doing things. However, though the arrow function equivalents would go like this, brownies.map, and then instead of typing the function keyword, we can pass in an arrow function, which is the brackets, the arrow syntax. We don't need the return keyword since this is all on its own line. We can then just copy this, paste this in, and both of these are equivalent. We can't see why the shorter version is often used with things like array methods and also some people just right arrow functions by default. Sometimes because it's just a newer syntax. This can be fine if this is the syntax which you'd prefer and they do have some benefits as we've just seen with the shorter form. But remember, just because arrow functions are a newer way of doing things, it doesn't mean we should always use them exclusively. You will notice that they are also anonymous. Which means they don't have a unique identifier over them. May be available which we assigned to them. This can make debugging a little bit trickier too. Also remember that we have the difference between the way it handles the this keyword from the regular function declaration.
34. Default Parameter Values & Using Rest: This video is going to be focusing on function parameters and a few useful tricks when using them, which were made available with the introduction of ES 2015. Remember a parameter is a placeholder for the value we are going to be passing into a function, and you can think of this like a variable. First, we want to take a look at default parameter values, and to see this will create a new function which is going to take in a currency amount, a currency symbol, and then return a new string to display the price back to the user. Into this lesson's folder, which is default parameter values, and using Rest, we have an empty script tag down at the bottom, where we can create our function, which I'm going to call format money. This is going to take the end, of the amount which we need to format and also the currency to the function body. This is simply going to return a new string. Since we need to access both of these variables, we can place this inside of the backticks and use the $ symbol and the curly braces to insert a variable. First, the currency and the amount. The string which will be returned will look something just like this. All function name just below the name then it's passing the amount and also the currency. Let's go for 100 and the currency symbol as a string and store this inside of a variable. Like this to the console. Save this and we would expect back the value of 100 with the $ symbol just in front. We could also go one further too by changing the price to be two decimal places. We can do this using a JavaScript Number method called toFixed. Just after the amount we can pass in it toFixed and then set this to be two decimal places. There we go. What about if we had a site which only had one single currency? Well, for this, rather than passing in the second value every time, we could instead pass in a default parameter so up to our parameters, we can set this equal to our default string. Now we could either lay this off or instead, we want to override this. We could change this to be a different value, so this would override the default just like that. Also if we remove this, it would then revert back to our default $ symbol. This also works exactly the same if you wanted to store our default inside of a variable. Create a constant at the top called currency symbol and set this equal to our default. Variables also work inside of here we could set this equal to our variable name of currency symbol. Save this. Refresh. We now see the default of our $ symbol, even though we've not passed this in as an argument. So this kind of approach would be really useful if you wanted to keep a single central value which we wanted to use in different areas of our site. Next, we're going to take a look at how we can use the Rest operator. The Rest operator gives us an easy way to deal with a function which is going to have lots of different parameters. Here, we only have two, so this is not too hard to manage. But imagine if we had a lot more parameters which we wanted to include, with this we can write a new function, so let's comment out all this existing code and then we'll create a new function down at the bottom, which is going to be responsible for calculating an average age, so the function keyword, the name of average age, and below call it by the function name. We could also pass in lots of different numbers, which is the ages of all of our different users. Passing lots of different arguments. With all of these arguments being passed to the function, it wouldn't make sense to create a new parameter name for each one of these values. Instead, it will be useful if we could just pass in one single value and to handle this, we have the rest operator. So what we can do is use the three dots. Personnel parameter name and this is basically like a variable with the three dots placed before we can now access our ages inside of the function. Let's try this inside of a console log, refresh, and we now have six values stored inside of an array. This is really useful if we don't want to create a new variable name for each one of the values. Or if we didn't know exactly how many values was going to be passed to this function. Going back to the purpose of our function, which is the average age, we can now use this ages array to calculate this by using a method which you've looked at in the past called reduced. So remove this console log, access our age is variable, and then call the reduced method. Remember in the previous video which we looked at this, this takes in two different things. We want to create this as an arrow function. This will take in the total and also the current value that's our arrow, which is going to add together both of these values so the current will say total. Then we can solve this inside of a variable. This is going to loop through each one of the values inside of ages which is these ones just here. It's going to select the current value and then add this to the previous total. Make sure that all of these values are combined into one single number. Now what we need to do is to take this total and divide it by the number of entries inside of the array, will return this back from the function. The total of all the numbers added together divided by the length of the array. How do we get the length of the array? Well, we do this with the length property, which in our case is the value of six. Since this function is returning a value, we can also store this inside of a variable. Let's call this the average. Set this equal to the return value, and then display this inside the logs. Save this, refresh, and the average of all of our numbers is 43. This is how the Rest parameter works by selecting all of the values which is passed to it. But if we didn't want to capture all of these values, let's say for example if we wanted a separate variable for the very first value, we could insert the first parameter just like this and then the value of ages would be all of the remaining values from 45 to the end of the array. You could go even further and store multiple items, such as the second value, but always remember the rest parameter must be last, since as it sounds, it collects all of the rest of the remaining values. These three dots may also look familiar from earlier when we looked at the structure in arrays. This example is what we looked at earlier and this is an example of using spread. Rest and spread are very similar and both have three dots. Spread means we can take something which we can loop over, such as this array of posts, and we can pull out values and spread them into something else. For example, they can be spreading into a new object or array to copy over the values, this makes it useful for things like duplicating arrays or just generally grabbing in values and copying them over. Then we have the Rest parameter which we've just looked at and this makes bundling all of the argument values together into one single array value really easy. Then below this will have the default parameters and this default is created by setting a value such as a number or a string. Remember it all, this is just the default value and if we provide a value when we call a function, this will be then used instead.
35. What Is The DOM?: Just before we jump into some code, it's really important to know about something which we're going to look at in this section called the DOM. The DOM stands for, Document Object Model and it's a programming interface for our HTML pages. This may sound complex but it's not too confusing once know know the basics. Taking a very basic and script buck version of a web document, this is the basic element we have. All documents need to have this HTML wrapper and then we have the head and body section one level inside. To visualize how this would look in the DOM tree, this example would be something like this. Over on the right, the document is the top of the tree. This is our web document or our web page. Then below it, we have the root HTML wrapper. Below this, we have the head and the body sections which are both alongside each other. This is actually how we see when we see them in our text editor. Our DOM is constructed of all of these objects which mirror our HTML page. One step further, add in a title element to the head section which we always do and also a h1 element to the body. These all nested are structured exactly the same as our web page as we see inside of our text editor. All of these objects in the DOM are clusters nodes. The h1 for example, is an element node, an envelope of the heading, and also the title. We have a text node, which is the text content of each element. Basically, the text which goes between the opening and the closing tags. Elements can also have attributes too, such as an h-graph, a class, and an ID. These are also nodes too. These ones are called attribute nodes, just like we see here down at the bottom. We have element nodes, we have text nodes, and we also have attribute nodes too. We've came this file without knowing anything about the DOM. This is all happening in the background. Why should we even care? Well, the DOM provides a way for JavaScript or other languages to connect to our HTML. It gives us access to the document tree so we can make changes to it if we want to. This means we can use JavaScript to create new HTML elements. We can remove them, we can change styling, we can add or remove attributes and basically do anything we want with our HTML elements. Although we write in JavaScript code, it uses the DOM to access these HTML elements. They work together to allow us to do this. We've already briefly looked at working with the DOM in our earlier videos when we looked at some examples such as changing the text inside the browser. We'll have a lot more to cover in this section too. Let's take a look at some code in the next video.
36. Selecting Elements: Hey, welcome back to this new section. For this section head into Section Number 4 which is events and the DOM. This is the first video which is Number 1, Selecting Elements. I'll grab the path to this file and open this up inside of the browser. We can see inside the browser we already have some HTML code which is displaying a table, and this is going to give us a reference for some different ways we can use to select any one of our HTML elements. Obviously, when we need to manipulate any of these HTML using JavaScript, we have multiple ways we can use to select these. First of all, as we looked at in the past, we can select an element by the particular Id. This was an Id attribute, and we can select it by a particular name. We can select by a tag which is the element's name such as Id, a p element or the image, we can select by a class name and we can also select with a CSS selector too. There's two different ways we can use for this. We can select the very first matching selector or we can have return back to us all available matches. Over on the right, we have a set of methods which is going to allow us to select any of our elements with these methods. We've used getElementById briefly in the past. We can select our elements by tag name and also by the class name too. Notice that the s is highlighted in both of these two methods since it returns back multiple elements. We have querySelector which is going to select the very first match, and querySelectorAll which will return all matches. Both of these methods, just like this, works exactly the same as it does with our CSS. For example, we could select it by an element name, we could use the.select a class, or also a # too if we want to select an element by a particular Id with this group of methods which we're going to focus on in this video and in the upcoming section too. Remember that a method is just like a function, but it lives on an object. Also, the document is an objective too. Let's go over to our index.html, scroll down to the script section. We'll create a console.log and I'll put the contents of the document. This is an object. We're going to open up the developer tools into the console and refresh. Just make this a little bit bigger. If we open this up, and then inside the console we can see all of the content which you have inside of our index page. As covered in the last video, the document is the top-level of the DOM tree. It covers everything inside of this HTML page. These documents been an object also has lots of properties and methods available too. We can see this if we type in the document and then use dot to get the auto complete. This goes back to earlier when we looked at object types such as arrays and we noticed that they had a lot of built-in properties and methods which we could access. We can check if this document has any images. In our case, we don't have an so this returns back an empty HTML Collection. We could also check some different things such as the URL. Hit enter. This will return back to the file path for these particular document. We can see mine is on the desktop and inside the modern JavaScript starter files, as well as the URL. Let's type in the head and this returns the head section which is all the data inside of this head section. Also the same for our body and as our body elements with all of the contents inside. The reason we can access this document and all of the content is because it's available globally on the window object. We could also access this via the window object too. Down to our console log type in the window, refresh, and inside the console, if we open this up, this window object has the document property just here where we can access all of the same properties and methods which we've just looked at. Well, what we're interested in at the moment is the methods available to select the required elements which is these ones over on the right. First, to do this, we'll create a new element which you want to select. We can place this anywhere in our code. I'm going to add a p element just above the section and then grab this by the Id of text. Then inside of the script section just below, we can grab this by first selecting the documents, and then we can access the method available on the document which is getElementById. We know how to do this, we pass in as a string the Id which is text, store this inside of a variable let's call this text. Now we can log this to the console. Refresh. There we go and this is now selected our p element which we've just created. This is pretty simple. This is just how we select one particular element. But what if we had two p elements? Well, to be able to grab both of these p elements, we have two options. On the second row, we have access to the tag name. As you can see with the s this is capable of holding multiple elements. This will be fine to use. Also the same for the very last row, we could also use querySelectorAll where we could select multiple matches by the p element, and of course, if we had a class attached to both of these elements, we could also use getElementsByClassName too. But we don't have a class attached to these at the moment, so we're going to make use of the tag name. Let's go down and instead of getElementById, and just to be getElementsByTagName, and just like we would do with CSS, we can select these by the tag name of p. Save and refresh. We now get back return to as an HTML collection containing two different elements. A HTML collection is a generic array-like collection of elements and this is how our return p elements are stored. Like with arrays, we can also access specific values by the index position. If we were to add the square brackets and then select index number 1, this would select our second p element, which is this one just here. We could change this to be index zero, and this would select our very first one. But note since this is a HTMLCollection rather than an array, we don't have access to any of the array methods. Next, we can select elements by the class name and for this, we also need to add a class to our elements. Let's go for our second element, we can add a class. I want to go for text-small. You want to follow a table which you already have. This one should be pretty straightforward. If I want to select an element by the class name, we have getElementsByClassName. Change is over, passing the class name which was text-small. Remove the index number and refresh. Just like before, we also have returned back to was HTMLCollection because this could also contain multiple elements which all have the same class. The last thing which we are going to look at work in a similar way. All of these makes use of a CSS selector to either select the very first element which will come across or a collection of all of the matches. Let's start with our first match which is querySelector. Again, this is also available directly on the documents. What we could do, just like CSS, we could make use of the class name with the dot. This will return back the p elements we just selected. We could also grab an Id or also the tag name just like this. Remember that querySelector will select the very first occurrence or the very first match. Refresh and there's our very first element just there. But if we wanted to grab all of these available matches, we need changes to be querySelectorAll. Save and refresh. We're now getting back a node list containing now two p elements. Unlike before where we had to return back to the HTML Collection, this time we get back a node list and there is some differences between a node list and a HTML Collection. I'm going to take a look at these in a later video. Also, remember that here on its own, when writing our JavaScript inside of here, the JavaScript doesn't know anything about our HTML model. It's accessing the document and then all of the elements which we need through the DOM interface. As a recap, we can select an element in many ways, such as this p element, which we can access by the Id, the tag name which is the element's name of p, or even the class name which is text green and the last two are selected in an element in the same way as we would expect inside of a style sheet. The difference is if we want to grab the first match with querySelector or all matches using querySelectorAll. Now we know how to select any HTML element which you want. We're now going to move on to the next video where we'll discover how to make some changes to any existing elements.
37. Changing Values & Attributes: We know how to select an element. How do we actually go about changing them? Well, that's we're going to take a look at in this video. We're going to show you how we can change the values of elements and also how we can add and remove attributes using JavaScript. For this lesson, this is changing values and attributes, so open this up, and also inside of the browser. To begin, we've got this heading at the top, the title on the links, and also the image placed just below. What we're going to do for this is first of all, look at how we can change the text contents, and we've already looked at this early on in the course, so they should throw up no surprises. What we're going to do is to change the title from meaty burgers to be no meat burgers, and we could do this down at the bottom. First of all, the word which you want to change or replace is going to be meaty. Therefore, we'll cut this out, and then place it inside of a span element, we could add an ID or any way of grabbing this elements which you want to. For this example I'm going to go for the class called change title, and then we can change the text content inside of the span. To do this, we're going to need to make use of JavaScript. Create a script section down at the bottom, and we can select just this section, install this inside of a constant called el. This is usually for elements, and then what we need to do is to grab the element by the class name using the querySelector. Since is easy class, we use the dot and the class name was changed title. As we know, this is our way of grabbing this element. To begin making changes to these elements, like with most things in JavaScript, it all begins with a parent object where we're going to inherit certain things from. If we do a console.log, just below and log the value of our elements. Let's save this and open this up inside the console. Refresh, now we can see we have access to the span which you just selected. But even though we know this is a span elements, if we do the typeof and then it refreshed this once again, we can see this is actually an object. It returns back an object which is an element object, and like any other object which we looked up previously, this means we can also access certain methods and properties available on this object. There are many ways to choose from, but this video is going to uncover some common ones. To begin, we can get the text content of an element by using a method called innerText. If we do a console.log for the value of our elements.innerText. Make sure this is camelCase with the capital T. Now into the console, this is the value of meaty. This is the innerText content from between the span tags, and it is this text which we see here. InnerText not only grabs the current x content, but we can also replace it too, and the way to do this is to access our elements by using el. Set the inner text, and we can assign this to be a new value such as no meat and closed on the console and reload the page. Our changes now take effect. But what about if we also wanted to add some markup to this text? For example, if we wanted to add the mark elements around this text, we could add the opening and the closing tag. Now if we save this and refresh, it probably no surprise that we see these outputs as a string. Rather than otputting this as a string, the way we can format these properly is to instead of inserting innertText, we can change this to be innerHTML and now the mark elements will take effect rather than outputting this as a string. One thing to watch out for though when inserting HTML like this, there is always a small chance that a user could input some dangerous code onto your site. It's really important to not set the innerHTML for any content which the user can provide, such as on a form or text input. Hello HTML does have some defenses against this. To be on the safe side, it is recommended to avoid inner HTML if you were just inserting a plain text just like we were before. We'll revert it back to be in a text and along with the actual textContent, we can also get attributes such as the ID, such as the class, the href, and also the source. We could also set new ones too. To see this jump into the console, and then we can select our elements , which is lower case. We know for these elements we have the class of change title, and if we wanted to select this using JavaScript, we can use getAttributes. Inside of the brackets. We can pass in a string with the name of the attributes which you want to select. If we go for the class, we can see this returned back just below, and also if we search for some fan, such as the ID, we don't currently have an ID on this element. This therefore, would return the value of null. We could also use this over in our code editor, and we could store the values inside of variables. We could also set a new ID if we wanted to. Crop the elements and then we can directly set the ID for this property and set this to be a new string such as new, say this, and open up the console. Refresh, and now if we go into the Elements tab, into the body section, the header, open up the site title and we can see alongside of a class, we also have this new ID. If we did already have an ID in place for these particular elements, it would override the original value. We also have available various methods which will work with attributes too. We have getAttributes, we have setAttributes and also removeAttribute too. Inside the console, let's take a look at these. I go over to the console, we can also use the getAttribute method which we looked at before and we can pass in the ID to get the new value which we just added. This is the return value of new, and we can also store this inside of variables in our code, as well as getting these values as just mentioned, we can also set new attributes too. Open the editor, let's add a new class which is going to change the color of our title. If we scroll up to the CSS, we can see just here we already have in place a green class, which is going to set this text color just here. We can add the green class to our elements. Let's do this just below our ID. We do this with el.setAttributes. But we need to pass it two separate values. The first one is the name of the attributes. We're going to add a class, separated by a comma. The second value is the className which is green. Now if we save this and head over to the browser, refresh the green class has now applied. Also if you go into the elements and then into our section, so this is the body, the header and the title. The span element now has this class of green. If you look closely, we can see that this is the only class which span now has. Even though early we added this class of change-title, this happens because when we use set attributes, not only do we add a new class but we also replace the existing one too. If we did want to include this as an additional class rather than replace, there's another way to do this and we'll take a look at this in just a moment. But first, let's take a look at how we can remove an attribute with the remove attribute method. All we need to do inside of here is to pass in the attribute name which we want to remove. Let's go for the ID. Refresh the browser and this ID has now been removed from our span. Working with dynamic attributes like this is really useful for updating things like our image. We could select this image element just here and if we wanted to, we could dynamically change the image source. First of all, if we remove the image source and then we can dynamically add this back in into our script. Select the image, install this inside of a variable. We'll use the querySelector, pass in the image elements then on the image element, we can use the set attribute method. This is going to set the image source. Just like above here, we are passing it two values. The first one is the attribute name of source and then separated by a comma, we'll pass in the value which is our image name of burger.jpeg. We can duplicate this and place in the old text which is burger image over to the browser and now our image is back in place but this time we've started using JavaScript. Personally, I've used things like this in the past to create games which will then show up with random images and also to add or remove classes to change the look of certain things too, such as the end of a game, we may want to add a new class to show or hide some elements, such as a score section. We could also set the text of green for the win or use red text for a defeat. Go back to the problem of multiple classes which we had before. First, what we're going to do is to add multiple classes to our title. We'll do this inside of the span section, just have to change title at the class of blue and also red. Then we can also comment out this line just here, so it doesn't override these three classes. These three classes can now be retrieved in multiple ways. First, we have something called className. If we go into the console, we can see this by accessing our elements and then selecting className. It's enter, you'll see the return value of green, so this just needs to be refreshed. We'll try this once more. Now we get back the three classes of change-title, blue and red. If you take a closer look at the return value here, this is contained inside of the quotations. We know that the className will return back a string. As well as a string will also have something called classList. The classList will return back if we open this up an array-like collection of values. We have index Number 0, 1, and 2. We can also select these individually inside of these square brackets. If we wanted to select blue which is Number 1, we can select Number 2 which is red and 0 for change-title. This is how we can retrieve our classList but what about the problem which we had before which was to add multiple classes. Well, the way we can do this is also to access the classList which will give us access to an add and also a remove method. To do this just below our comments, so rather than setting the attribute just like this which will only override the existing value instead we can access our elements, use a classList which then gives us access to a method called add. We can add multiple classes separated by a comma. Save this and refresh. Now, the green class has now been applied. Once again, if we check our classList, we can see the value of green and cyan has been added to the end of these classes. The remove method works just the same as well. We access the classList or remove. This time as a string, we can pass in any one of our classes which we want to remove. Let's go for blue, Save and Refresh. Now if we access our element or classList once again, the value of blue has now been removed from this element. If we wanted to go even further and rather than adding individual values like this, we could also set a variable containing our classNames. Let's remove the value of green and cyan and then just above, create a constant called classes and set these up as an array. First of all, green. We'll keep this the same as before by adding cyan and then we can use the spread operator which is the three dots to pull out all the values from the classes array and place this directly inside of the add method. Save, Refresh, access our classList. This still also works just like before. The recap, we can select any elements and set the inner text value with the inner text method. We also have inner HTML to add the HTML content inside of an element. We also have the id property which can be used to update or to set a new ID. Also, we have full control of our attributes. We can get any existing attribute such as a class or the source. We can set new ones and we can also remove any attributes too. Last, of all, we looked at classes and the different ways we can use to add, update and also to remove them. We have the className which we can use to retrieve back the values of our classes as a string. We can also use this to add a new class too. We also have classList which is an array-like collection of all of our classNames. This also exposes some methods which we can use to add and also remove some classes. Finally, we also looked at a different way of including classes which was to create an array. Then we can make use of these classes by using the spread operator. Next, we'll also look at how we can directly modify CSS properties using JavaScript.
38. Changing An Elements CSS: We've covered how to change an element content such as the inner text, and also how to add, modify, and remove attributes. Something else we can also do is to modify the style of any one of these elements. In the starter project which is Changing An Elements CSS, we're going to open this up inside the browser and then jump into the console. A starter is the same simple example that we looked at in the last video. We have the heading and also the image with certainly text contents of the header, the green class, and also certainly image dynamically. To work with the styles, we can also access our elements which is this el variable. In Console, we can access el.style. You use this style property to read values as it gets a little bit confusing. We know we have this green color applied from here by adding the class, and this green class is certainly text color. We may expect this back if we select the color property, hit "Enter", and instead we get back an empty string. The reason why is because if we select the color property just like this, it only returns back any styles which we add inline in our HTML. If I hit "inline", I mean if we go to our elements, I'm going to set the inline styles just like this. For example, we can set the color to be red. Now, if we refresh this, we'll do the same by setting the color. This one returns back our red value. This will only read inline styles and will ignore any other sources such as any of the styles which are placed in the head section or any which are placed in an external style sheet too. If you did want to know the actual value from anywhere, there is a method available on the global window object called getComputedStyle. First we'll select the window object and then getComputedStyle. We want to know the style of a particular elements, so we can pass this variable in if we hit "Enter". This will give us back a returned object with all of the available styles which apply to these elements, or if we wanted to we could just get back a single value such as the color. This is not something which I personally use a lot, but it is available if needed. Back to our style property which we used before which is this one just here, we can also use this to set any styles too. As an example we'll convert some of the styles which you already have in the head section down inside of the script. Just below setAttribute select the element el.style property, and we can set the color to be equal to a new value. This will be a string, and I'm going to place in an RGB value of 40, 141, 40. Close this off. We don't have any conflicts, we'll also comment out this green class, refresh. This changes to be a green color and just to confirm, we can see here we don't have the green class applied. We can also comment this out just to make sure that this is coming from the style property which we just added. Let's go a little bit further on. If we go back to our styles at the very top, we have this header section with four different CSS properties. We set in the display type and also some flex properties alongside the pattern. We can also comment this section out and replace this with JavaScript. To do this, we first need to store a reference to our header elements just like we did with this section just here. Let's add this down at the bottom and store this inside of a constant called header, and we can select this in any way which we want. I'm going to use the querySelector as any element name of header, and then the first property which we need to select is the display type of flex. We just basically replace in all of these four values by using the star property at the bottom. Access the header, the style. Set the display type to be equal to a string of flex. Refresh the browser. We can see the flex box has taken effect but we still have some alignment issues, and this can be fixed by adding the rest of the CSS properties. The second one is header.style, and this time we need to set justify-content. If we take a look at how we did this in our CSS we use the lowercase, and this was separated by a comma. However though one of the big Gotchas with JavaScript when setting the CSS, is we also need to convert this to be camelCase. We can't use justify-content. We see straight away that the text editor has highlighted an issue, and we need to convert this to be camelCase. This means content begins with a C, and then we can set this to our string which is space-between. Next path; align-items which just like justify-content, also needs to be converted to be camelCase. This was also set to be center, so set this up and the value for this is center. Finally, you have the padding. The padding value if we take a look this was zero and some pixels. Pass this in as a string and check this out in the browser. Refresh. We can see our padding around the outside of the text, and also the alignment has been fixed with these flex properties. This way of setting the CSS has lots of good use cases. As mentioned in the last video it can be useful for showing and hiding content for change in layout, and for also changing the theme of our website. For example, we may have a bottom which add some CSS properties, a switch between light and dark mode. We could add CSS animations. If the user clicks on some of them, we could toggle different color schemes and so many more possibilities. It's also worth knowing that adding styles like this with JavaScript carries the same priority in the cascade as an inline style does. This technique will override any existing external style sheets and also any styles which you have up in the Head section. To see this we can uncomment out the green section. We can then reapply this with our JavaScript by removing the setAttribute comment. Also if we change the color to be red; so I'll have in the RGB color, place in the red value. Now what we'll have is a class of green being applied using setAttributes which is in fact red, and then we set this green color just below. Save and refresh. We still see the green text over the top, and this happens because this has been created using a JavaScript style property which carries a high weight in adding a class. We can also confirm this if we move the star property to be just with this class setting. Make sure that it's nothing to do with the order. Save and refresh, and we can still see this green color has applied. If you're wondering how to add multiple CSS properties at once, we can also set this using an object. We'll look at this in more detail in the Object section, but for now this is how we can retrieve and also set CSS style in using JavaScript. We set our style properties just like we would do in a regular style sheet, but remember when a property is multiple words such as background color and justify-content we also need to convert this to be camelCase.
39. Creating New Elements: Along with all of the modifications we've been making to existing elements, we can also create our own too. In fact, we can even create sections or a full web page with HTML content inside of JavaScript. As you can imagine, this opens up many doors. A means of a content could be more dynamic and also change even after the page has finished loading. This opens up so many possibilities and some examples could be to only show the content to the user if they are logged in. We could get all of the users previous orders and create a HTML list based of this information. The user could also add a new to-do item and the list is endless. It's only limited to our imagination or our use. Back over to the editor and head over into the creating new elements file. Down at the bottom, we have some comments inside of the script to guide us through this video. Open this up in the browser and before we go ahead and create a new element, I want to show you something called document write. As it sounds, this writes directly to the document which is our web page in the script, access the document and a method called write. Since this is a method, we open up the brackets like this, and then we can pass in a string which you want to display inside the document. I'll give this a save and reload the browser. Down at the very bottom we can see this text has been placed at the bottom, as well as inserting a plain string of texts like this. We can also inject some HTML. We can surround this inside of some element tags, such as H1, save, and over to the browser and the larger level one heading has now taken effect. This method is more useful, things like testing rather than actually adding any content or page. One of the reasons for this is because if the page has finished loading, it will override all of the existing content. We can see this better if we delay the document write to wait on the page to first finish loading. To do this, we have a method available called setTimeout. Don't worry if you've not seen this before, it's a way to run a function after a certain time delay. We'll discuss this further into the Course 2. What we're going to do is comment-out the document write, and then create a setTimeout function, which inside is going to take a function. We can write the function inside which is going to run in any style which we want to. We can use the traditional function syntax or we can pass in a arrow function. This was the brackets just like this. Great arrow, and since we're just using a single line, we don't need to add the curly braces or a return statement. Instead, we can place inside a document write just like above. Then inside of here, we can pass in a string or some HTML content. Where did my content go? Then just after the document write, then comma, and then this is the second argument for our setTimeout function. The first one is actual function which we want to run and then separate it by this comma, where we'll have the time delay in milliseconds. If we place this in as 3,000, this function will run after three seconds. Let's try this out if we now save and refresh. We don't currently see any document right at the bottom, but after three seconds, our function will run and replace all of the existing content. The fact that this can happen means it's not often a good way of adding content to our web page. For this, we'll have some more dedicated methods. Often when we create elements, this happens in multiple parts. If we were to create a text element, for example, we need to do this in multiple parts. First, we will create a P element and store this in a variable, and then create the text content node. Then we need to merge these two together. In this HTML start up file, we'll have a new HTML section just above. We have the section wrapper. Inside, we have a level three heading. We have this div with the class of contents, and then nested inside we have two more nested divs. The first one contains an image, and the second one contains a P element, and also a buy button. To get lots of practice creating our elements, we're going to recreate this full section, but this time using JavaScript. As a guide, we'll use the comments down at the bottom and we can remove these previous document write examples. Following these comments, we're going to begin by creating the section heading, which is this H3 about the top. Now, we'll keep going throughout the rest of the content. The way we can create a new element is by accessing the documents. Then using a method called create elements. For its elements is pretty simple, all we need to do is to pass in a string with the elements tag name. For example, we need to create a level 3 heading, so we do this and then we can store this inside of a variable. Mine is going to be called the section heading and set this equal to our new element. Since we now have a variable reference, we can see this if we go over to the console. Then access this by the variable name. Passing this section heading, which returns back a empty level 3 heading. As mentioned before, when we create new elements, this is often in two parts. We'll have this element which is empty, and then we also need to create the text content inside. Remember, earlier when we looked at the DOM, said that all objects inside of this tree, act as nodes. This example shows an element node in the form of our H1, then a text node with the text of hey, we have the first part which is the element node, which is our H3. Now we need to insert some text content. To do this, we have a method available called createTextNode. This method is also available on the document object. We access document dot createTextNode. Inside we pass in a string of text which you want to insert. Since we are replicating this section, we can copy the content from inside. Place this in. Store this inside of a variable, let's say the heading text. Refresh the console and we should also see this if we type in the heading text. We have our text string just here. This now means we have two separate nodes. We have our element node and also our text node. But we need a way of merging these together. The way to do this is first access the parent node, which is the section heading, grab this variable, and then since this is an element, we can access a method called appendChild. AppendChild will then take in the child which want to merge in, which is our heading text. Place this in, save, and now back over to the console, refresh. Let's test out the section heading. Now, rather than just returning a empty level 3 heading, this now also contains our string nested inside. This now completes our heading and the rest is going to be very similar. We'll go down to the image and just like before, we use document dot createElements. This time the type name is IMG. Store this inside of a constant called imageElement. As you would expect, an image is slightly different because we don't need to insert any of the text nodes inside. Instead, what we need to do is to set the attributes. We need to set both the source and also the alt text too. Just below this, access our image elements. We can call a method called setAttributes, which takes in two things. The first one is a string of the attribute name, which is source, and then the content which they will file path of burger.jpg. Duplicate this and the second one is the old text with the string, let's say burger image. We can also test this out in the browser by accessing our image elements. Refresh, access the image elements, and this looks exactly what we need for our image elements. Let's keep going. The info text, this is a P element. This section just here and while we're up here, let's copy the Lorem ipsum text. Then afterwards we'll create the button and then work outside onto our containers. We should know what to do here. We access the documents, create element. The element is the P element, and then we can store this inside of a constant called infoSectionElement. The info section element is also going to take in a text node just like the heading above. Start this inside of a constant and keep this consistent. We'll say infoSectionText equals documents.createTextNode. I see now a string which we just copied from before, which is the Lorem ipsum text. We can see straight away that we have an error just like this because we need to make sure that all of this is on the same line. We can only insert multi-line text if it were to replace these single quotations with the backticks. As before, we have our two independent elements, and then we need to call appendChild on the parent to merge these both together. The infoSectionElements.appendChild. I said I will text, which is infoSectionText. Let's try this out. We'll copy our parent container, paste this in and refresh on the textContent is now nested inside. Next, we have this button. The button will follow a very similar pattern to this info, so we'll copy all this section, paste this in, but of course, we need to change the p element to be a button. The text is going to be, buy online. We still need to append the child element into the button, but we do need to change these variable names. We'll say the buttonElement, then the buttonText. Down at the bottom, we'll select our button elements, which is the parents, then append the buttonText. Let's try this out. Refresh, refresh this and paste this in, and there's a button. This is fine, and if we go back, now up to our HTML section, we've created all of the text elements. We've got the H3, we've got our image elements, we've got our P, and also the button. The final thing we need to do is to create our wrappers. We've got a div here, we've got one here, a wrapper for both of these sections, and then finally the outer section wrapper. Like with all other elements, we're going to use createElements. I'm going to copy this line one, place this underneath the wrappers. This one is the section wrapper, which is the main element surrounding all of this content. This was a section element. Then I'm going to duplicate this three more times. The rest of these elements will all div. But they do need have some unique names, so the section one is going to be the contentWrapper. This is the content just here. Our last two is the one surrounding the image and then the one surrounding text and the button. So we'll call number 3, the imageDivWrapper. Then the last one was surrounding the text and the button, so we'll call this the textDivWrapper, which then brings us down to this section which is putting it all together. What we need to do now is to basically merge all of the elements which you created up above inside of all wrappers. The way to do this is also to make use of the appendChild method. We'll start from the inside and work our way out. First of all, we'll work with the info section and we'll insert the p elements and also the button. Down to the bottom, what we're going to do is to select our textDivWrapper all appendChild. Then we need to do this two times. The first one we need to pass in the info section elements. Info section element is the text, which we created just here. Then we also need to do this a second time, but this one is going to be for our button. The button is a variable name of buttonElement. We can duplicate this, insert our button elements. Before we go any further, we can see this inside the console if we grow up our textDivWrapper. Paste this in. As expected, this contains a div element, and then open this up, we have our p element and also the button. Next onto the imageDivWrapper. This one is just come to be one element nested inside. This is our image element. Pretty simple. Make some space. Call the appendChild method and then we can insert our image elements. Now back up to our HTML. We've got this section created here and also this one here. We need to go one more level up and access our content wrapper, and then insert both of these divWrappers. Select our content wrapper, go to appendChild, and then we need to insert both our textDivWrapper and also the image onto. Let's start with the text, and then let's duplicate this. Again, inside the content wrapper, we're going to place in our imageDivWrapper. Again, before we go any further, we'll grab our contentWrapper and make sure both of these divs are nested inside. Paste. Open this up. There's our two divs inside. The first one is the text, and the second one is the image element. Good. We're almost there, now if we go back up, let's see what we need to do next. We have the level 1 heading and also this full content div nested inside of our section. We need to grab a section and do two more appendChild methods. This section was the section wrapper called appendChild, and the first child which we need to insert is the section heading. The section heading remember was our level 3 heading, and then we need to duplicate this, and the second element is our content wrapper. This should not be all of our content now in place, and the final thing to do to finish this section off is to add our three classes. We have the content class, we have the image section, and also the info section too. These are all added to our divs. So let's go down to the bottom, and just below adding classes, the first one is the content wrapper. We can add the class with set attributes. Set attribute takes in it two things. The first one is the name of the attribute, which is class, and then the class name of content. Duplicate this two more times, and the second one was for our imageDivWrapper, this image. Let's take a look. The class name for our image was this one just here. Go back down. Image_section. The third and final one is for our text div wrapper. This textDivWrapper is the info section. Let's grab this and paste this in as our string. Good. Let's give this one final test inside the browser and we need to test out the section wrapper, which is the main wrapper surrounding all of the content. We load, add this in. Open this up and what I'm going to do is to scroll up to our HTML and make sure this is exactly the same. To begin, we have the section wrapper, which contains two elements, the level 3 heading, which is there, the div, the class of content, and then all of the additional content is nested inside. Open this up. This contains two divs. The first one has the class of info section, and the second one is the image section. We've got the info section and then the image. So we just need to make sure ours are the other way around. Al we need to do is to swap the position of these two elements to make sure that our image is just above our text. Save, and we'll try this one more time. Open up the section wrapper into the contentdiv. Good. We're now back on track. We have the image section at the top. Inside this contains the image elements. The info section down at the bottom, this contains our p elements and also our button. Good. This is all now in place, and the last thing to do in the next video, is to look at some ways we can use to add this to our main page.
40. Adding Elements To The Page: This video carries on from the last video, which is adding elements to the page. Previously, we replicated this section just here, using JavaScript by creating all of the elements one by one. We then added these elements to the various containers, and when we left off with this full section reference, your reference list was the section wrapper. This is stored inside of a variable, and we can see this if we type this inside the console. Open this up. We already have this added to the page we see, but this is inside of our HTML. What we're going to do, so we don't get confused, is to comment out this section, refresh and now we're going to dynamically insert this using JavaScript. Let's take a think about what we actually want to do here, we have this body section about the top, and the section just here which you created is a direct child of this body, as is the header and the image elements. What we need to do is to first begin by selecting the body, roll it down to our script, and we can access this with document.body. Two common methods which you have available to use is append and also prepend. Prepend will add the new content at the beginning, and append will add it to the very end. Let's begin by taking a look at prepend. This is a method, so we open up the parentheses, now we want to add our section wrapper. Let's say this and refresh the browser, and this is added to the very beginning of the body section. We can also change this to be append and this new section will be directly added to the end of the body. Something else we can also do with append, rather than adding a single element like this, is to add multiple elements to our page, and we can also add different types of content too. For example, we can add a JavaScript like string of texts, which is called a DOMString. Let's say any text inside here, and then separate it by a comma, we can add multiple pieces of information, such as multiple pieces of text or multiple elements, so let's also say we wanted to add an element, let's go for our button, also our imageElement. We can add in as many of these as we would like to. Now, save and refresh this. We can see our text, we can see our button, our image, and the final DOMString at the very end. Similar to this, we also have a method called appendChild. Let's give this a try. Now, if we save and then refresh this, we'll see an error straight away inside the console. We see this error because there is some differences between how append and appendChild handles inserting elements or nodes. AppendChild can only be used at a single node or a single text element. If I have more than one to add, the append method is the way to go. Also, as you see here, appendChild can not be used with DOMStrings, so we can not use it to insert text nodes just like we did before. Also only the appendChild method gives us back a return value, and this return value is a newly added node. With this in mind, back to our area which we were at before. The reason we have this area is for two reasons, it's because we're trying to add some DOMStrings, and also the number of elements which we are trying to add. If we reduce this down to one single element, let's go for the buttonElement, we shouldn't now see a problem. The next method to cover is insert before. Insert before gives us a bit more flexibility in where we want to place our new node, fill up and let's take our header for example. For this, imagine we wanted to place a new piece of content, which is a new element between the heading and the nav, so on this line just here, the methods we've covered so far only place elements at the beginning or at the end. As the insert before method sounds, it can be used to insert our new element before this nav, let's remove this first and then go down to our script. We first need to select the parent. In our case, the parent is the header, so document.querySelector, drop the header, and install this inside of a variable, and also since we want to insert this element before the nav, we also need a reference to this too, so it is inside of a variable called nav. Set this equal to document.querySelector, and this time we'll select our nav. Now we have access to two elements, first of all, the header is the parent element, and the nav is the element where we want to insert a new node just before, and for this, we select the parent which is the header, the method name, which is insert before, and then inside the brackets we need to pass in it two things. First, it's the element which you want to insert, and we're going to reuse any of these elements from above. Let's go for the button elements, and as the method name of insert before suggests, we then need to add the name of the element where we want to insert this button before, and in our case it's the navigation element. Let's try this out, refresh the browser. Now our button has been inserted before this navigation. This works by selecting a parent which is the header, and then adding a element inside. Another method which also works on the parent, is replaceChild. As it sounds, it will replace one of the elements inside of the parent with a new one which we specify. Now let's comment this out, and we can also use the header as our parent once more. The method name, which is replaceChild. ReplaceChild also takes in two values, the first one is the new elements which we want add in. Again, let's go for the button as an example. Then the second value is the old element, which we want to replace. I'll use the nav for this example, refresh. Now the navigation has been removed and replaced with this new buttonElement. These are some different ways of adding new nodes or elements to a web page using JavaScript, and to around this off, I'm going to remove the sections here. Comment out this example, and we're going to append the sectionWrapper back to the page, which was a new section which we created in the last video. Good. This is now on the page, and in the upcoming video, we're going to discover how we can clone elements and also how to remove them.
41. Cloning & Removing Elements: Let's kick off this video by looking at cloning elements, which we already have. The starter files in cloning and removing elements will have the same setup as the previous video. Go down to the bottom and just below this comment here, the first thing we need to do to clone an element is to actually select one. You can choose any element which you want. But for simplicity, I'm going to use one of the button elements which you already have. Let's select this. Now on this button element node, we can call a method called clone node, add the brackets and install this inside of a variable called clone button. Now, if we save this and go over to the browser into the developer tools with right-click and inspect into the console. Now using this variable name, type this inside the browser, it's uncertain. We now get returned back to visit this button element. If we look closely between this button, we don't see any of the contents such as the text inside. You can look to the button, you can see here we created the text node buy online and then we appended this to our button. By default, we use clone nodes, it will only clone the element nodes and not any of the content nested inside. If we did want the contents inside, we need to pass in a Boolean value of true. This will then copy all the contents from inside. We can see this, if we once again type our clone button, hit Enter. We now have the text content from inside. One thing to watch out for when cloning is if we are cloning an element which has a unique ID, with IDs we always want them to be unique. We don't want to have two elements with the same value. Also, here we've only created this button element. We have not yet added this to the DOM. Let's now take a look at how we can remove elements using a method called remove child comments, I'll just clone. The remove method is pretty simple. All we need to do is to select our node, scroll up. For this example, I'm going to remove the section heading, the section heading is a level 3 heading which was created here, installed inside of this variable. Select this. The first method we'll take a look at is remove, take this, and this is the heading just here. If we refresh this, the heading has now been removed. Also in addition to this remove method, we can also do this on the parent. But if we scroll up to our HTML, if we take a look for our level 3 heading, here, we can see that the parent is this section. Then scrolling down to our JavaScript where we actually create this, we have a reference to this section called section wrapper. This is the parents. Let's comment this out. Grab the section wrapper, we'll call it the remove child method. Then we place inside a reference, the child element which you want to remove. The child element which is nested inside is this section heading. Now, if we save this and refresh the browser, we can see that the section heading has still been removed. But this time just done in a slightly different way. By now you should be starting to get a good grasp of how we can use JavaScript to interact with the DOM. A lot of these processes follow a similar pattern. We normally have to select an element, we can store them in a variable. Then we call a method to perform a certain action. We can do things like remove elements. We can add one element whenever. We can create and modify elements to construct our HTML exactly how we want it to be. Coming up next, you'll have the chance to put all of this into practice with a mini challenge.
42. Mini Challenge: Welcome to this mini challenge. What I would like you to do now is to try a few things out on your own what you've learned so far. Pop into this lesson's folder, which is the Mini Challenge, and then open this up inside the browser. You'll see inside the browser that we have a new section down at the bottom. The task which I would like you to do is to recreate this section using JavaScript, just like we've previously done in the past videos. For this challenge, I've also moved over all of the existing styles into its own dedicated stylesheet. Into the index page, if we scroll down to the bottom, we can see a new section which is this one just here. This one has the class of recipes, and his is a section which I would like you to recreate using JavaScript. Once you are done, you can either remove this section from the HTML, or you can comment out for future reference. Since I've already added the styling for this project, all you need to do for this to kick in is add these classes each one of these elements. This video doesn't have any guidance, it's just a chance for you to go and put everything you've learned into practice, such as creating new elements, creating rappers, adding them together, adding class names, and if you keep them organized into different sections like we did below. If you didn't run into any trouble, as you can see, I've also kept in place the previous code from the last section, so we can use it as a reference if needed. Give it a try. Good luck and remember there is no right or wrong way of doing it. The aim is simply to get some practice on your own and to replicate this section which we already have.
43. Looping With DOM Elements: Welcome back. I hope the last mini-challenge went well for you and you you to create a new section using JavaScript. When even creating a small amount of elements, things can get pretty repetitive. Imagine creating a list with even five or 10 items, creating all the list item elements, adding the content, and then adding these elements to the parents will be a lot of lines of code. Or if we wanted to add the same class names and lots of different elements, again, this is a lot of work and repetition. To help with this, we can use a loop, although we do have much more on loops in a later section. We've already looked at some examples of looping in the array section. We've used the array methods which was mapping for each, and these will run a function for each item in the array. This was a way of reducing our repetition and this can also be applied to anything such as our DOM elements. In this video, we'll jump into the correct file and open this up inside the browser, and then scroll down to our index page to the header section, and here we have an unordered list. Since this has multiple list item elements, I'm going to use this and create them with a loop. The loops can be used to create these items. We can grab all of these items, we can make changes, we can add classes, and also remove some content too. Let's go down to our section at the very bottom. Just below the looping section, we can start by grabbing all of our list items. Nothing we haven't seen before. We'll grab the document and then we can grab these with query selector all. Remember, we use query selector all since we have multiple list items, slide by the tag name, and store this inside of a variable called list items. Check this works. Inside the browser, we can open up the console and access this variable. Type in list items and we can see returned back to us is a node list containing our two list elements. Already our two list elements have the class of another item. If you had multiple list elements, adding in this cluster, each one when we create them, will be a really repetitive process. If we were to add these manually, what we would need to do is to access our list items. Since we have multiple items, we need to select them by the index number. We can then access the class list property, the add method. Then we can have a screen which is a new class name. Now save this and refresh and once again access in the list items. This would then add the inline class to our first element. As mentioned, doing this for lots of different list items would make things really repetitive, so we're going to take a look at how we can help with this by adding a loop. JavaScript has lots of different types of loops available. For a relatively simple one we can use for this case is a loop called for of. Let's comment this line out and just below, we start this off with the for keyword. Then inside of here, we're going to type in const item of list item. What we're doing here is we're selecting our list items which contains multiple elements, and then we're going to create a new constant called item. We can access this item variable on each loop. For the first loop, the item variable will be our first element. For the second loop, item would be equivalent to our second element, and so on. Open up the curly braces and inside of here, we can add the code which you want to repeat for each one of our elements. Using the same example as above, rather than adding this to our first item just like this, instead we can access our item variable and then do exactly the same just afterwards. Copy this section and paste this in. On the first loop, this will add the inline class to the first item and then repeat for the second item, this and over to the console. This item is not defined and this just needs to be a list items. This should make the errors go away. Now once again, we can access our list items. We can see that both of these elements now have the class of inline. We've not saved a lot of code for only having two items, but you can see how useful this would be if we had maybe five, or 10, or even more elements to apply this to. An alternative type of loop, instead of using this general for of loop is to access one of JavaScript's built-in methods. Remember earlier on when we mentioned that query selector all returns back a node list. With this node list, we also have access to some methods. We can see these if we go down to the prototype and open this up, we have access to various other methods such as for each. This is going to be the loop which we're now going to look at. You do this, let's comment out our for of loop. Just below we can access our list items. The built-in method which we just mentioned was for each. Inside of here, we then pass in a function which you want to run for each one of our values. Each one of our values will be stored inside of a variable called item. Then open up the curly braces, we'll do exactly the same as above. Rub our item and then add this class name, save this, and refresh the browser, access the list items. Our class name of inline is still being applied to both of these elements. This is how we can modify, but what about creating new elements such as a full list item? Well, let's give this a go. First is, before we do this, to avoid confusion, if we scroll back up to our list items in head section, comment out both of these elements. Then we can go ahead and recreate these using JavaScript. Back down to the bottom, comment out this example. Then just below this, we can start with a regular list item as usual. To do this, access the document. Then we create our list item with the create element method. Passing in the string of LI. Since we need to also modify this, we can then store this inside of a constant called list elements. Then we need to create our text node for our first element. Again, store this inside of a constant and we'll say list text. This equal to the documents, then we use the method called create text node. The text for our first list item was our burgers. Then we can merge these by first accessing the parents, which is list elements. Then we can add our text using the upended child method. As we already see, we also need to add a class to each one of these list items. Grab the list elements. Then classList.add and the name of nav-item. This is the full first list item created. Now all we need to do is to add this to the unordered list. Let's grab this with documents.querySelector. Need to select the unordered list. Then use appendChild to then add our list element. Now give this a save and refresh the browser, and reinstated is our very first link of our burgers. As you would expect, we do need to replicate all of these lines of code for each one of our list items. We only have two links, but this still repeats a lot of code. We're going to take advantage of a loop to help us with this. But first, we actually need something to loop over. For this, let's create a constant called links. Links is going to be an array containing the text values of each one of our list items. The first one is going to be our burgers, separated by a comma. The second link was for history. Let's use the for of loop to loop over all of these links. We'll say const link of links and includes all of these five lines of codes below. Move these up inside of our for of loop. If we initially save this and go over to the browser, this same code will be repeated for each one of the values in the array. We also need to change the text content of the second link. The way to do this is rather than having a hard-coded text inside of the text node, what we're going to do is to remove this and replace this with the value of link. Value of link is going to be our burgers on the first loop, and then the text of history on the second loop. Replace this, over to the browser and refresh. There's our two links now in place. Just like before, when we only have two links, we have not saved a huge amount of code. But the benefits would get a lot bigger if we had more than two list items to create. Alternatively, arrays also have access for each for each method. We could also use this too if we wanted. All we need to do is to remove this section just here, grab our array which is stored in the links variable. Then we can make use of each method. Remember for each we'll run a function for each value in the array and then store this value inside of a variable. Remember the curly braces goes inside of here. We need to modify our existing code, move these two curly braces from the outside. Grab these five lines of code. Move these up inside of our loop. Refresh, it will get exactly the same result. The loops are a great way to perform repetitive tasks in programming. We'll also look at some more types of loops later on in the course.
44. Introduction To Events: The upcoming videos are going to be focused on events. These are a really useful part of JavaScript. Events are like things which happen in the browser, such as a button click, a mouse passing over an image, a keyboard button was pressed. When any of these events happen, it send a signal for us to do something. Often, well it's now for these events to happen and then run some code such as a function. For example, you will probably have filled out a form on a web page, such as a contact form, and then hit Submit. Well, when that form is submitted, it also finds a submit event. We could attach a click event to an element such as a button and this could run a function each time this button is clicked. Also, if you have ever visited a webpage and then tried to leave, by moving the mouse up to the Close Browser button at the top, I want to then see a promotion of a pop-up on the screen. Well, this is all JavaScript Events happening in the background. We could attach a mouseover event to an image which maybe reveals more of the image as the pointer moves over it. As you can imagine, the possibilities are huge. Remember, JavaScript interacts with our HTML through the DOM. Again, we're mixing a JavaScript here with our HTML elements. With this in mind, we need to make use of the DOMs event interface. Most HTML elements can accept an event listener being attached and there's multiple ways we can do this. We will discover some of these in the upcoming video.
45. Listening For Events: Welcome back. Now we have a basic understanding of events. We're now going to take a look at how we can listen out for them, and then react to these events. We jump into this file which is listening for events, and open this up in the browser. Since we are continuing with our No Meat Burgers project, this file is starting to get a little bit larger than we want to, so we're going to go ahead and create a few new JavaScript files, which will help us organize all of this JavaScript. First of all, since we've created quite a lot of elements inside of our Script section, what we're going to do is create a new file inside of these lessons folder. This one is going to be called the elements.js. For this, all we need to do is to grab all of the contents of our scripts. All of the elements that we've created in previous videos, put this out, leaving an empty script section, paste into our new file, and save this. Then we'll create a new file which is going to be follow upcoming section, which is the events.js. Having multiple files like this is completely fine. All we need to do is to make sure these are linked inside of our index page, so we keep the script, but we need to add the source to point to both of these files. The first one is the elements.js, duplicate this, and the second one was for our events. We can check this also works by saving and refreshing the browser, and we still see all of the elements which we created in this file. We're now going to move on to how we can work with events until it's now for an event. We first need a way to attach it to one of our elements, and there's different ways we can do this. If we go over to the Mozilla documentation. On the Mozilla documentation, in a section called GlobalEventHandlers, so you don't need to go off this page if you don't want to, but this is going to give us a list of lots of the common event handlers which we can use, and we can place these on our HTML elements. For example, we can listen out for lots of events such as onfocus, onblur, onclick, which is a really common one. We can listen out for an element to be drugged and so many more which has us cover it for lots of different events. We can wait for the page to finish loading before starting off a function, we can listen off for a mouse to pass over an element, to leave an element, and also things like on play and on pause which are related to playing audio and also video. As you can see, these event handlers have the on prefix. What we're going to do is to go over to our project and begin by listening for a click with the onclick event handler. Into the Index page, we're going to look for our image, the burger image just inside here, and then inside as an attribute, we can add onclick. Onclick is then going to run any piece of JavaScript code, so we can run a function or we can run something very simple like an alert with the text of clicks. Save this, and now this is attached to our image elements. Refresh the page, and then scroll down to the correct image which was just next to the ultimate vegan title. Click on this, and then this is our alert up at the top. If we try to click on different images, this doesn't work because this is only applied to one single element. If we go a little bit further than this, we can also go over to our events.js file, and add a function which is going to run when this element has been clicked. We just as before create a function, and we'll say, "changeImage." Now and I will check this works with an alert. We'll say "Clicked." Save this file and back to our Index page rather than running this alert inside of here. We can remove this and pass in our function name which was "ChangeImage." Let's save this back to the browser. We can try all of these images and then the final one figures our function inside of the separate file. This way of adding an event handler as an attribute is referred to as an inline event handler. This works completely fine, but it can be considered a bad practice. This is because it mixes up our HTML and our JavaScript code. What we can do instead is to remove this, and leave our HTML intact, and then we can listen out for this inside of our events file. What I'm going to do is to create a reference to this element, where document.querySelector, and then we can select any one of our elements. For this, I'm going to grab our header image, which is up at the top. Since we have multiple images, we also need a unique identifier, so we'll place in an ID of headerImage, and then we can select this inside of our events. With this being an ID, we also need to place in the hush plus in our headerImage, and then store this inside of a variable. We're grabbing our images here, we have a function to run, so now we need a way of linking these together. Well, the way we can do this is to access our element, which is the headerImage, and then we can directly access onclick and set this equal to our both function. This is changeImage. Let's get a strike, reload the browser, click on our main image, and this runs our function. We don't just want to do an alert, though in this case, we want to be able to do something to the image. We can use any of the techniques learned so far, such as adding classes or even CSS. Instead of the alert, we'll grab our headerImage, set the style, and then set the width property which is equal to a string of 50 percent. We'll try this again. This exact same technique works exactly the same with all of the different event handlers which we just looked up before. For example, if we wanted to run this particular function when the mouse passes over this image, all we need to do is to change onclicked to be any different value, such as onmouseover, refresh, and as soon as this mouse passes over the image, this code will now run. This setup is a little bit better because all of our JavaScript is now contained in its own separate file outside of the HTML. But one of the disadvantage to this approach is, if we wanted to trigger multiple functions. Let's say we quickly copy this function and pasted a new one called hi, we can add a quick alert inside of here. Then if we also duplicate this line of code here, we'll also run our second function which is hi. Let's give this a save and see what happens. Refresh, move the mouseover, we see our alert, but we don't see the image size changing. When we set up multiple functions which respond to the same event, it will override the previous one, meaning only the last function will be run. We're seeing this in action because all we're seeing inside the browser was our alert. Another way of approaching this is to use a method called add event listener. This approach will replace both of these lines of code just here. We still need to access our elements, which is the header image, but this time we pass it in a method called addEventListener. Inside of here, the first thing we pass in is a name of the event which you want to listen out for. Let's go for a click event. All of these events are exactly the same as before, but we just don't use the on prefix. Separated by comma, we can even write in a function just like this, or instead, we can pass a reference to one of the functions which we already have. Let's go for a changeImage, and we could try this one out in the browser. Click the image, and this one now works. One of the advantages of using this addEventListener method, is it also allows multiple functions too. If we were to duplicate this line, unlike when we added the onclick event handler before or the onmouseover, we can pass in a second function and both of these functions will now run in the browser, like this, there's our alert, and then the image will be shrunk to 50 percent. This is really useful if we have multiple functions which we want to run, but I'm just going to remove this hi example and leave a neat change image. AddEventListener also has some other benefits too. Another one is, we can also remove event listener code when it's no longer needed. It also has a setting, which means we can adjust when the event is fired too. But both of these will be covered in more detail during this section. We have lots of different events also in our program, the developer tools can really help us with this too. If we right-click and "Inspect" inside of Chrome, we can use the Inspector to point to any one of these elements we want to check. In our case, if we click on this headerImage and then go down to the Event Listeners tab, we can see we have a click listener on this, and if we open this up, we can see, attached to this is a Click Listener, which then runs our function called changeImage. This is really useful for figuring out which event listeners are attached to which one of our elements. Just to recap, we have covered three ways to attach an Event Listener to an element. First, we added an inline HTML attributes. Although this is probably something you should avoid to keep our HTML clean and separate from our JavaScript. We then called the Event Listener directly on elements, and this kept all of our JavaScript code together in one single file. One of the limitations was we could only run one single function, one piece of code from this example, and finally, we looked at the addEventListener method, which not only solved this problem, but it also has more features available too, which we'll discover in the upcoming videos.
46. Listening For Multiple Events & Event Data: The previous examples we've looked at added a event listener to a single element. But there may be a time when we want to add the same event listener to multiple elements. Let's jump into this lesson's file, which is listening for multiple events and event data. You can take a look at how to do this. The example we're going to be using for this is down at the bottom of our index page. You'll notice with these two recipe sections at the bottom, I've added a star to the top of each one of these articles. We can see these if we go down to the bottom of our HTML. In each one of these articles, we have a span element at the very top. This is at the top of both of these articles. What we may want to do is to add an event listener to each one of these stars, which will then add them to a save list of favorites. We could also have many more recipes listed and we may want to add the same event listener to each one of them. Selecting each one of these recipes individually and adding an event listener would take a lot of work. Instead, we can use a loop to help with this. Over in the sidebar, let's go to the events.js file. The first thing we need to do inside of the events file is to select all these span elements which we want to work with. In the Index page, we can see that these span elements have a class of add. We're going to select both of these with querySelectorAll. Let's do this. We'll store this inside of a constant called the addButtons. Set this equal to document.querySelectorAll. Then we can pass in our query as a string. It's a class so use the dot on the class name of add. Remember from earlier when we used querySelectorAll, is it will return back a HTML collection which we can loop over using forEach. First, select all of our buttons with addButtons. The method which is forEach, forEach takes any function to run for each one of the elements, which is in our collection. Therefore, each element also needs a variable name. We'll call this button, to keep it simple. Then just like we looked at above with our single element, we can also use addEventListener. We can access our button.addEventListener. Then inside we're going to listen out for a click event separated by a comma. We then want to run a function. We haven't created a function yet, but we'll do this in just a second. I'm going to call this addToFavourites. This is how we add our event listener to each one of the buttons inside of our loop. Then we can go ahead and create this function. This was addToFavourites. Now for now we'll just add a test alert to make sure this is all working. I will added. Say this, and over to the browser, down to the bottom, click on our star. That's our alert, click on some other elements to make sure this isn't working. Then we can try our second star. This is now added to both of our stars. This is how we add an event listener to multiple elements but often we may want to also be able to tell which one of the elements was actually clicked if we were just adding some CSS or something very generic. It doesn't matter which one we click on. But for our particular use case, we may want to know exactly which recipe was clicked on. Then we could redirect that recipes page and also make sure the correct one is added to our favorites. The way to do this, along with many other things, is by accessing the event data. To access our events data inside the function, we pass it in as a parameter. I'm going to name this variable e, but its name is completely up to us, but it is common to see it called event or e for short. It contains the event object. This event object contains a huge amount of data which we can access. You'll see this. Place in a console log with the value of e and remove our [inaudible] for this example, and then refresh the browser and open up the developer tools into the console and click on any of those stars. This will then give us access to all of the events information. Since we've used a mouse, this is a pointer event and this will give us lots of different information in the form of an object. We can see this with the curly braces and we have lots of key value pairs. For example, we can see the location of the click, which is the x and the y-axis. We can see something called bubbles, which we'll take a look at very soon and lots more information regarding this event. One of the most commonly used pieces of information inside of this event is the target section. If we open this up, this gives us access to our elements, which we've clicked on. In our case, accessing e.targets inside of JavaScript would access our span elements and all the information contained inside. But our use case is a little bit more complex. If we take a look at the structure of our code in our index page, what we want to do is to grab the contents for our level four heading to add this to our list of favorites. But if we're clicking on this span element just here, how do we then access the information from two lines just below? Well, the answer also lies in this target section. It's all alphabetical. If you scroll down to the p section, the first thing we need to do is to step up one level to our article. This article is the parent wrapper for all of this information. We can access all of these contents inside of parent node. We can see the article just here. Open this up. This contains, if we scroll down, a list of children in the form of a HTML collection. Inside the children, we can see we have the span elements with the class of add at the top. Then our image, our level 4 heading and then the div down at the bottom. We can access all of this object information in exactly the same as you would with any other objects. Let's go over to our events. What we to do is to access the target, which is the first section, and then the parent node. After the parent node came the children. Then since the children's section is a HTML collection, we access this by the index number. Just like with an array, we pass in these square brackets, and the index number of two, which is a level 4 heading. Let's save this and check this contains our level 4 heading. Refresh. Now if we fire any of these events with the stars, it's going to give us our h4 Spicy bean Burger. Our second one, refresh. We'll try the Ultimate Vegan. Good. We now have the elements which you want. Now we can drill down into this and select the name with our inner text. So children.innerText. Try this again. Click on the stars and this will then reveal the text for each one of our recipes. This is a pretty long way to get the recipe name which you want to, but sometimes to get the correct information, we just have to keep digging into the object to get the information which we need. I'm not going to build a favorites list for this project, but this is how we could go about it. You could grab the name for each one of these burgers and then push it to an array or even a database. One of the pieces of information we also see in inside of the event object was something called bubbles. This is what we're going to take a look at in the upcoming videos when we discover all about events propagation.
47. Event Propagation: This video is going to look at something important that happens behind the scenes when dealing with events. Even better, we're going to add another event listener over in our startup project. Open up the start project, which is event propagation, and then you'll see inside the browser that we have the same project we carried on from the previous video. Looking at the recipe section down at the bottom, we have our two recipes, and we maybe want to extend the functionality of the recipes. For example, we could click on one and then we could expand the recipe. We could open this up in a pop-up or even redirect the full recipes page. We're going to go over to our events.js inside of this folder and then simulate this by first selecting our recipes. Our two recipes, if you remember, stored inside of the Article sections. We'll begin by grabbing both of these articles and storing these inside of a constant. Let's set this up. Our constant and we'll say recipe titles and set this equal to document, and then deselect multiple elements, we use query select all passing in our article. Now, since this returns back multiple elements, we need to loop over our recipe titles, and we can do this with a for each loop. For each, we'll take in a function which is going to run for each of our elements. In our case, we have two separate elements. We store these inside of a variable called title. Now, we're looping over both of these articles what we want to do is add an event listener to both of these. We looked at how to do this previously, we first select each individual elements, then we can use add event listener. This will listen out for a click event and then run a function called Redirect. Of course, we've not created this redirect function that just yet, let's create this just above. Now, all this you're going to do is to create an alert. Let us know this is working. We'll say recipe clicked. Also, we can pass in the event data. Back over to the browser and reload the page. Click on any of these articles and this will then call our function once done, we can try this with the second article too. This all works as expected. But what about if we tried to click on the Star? First of all, we see the title of Ultimate Vegan, and we set this up in the previous videos. But what about if we click "Okay"? Well, we'll then see our second layer, which is recipe clicked. We may not be expecting this because we did click on the Star and not the actual article. Well, the reason for this is because of various phases which occurred during the event. In modern browsers, event handlers will do something called bubbling by default. If you think of a bubble in water, a bubble will always float to the top and this is what happens with our events. We can see this better if we go into our index.html and then find any one of our articles. When we trigger an event in the browser, such as clicking on an element, the bubbling phase will cause it to not only set of this click event, but will also trigger any inside of other parents elements too. This is why when we click on this Add button just here, it will also bubble up to the parents elements which is the article and trigger any events associated with this article too. Not only this parent article will also keep bubbling up to the other parents, such as a div, this section and it will keep going all the way to the top of the body, the HTML, the document and then finally the window object. It will also trigger any events attached to these elements too. This bubbling events can be useful. For example, rather than add an event listener to lots of different child elements, we could just add a single event listener to a parent's elements and we can test this by adding a simple event to the body. Let's go up to the opening body section. We'll add an inline event handler called On-click and set this equal to an alert, which is going to output the string of body. Now refresh the browser, click on any elements will go for our article, so we'll see recipe clicked and then also our body element has been fired on the way up too. To remove this example, we don't need this inside of our project, but this gives us a good indication of what is going on inside the browser. There is also the opposite available too and this is what is called the capturing phase. This begins at the very top, which is the window object, and then runs all the way down through our elements to the bottom by running any event which is attached to any of the elements on the way. This is bubbling and capturing which both relate to fire events if on the way up or way down and there is also a third term too, which is called the Target. The target is the actual elements which fires events, such as the article event, which we just created. Knowing that other nested events are also triggered on the way up, all the way down, this leaves us with some different ways for how we want to handle it. We may still want all of the events to fire, but maybe do the opposite of what we currently have. Currently we want to click on our add button, this will fire first when clicked on, followed by the outer article element. We're seeing this by the order of the alert inside the browser. But we may want to also fire them in the reverse order, or maybe we don't want any of the events to be fired at all, only the events for the elements which we clicked on, and is a way to cover both of these situations. First of all, we'll take a look at how to reverse the order in which these events are fired and the way to do this, if we just double-check inside the browser, when we click on the star, we see the title which is ultimate vegan, followed by the article event which was recipe clicked. This is working inner to outer and we're going to reverse this by switching this to the capturing phase. Way to do this, is to go inside of our events and then inside of our add event listener, add a third value separated by a comma and we'll set this to be true. True will enable the capturing phase rather than the default bubbling. If we wanted to, we could also set this up as an options object, where we set the capture to be equal to true. Both of these approaches are exactly the same and fine to use. Alertness to run from the bubbling to the capturing phase will mean that now if we click on our button, which is the add section just here, rather than working from the inside to the outside, the outside article event will be fired first, followed by this art. We can try this if we refresh the browser, click on the star. We first see recipe clicked which was associated with the article, followed by our span elements just afterwards. The overall term for this bubbling and the capturing phase is called events propagation and we can also stop this propagation completely. This would mean only the exact element which trigger will run rather than overs inside the tree. As an example, when we clicked on the start, if we only wanted to run the add to favorites function rather than the one we just created before, we can jump into this function and we can access our event information, which gives us access to a function called Stop Propagation. We can also remove the options object from below, which sets the capturing phase. Refresh the browser and now if we try this by clicking on the star, we can see just the title of ultimate Vegan is run. Click "Okay", we don't see any other events fired. This can be pretty complex if this is the first time you've been introduced to this thing. But the easy way to remember is if you have multiple events, we have an option where we want to trigger any of these events on the parent elements or on the child elements, or as we've just discovered we can also reverse the order and also stop any propagation and completely too. The reason why we have both the capture and the bubbling stages is historic. Longtime ago, when browsers were less standardized, some browsers used the capturing phase and some used bubbling, which then led to the current standard where both of these are now implemented in modern browsers.
48. Running Events Once: Welcome back. We're now going to take a look at how we can run a event only a single time. We'll jump into the current file which is Running Events Once, and open this up inside the browser. This also has an attached events.js file with the similar example to what we looked at in the previous videos. We know from the star buttons at the top, we're going to loop through all of these, the forEach loop at the EventListener which will list now for a click and then run our addToFavorite function. All it does is to create a simple alert with the text, which is either the ultimate vegan or the spicy bean burger. A little earlier when we looked at different ways to listen for events. I mentioned that there is a little more to addEventListener than what we're currently using it for. We just looked at one of the features previously, which was to add an options object and set the capture phase to be equal to true. Along with this, another option we have is to restrict the event, the only ever be called once. This is pretty simple, all we need to do is to change this to be once and set this to true. Let's see what effect this has inside the browser. Now, if we reload and click on one of the stars, we see the title of ultimate vegan. This all works completely fine but what about if you try to click this a second time? The second time round we don't see the text of ultimate vegan, instead, we see the text of recipe clicked. This makes sense because we've set the event listener for the title to only ever run once. Therefore, it will refer back to the surrounding article since the stars event is no longer active. This is a really great way to add a single use event listener to only ever be called once.
49. Preventing Default Behaviour & The Passive Option: When we trigger an event, it also has some default behavior which occurs inside the browser. This makes sense because we want the event to actually do something. A simple example is a checkbox. Let's jump into the correct start files which is Prevent Default Behavior & The Passive Option and open up the index.html. Let's go down to the bottom after the very last section, and just above our scripts we'll create an input with the type of checkbox and ID of the checkbox too. Let's save this and open up inside the same folder the events.js. We can begin to grab this element. Anywhere inside of here is fine and we'll grab a reference to this checkbox, store this inside of a constant. We write document.queryselector, and then we're going to pass it in the ID using hash. The ID we gave to the input was the checkbox, and then we can access our checkbox using a method which is addEventListener and then we're going to listen out for a click on this element. This also needs to trigger a function which we'll call handleClick, and then set this function up just above. The function handleClick and its function also needs to access the event data, so pass this in as a parameter and for now we'll do a simple console log with e.target. Since this is a checkbox, we can also access the checked property. This should return a true or false value if the input is checked or not. Over to the browser, refresh, and we'll also make this a little bit bigger. Jump into the console. We can just well, see this at the very bottom, so click on this and we see this is checked because it's true. We can uncheck this and this will be the result of false. We can toggle list and this toggling action is the default behavior, but if we didn't want this default behavior we could prevent the default and handle exactly what we want to happen ourselves. We go back to our script which is the events and scroll up to the function which is addToFavourites. Earlier we accessed the event data and used a method called stopPropagation. Similar to this, we can also make use of another method called preventDefault. As you would expect, this is also available on the event object. We can use this inside of our handleClick function. At the top access our events, we'll call the method which is preventDefault which will in turn stop the default behavior inside the browser, which will also toggle the checkbox value. We'll give this a go. If we refresh, check outbox at the bottom; this is true. If we keep clicking, this is only ever a result of true. We don't see a false value, and also we don't ever see that this checkbox has a tick inside. Living us now free to do whatever we want with this event inside of our function. Also down in the addEventListener method, we can also add in a third value which is an options object where we can set the passive option to be equal to true. Setting this equal to true will always stop the preventDefault from ever being called. I save this and see what happens inside the browser. Refresh and if we click on our checkbox, we can see we're unable to preventDefault inside of the EventListener. This is because if we set passive to be equal to true, this will stop the preventDefault from ever being called. We can see this, we'll reinstate our original behavior of toggling between true and false and we also see the tick inside the checkbox too. You may be wondering why we are preventing the default inside the function, but we are overriding this inside of the EventListener. Well, one reason could be, we may be want to stop other developers from doing something in the future when we're relying on the default behavior. Using the passive option can also lead to better performance too. An example of this is on mobile devices where as sometimes developers prevent the default scroll behavior to implement some custom fancy way of scrolling. But if we're not doing something custom like this it is bad to let the browser know by adding the passive option, therefore the browser doesn't have to figure things out for itself which can take time and also hinder the performance. Back over to our Index page and we can remove this input just here, and we're going to now take a look at a more commonly used example of preventing the default behavior which use when used with forms. An example of this is a sign up form, so create a new section with the class of signup. Inside here, a level 3 heading with the title of Sign up or we can rest this via our inbox. Just below this we can start to construct our form, and then inside the form elements we'll create a new div for each one of these sections. First of all, the label is going to be for the user's name, so we'll say for name passing the name label with the colon. The inputs, this is the type of tax. To match up with our label, we'll also pass in the ID of name. This second div is just going to be for the email, so we'll copy and paste and change each one of these to be the corresponding email. The third and the final div is going to be for the submit, so create an input with the type of submit and also the ID of submit too. Since we have also removed our checkbox from before, we can also go back to the events and remove our function and the EventListener. Let's say this end test, this is all looking good inside the browser. There's our title, and the name, and the email inputs along with our submit. When we submit the form, the default behavior is to send the form to a back-end web server and then maybe do something like redirect to a success page. Obviously, we don't have an additional page to redirect to, so we're going to redirect to the same page which will in turn cause a page reload. The page reload loses all of the form data which is nested inside. If we add something inside here; just any example is fine, hit "Submit", we can see an example of this. We see the page has reloaded and we also lose the form data from these fields too. Well, there maybe occurrences where we want to first capture this data and make use of it before it's all gone. An example of this would be to maybe validate the form data before it's sent to the server. As we just looked up before if we do want to capture this data before the reload, we need to prevent the default form behavior. To do this, go back over to our events and we're going to start by capturing the form and the input elements. Say const form is going to be equal to document.querySelector where we select form element. If we copy and paste this in two more times, the second one is for the userName and we also give this an ID which is equal to name. The third one is for the userEmail. Next up, we'll grab our form and we'll add an EventListener, which is going to this now for the form submit. The reason we can do this and listen out for the submit event is because inside of our Index page, we've added the type of submit. Separate it by comma, we'll trigger a function called handleFormSubmit, and then set this up just above. As you would expect since we need to prevent the default behavior we'll access our event object, then create a console log which grabs our userName. All we've done here is grab our userName element, but if we want to get the value which is input by the user we need to access the value. As for results, refresh. Inside the console, place any name inside of here. To any email, name and submit. You'll see it very quickly there that the username of Chris was placed inside the console, and then very quickly all of the data will disappear. As you would expect the way to prevent this is to access our event object and just like before we can prevent the default behavior. We'll say this and try this out once more, add the name, and email is fine and then hit "Submit". Now our data is still in place. We have our console log, and also inside the input we have the name and the email inputs. Good. Now we have access to all this information before it disappears. We can now validate the name and the email, and check it in the correct format before sending it to the server. I'm just going to do a very simple validation check for this example to see if the user has entered a name using an if statement. We've not covered if statements just yet, but they are simply way to check if something is true. The way we can do this inside of our function is to access the if keyword and then place a condition inside the brackets. We want to check if the userName.value which is the text string, is equal to an empty string. If it is we'll open up some curly braces just like the function body and place in something which you want to run. Let's just place an alert which says Please enter your name, and then return out of this statement. Now, let's save this and reload the browser, hit the "Submit". Our alert has been run up at the top, let's try this with some data placed inside. There we go. Now the username has a value rather than an empty string. We no longer see this alert running inside the browser, so this gives us a chance to do whatever we want with the data before we send it to the server. Remember though since the page is no longer reloading, we also need to handle empty and these form inputs ourselves. This is also pretty simple, we can do this inside of our function just below the if statement. What we need to do is to grab our userName, access the value, and set this equal to an empty string. The same with the email, also to an empty string. Then below this we could go ahead and send this to our server with any way which you wanted to. Let's try this out. We can check the form inputs, we'll clear. Refresh, add in our data, hit "Submit" and it's all worked successfully. It also removes our name and the email data. It is common to see this thing when using frameworks or libraries. If you've ever used something like React or Vue.js in the past, you may have used this in the past when working with form inputs. Next, we're going to finish off our look at events by removing any events when they're no longer needed.
50. Removing Event Listeners: I've had quite a practice so far of creating events, and we've also taken a look at how we can add the one's option if you are a listener to only run a single event once. As soon as that happens, the event listener is then removed from the elements. But we can also remove event listeners manually too we can remove them if they no longer needed or used, and this removal is not essential in smaller projects, but once we get to a larger scale project, cleaning up any old unused event listeners can really improve efficiency. It also means we can use the same element to do different things all by adding and removing these event listeners. Jump into the Chrome file, which is removing event listeners, and if you open this up inside the browser, you'll notice we moved away from the burger project setup. We have a simple example, so have a span element, and then inside the P elements will have a startup score of zero. The aim here is to click on this add button to increase the score, and then we'll use the cancel button to remove the event listener. This also links to our events.js inside the same folder, and if we jump into this, we've got a reference to all three of our elements. We have the add button, we have the cancel button, and then the output, which is our number. What we'll start to do inside here is to create an event listener, which we're going to remove in the future. This event listener will be attached to our add button, so let's add this as we normally do. This now for a click and then will trigger a function called increase. This should all be familiar. We'll now create our increased function just above. What do we want this function to do? Well, we need to select this output which is the current value of zero. This is a p element. We want to select the current value and then increase it by one. First of all, the way to do this is to select our output. We can change the inner text content and reset this to be a new value. Currently, we want to add the value of one each time we click on this button, but one thing we need to remember is here we have the inner text. Well, here we add in a number, so what we first need to do is to convert our inner text to be a number. Where you can do this is to access the number function, and then what we'll do is to grab the current output.innerText. This will then transform this into a number, and then we'll add one onto this. Let's give this a try and save the file, and refresh. Click on add, and each time I click on this, this is increased by the value of one. Next, we also need to listen out for a click on this cancel button. This is pretty much a repeat of the above process. We'll grab a reference to our cancel button. We'll add the event listener. Let's now for the click event, then call a function called stopListener. This load will create this function. For now, just place in a cancel log so know this one is running. Let's try this out, refresh the browser and into the developer tools, jump into the cancel. Cancel button will now take our logs. To get this cancel button to actually remove the event listener from our add button. What we need to do is to access a method called remove event listener. This is pretty straightforward to do rather than our cancel log; we can remove this. We can access the add button, and call remove event listener. Say this, and we'll try this out, refresh the browser, will click on the add button, and this increases the value. Click the Cancel button, see an error inside the cancel, say in two arguments are required, and still, if we tried to click on the add button, the event listener is not yet canceled. This is because we also need to pass in the same parameters that we used when we added the event listener, so we need to remove the click and also the function call refresh, and we'll try to add, which is fine. We'll remove the event listener would cancel. Now we don't see any errors, and if we tried to click on the add button, no further updates will take place. As we've just seen, we need to make sure that the parameters are exactly the same too. Currently, we have the click event, which will is now four, and this is called in the same function. But if we tried to remove a different event listener, such as changing this to you on mouseover, we could say this and try this out once more time. The add button works. But if we cancel the event listener, the add button will still work since we have a different event type. Let's change it back to click. Also, if we had the options object, like we looked up previously, for example, we could set the capture phase to be true. Now, if we reload try, we'll try this out once more, we'll try to cancel. The add button still works. This is because we don't have exactly the same parameters inside of our remove event listener, so it's considered a different event. If we wanted this to work, as you would expect, we also need to copy this over. add in the third parameter, test this out. We'll try to cancel, and now we can't add any more numbers onto this. This is what we need to do to remove an event listener at any stage of our program. As we've seen, we also need to make sure that all of the parameters are exactly the same. Otherwise, this would be considered a different event.
51. HTML Collection or NodeList?: Throughout this section, we've collected various DOM elements using different methods. We've selected DOM elements by class name, by ID, and also using the query selector. When we selected multiple elements at the same time, we also got back either a HTML collection or a NodeList. As promised earlier, we're now going to take a look at the difference between the two. Generally speaking, it often doesn't matter which one we have. Both contain multiple values in an array-like format, which we can use how we would like to, such as looping over them. But if you are interested in the differences, we're now going to cover them in this video. Jump into this lesson's file and inside of here we have an unordered list we do four different list-items. If you look closely, you'll see the first three list-items have the class of list-item, and the final one has the class of active. This will become important soon, inside of the script.js. Inside of the script, we'll take a look at how we can grab the contents of all of these list items, we query selector all, and get elements by class name. First we'll create a constant called static, and we'll see why, in just a moment. Set this equal to document.queryselectorall, we're going to grab all of our list-items and these classes. Just like we're seeing inside the HTML, we'll grab these with the class of list item. After this, create a second constant called live. This is equal to document. I'm going to grab the same list-items, but this time using getElementsByClassName. Grab the list items and we don't need the dot since we already know we're grabbing the class name. Just as a quick refresher, if you don't remember from early on, when we use the query selector, this will return back a node list. Make sure this is query selector all since we're grabbing multiple items. This will return back a node list and when we use getElementsByClassName, this will return back a HTML collection. We can test this, if we do a console log for the value of static. Duplicate this and the second one is going to be live. Refresh with the console open. Here is our NodeList and also our HTML collection. Both of these does have some similarities and the first one is they both have a line of property. We can see this, we access.length on both of these console logs. Refresh and we can see both of these has three separate items. Also another similarity is if we remove the length, we can also use the square brackets to access any property by the index number. This works for static and also live. This will return the single value which was selected. But as well as these similarities, there is also some key differences too. Earlier we talked about something called nodes, and said that we can have different types inside the DOM. We have element nodes, we have attribute nodes, and also the text nodes too. These are all values which can be returned inside of a NodeList. With a HTML collection though, these can only contain HTML elements. Often this is not going to cause any major problems, but it can be useful to know. Also a clue to the next thing we're going to take a look at, is the name of these constants. A NodeList which we get back with query selector all, will return a static collection. An HTML collection is considered live. What this means is when we update the DOM, only live collection is aware of any of the changes. To see this test what we're going to do if we jump back into our index page, is we're going to make our item 4 have the same class of list item. We'll then see which one of these two references to the same elements are going to be updated inside the console. Quickly, just before we do this, we'll also move these square brackets. Sometimes when we have multiple console logs like these, it is easier to wrap both of these inside of some curly braces. The reason why, if we look at the console at the moment, we don't see which one of these is which. If we save this and refresh, these curly braces will now turn these both into objects, which will give us a property name of static and live. We can clearly see the difference between these two logs. Now let's get back to the task of updating the fourth list item element, to have the class of list item. First we need to grab a reference to this. We'll say const, and we'll say active, and we'll set this equal to documents.queryselector. We'll grab our fourth list item which has this class of active. Then I'm going to set up a set-timeout function, which is going to update this elements after a certain period of time. Set-timeout takes in a function which is going to run. Also just after the function as a second argument, we pass in, the time delay. After 3,000 milliseconds, which is three seconds, we're going to run the contents of this function. All we need to do here is to select our active elements, drop the class list, where we can make use of the add method to add a new class. The class which you want to add is list-item, make this the same as the previous three items. Then also inside this function, we can move up the two console logs and see what happens after we perform the update. Save, reload the browser and give this three seconds to run the function. The static NodeList only has the three original items, well the live collection has been updated. This also includes the fourth item which we've just added.
52. Mini Challenge: Create a Dark Mode Button: Welcome to the end of this section. As a little mini-challenge, I would like you to go ahead and replicate what we can see on the screen just here. We have some very basic HTML. The key part is openly top corner. What I would like you to do is to use JavaScript to respond to the user's click on this button and then it toggle between the light and the dark mode and to do this, is actually not as difficult as it looks. All we have if we go into the start files, is [inaudible] index page with all the texts, just like you see here, we have our style sheets and then currently inside the style sheet, we have the body section which sets the default color to be light mode, we have the light background color and also the darker text. Then what I would like you to do is to listen out for a click event on the button and then add the class of dark. This is going to do the opposite, we're going to set the lighter color for the text and also the darker background color, give us a go using JavaScript, respond to the click at the dark mode class. Then also if you fill in confidence, it would be good if you could add an IF statement like we looked at in a previous video. Also check if the dark mode is currently enabled, if it is, we then go in to remove this class which will then toggle back to the light state. As a little guide to help with this over the Mozilla website, we can make use of a method called contains and we can use this to check if our elements contain a certain class. In our case, we're going to check all the classes which had been added to the body and then we'll check if it contains the dark class. If it does we'll then want to remove it. Give us a go, don't worry if you get stuck along the way, you can always refer back to this video for some guidance. Back inside of the index page, let's jump up to the header section. You can see here we have the initial button which is the moon and then just below we have the HTML entity which is going to be for the sun. With that in place, let's now go ahead with my solution and if yours looks a little bit different, it's completely fine. Jump into the script, inside of the script section, the first thing we need to do is to grab our button and store this inside the variable, with document.querySelector see in our button. This is a reference to our button which we've just seen inside of the HTML and we only have this single button, this is fine like we've done many times of all, we then access our button element. We can then add an event listener and this is going to listen out for a click event, this will trigger a function and let's call this function toggleDarkMode which we can then set up just above. Back to our style sheets, let's just open this up and take a look inside. As we've seen before, the body section has the default light mode enabled, what we can then do is add this dark class to the body which will then overrides both the color and the background but just before we do this, we need to actually select the body and store this inside of a constant, document.querySelector, that's in the body. Now we have a reference to this body, we can select this inside of our function and we can use this to add our new dark class, this was classlist, we use the add method, where we add the class of dark. Now, with this in place, we'll open up our index page inside the browser and this is our first step taken care of. We have the light mode enabled by default and now if we click on the moon icon, this will end at the dark class and also the corresponding colors. This is the simpler part, all we've done here is add a class but now we need a way to figure out the opposite and remove this dark class. To do this, we can add an IF statement inside of our function and this is going to check if the dark class has already been applied before we add it just below. We can use the contains method which we just looked at in the browser. What we need to do inside of the IF statement is to check if the body contains this dark class. We'll first just bold check this inside of a console log, we can access the body, the classlist and then use the contains method to check if this dark class has been applied. As you can see inside the documentation, this will return back a Boolean value of true or false, we can then use this inside of the IF statement. This console log is at the top of the function, we'll check if this is true at the beginning and then just after we add this, we'll check if this applies at the very end, save this and over to the browser, jump into the developer tools, reload and into the console. It doesn't like our empty IF statement, we'll just remove this and refresh and now if we toggle our button, initially we see the value of false since the first console log is at the top of our function but then our second one is true because we've added this dark class to our body. Great, now we know this works, we can remove our console logs and we can now apply this to our IF statements. Just like the logs, we'll check if the body.classlist contains the class of dark, if it does the code inside will run and what code do we want to run exactly? Well, if we think about this we tried to toggle the dark mode on and off, the dark mode is already applied, we want to remove this class from the body, we can do this by accessing the body.classlist and then use the remove method which will remove our dark class, save this and try this out inside the browser, the default is light mode. We now have the dark mode but if we tried to click on this again, it doesn't yet return back to our light mode. The reason why, is because of inside of our function, whatever we do at the beginning of this function will always still apply in the dark mode class and the way to get around this is inside of our IF statements. If we add the return keyword, if the IF statement is true and the code inside will run, this return statement will break out of our function, the code just below will not run. Effectively, if the IF statement is triggered, only this block of code will run. If it's not triggered, this section at the bottom will run instead. Try this one more time, refresh the browser. Our toggle button will now work correctly. The remaining steps was to change this icon in the top corner, to change between the sun and the moon. We already have access to our button, so we can select this inside of our function. First, just above the return statements, we'll access our button and we can change the inner HTML to be equal to our HTML entity. In this IF statement, we are removing the dark mode, we then want to provide a reference of the moon then reselect it. Go to our index page, grab the entity which is the moon which is co-reactive, so select this, paste this in as a string and just below, we can also set the color of these elements with the style property, set the color equal to an RGB value of 62, 62, 62. Outside of the IF statement, we want to do the opposite, if we copy both of these lines, we just add it in the bottom of our function. The inner HTML is going to be our moon icon which is this one in the comment then you save it, add also the color, I'm going to go for aqua. We'll try this out, toggle to the dark mode. I'm looking then at re-enabled the light mode with the sun icon, click on this and this will then reinstate the moon. We can then toggle back to the dark mode.
53. Video Player Project: Creating The UI: Hey. Welcome back to our new section. This section is going to be used to create some practice projects to reinforce what we've learned so far. We're going to kick things off with a video player project. HTML has a native video player with controls to play and pause the video. But we can also remove these controls and create a fully custom player. We do this using some properties, methods and events which we'll have available. Just as a quick preview, this is what we're going to be creating and this is the final version. At the top, we have our video display in which is the full width of the browser, below we have a progress bar and then we have the controls at the bottom. As you would expect, we can click on the Play button and this will begin the video and start things off with the progress bar. We can pause, if the video has audio, we can also control the volume level and also the playback speed can be controlled too. We can make this slower, we can speed things up and we can also skip through the video by going backwards and forwards too. To start things off, jump into the stars files. I'm going to need to go into the new section which is Number 5, jump into the video-player project. If you open up the index page, you'll see we have a pretty basic starter. We don't have any content, all we're doing here is linking it to our style sheets and also our script.js. The script is an empty file, so we'll create all of this ourselves but we do have a headstart with the style sheet. This just gives us some basic styling and layout so we can focus on the JavaScript. Also provided is a video which is an MP4 file and this is the same one you just seen in the final version. But you can also replace this with a video of your choice if you prefer, everything will work exactly the same. Let's start by opening up our index page inside the browser, copy the path to this file, paste this in and as you would expect, there's no content yet on the screen. We'll begin inside the body section, I use the HTML video elements and this is a wrapper for the content which we're going to place inside. If you've used the native video elements or even the audio elements, this will be pretty familiar, if not, video is just a wrapper where we provide the source to our video files. The source is provided inside with the source elements. This doesn't contain any content inside, so we just have the single tag. We don't need to close it off just like this, instead, we use this to provide the source to our files which we want to play and in our case, it's the video.mp4. A second attribute which we can add is the video type and in our case, this is the type of video and it's an MP4 format. The video element does also support other types too. Although this will also just add some text in place which is some fallback text if the video is not supported. This is not really a problem nowadays since the video player is really well supported in all browsers but it's worth putting this in, just in case. Let's say your browser does not support HTML5 video, so initially if we open this up inside the browser, refresh the page, we effectively have a still image, we can click on this, we can play. The way we can do this is to make use of the native HTML5 video controls. Activate this, it's pretty simple, we just go into the video wrapper and we add the controls attributes. This will enable the default video controls which we can now see down at the bottom. We can play this. We have the elapsed time, the total time of the video, we have a progress bar and we can also control things like the volume, we can switch this to be full screen. Also, we have some options for the playback speed and also to enable picture-in-picture. Of course, this is all really good and it's great to have a native video player, for our situation, it doesn't learn us anything about JavaScript.` What I would like to do is to remove these native controls by removing the controls attribute and recreate these buttons to interact with the video, play it using JavaScript. Where we could do this, if we go over to the Mozilla website which is developer.mozilla.org, do a search for video. This is one minute here. Inside of here, we'll see an example which is nothing we've already not seen so far. We have the video wrapper, we have the controls attribute, we have the source to our video files and then the fallback texts if the video player is not supported. We have various other attributes such as, if you want the video to also play and also if we go a little bit further, we have access to various events. Various events are configured throughout the playback of our video, for example, looking at this now for events when the video is playing, for when it's paused and also the video progress too as the time updates. Also, this video element inherits methods from a parent API called HTML media elements. Let's do a search for this, scroll this up, HTML, media elements and as well as these events which we can list now for. This media element has properties and methods such as the ability to play impulse, we can change the volume and we can see how long the media has been playing for. We can see these if we scroll down a little bit further, we'd have various properties. We can also toggle the controls from here if we wanted to, we could check the current time of the video as it's playing, we can check the duration of the video, how long it's for, we can loop the video, we can also mute the video, and scrolling down we'll also have the various methods which we can use too. We have some useful methods such as the ability to play and pause a video and we are going to make use of these in our projects. Our video elements which we use inside of here has access by inheriting all of these properties and methods. Of course, regular methods such as a dif would not need access to these extra methods which is why these need to be inherited. But why not just attach these extra methods and properties directly to these video elements? Why do we need to inherit them in the first place? We'll have any separate means, other elements can also make use of them too. Looking at this, other elements such as the audio elements can also make use of these same methods and properties such as play and pause, meaning we don't have to duplicate these, to add them to both the video and the audio elements. Also this HTML media element is part of a collection of lots of different web APIs which give us access to the power of lots of amazing things inside the browser. In fact, one of these web APIs listed is the DOM API. This is the one which we've used in the last section to interact with our DOM elements. For example, among others, that is the HTML canvas elements, which enables various drawing functions. This is just above. It enables to draw inside the browser and we'll take a look at this one later too. We also have things like the Geolocation API, so users can share their location. We have drag-and-drop, which allows us to move elements on the page and drop them into certain locations. We're going to use these media properties and methods very soon, but first we need to create some HTML controls, which we're going to use to activate them. Let's create these inside of the body section, just below the video. This will create a new section with the class of controls. This is just going to trigger our CSS and let's open this section up. At the very top, we'll begin with a progress bar, just like we see in the final version, and then we'll create various new sections from top to bottom. From the top we have the progress bar, it's in the value attribute, which is going to be initially the value of zero and we'll update this value as a video progress updates. Next a div section, which is going to be the wrapper for the Play and Pause buttons. The first button detects the play, and since this is going to be controlled using JavaScript, this will need a unique ID. This can be Play, and so you kick in our CSS, we'll give this here class a round. Duplicate this one and change the ID to be Pause and also the text too, give this a "Save" and "Refresh" the browser. Good. Of course, these won't do anything just yet because we need to grab these using JavaScript and trigger all properties and methods which we looked up before. The next section is for the volume, so just below our last div, we'll create a new one. The class of align. From left to right, we'll create a span element and this is going to be to reduce the volume level, so say volume negative in the center and input which is going to be a range slider. The ID is equal to volume. Then we can also control the minimum and the maximum values for this input. The minimum is going to be equal to zero and the max is equal to one. This is what we use inside of JavaScript. We'll grab the range between zero and one. The detected volume is selected by the user. We can also jump up from zero to one in various stages and we can do this with this step, which is going to be equal to 0.1. This means that each time we move this circle across, this will jump in 0.1 increments, basically giving us 10 steps. After this, just below a second span elements and this one is to increase volume. We'll say volume plus. There we are. The next section is for these playback speeds, so this is going to be various buttons which goes from 0.5 up to a double speed. To keep this consistent place in a div, and the first button is going to be for the playback speed of 0.5, the class of speed, and then copy and paste this three more times. This is going to be for one, which is the regular playback speed, 1.5, and then double our regular speed. The last section, again inside of a div, this is going to be for our back and our forward buttons. Last button, we can use some HTML entities to get these left and the right directions. Entity for the first one is ⟲ grab this inside of JavaScript with a unique ID which will be equal to back and also the class of skip. Duplicate this, and this is for forward. We'll use the same class, where the entity is the ⟳ and this will give us the Forward icon. Let's try this. "Refresh" and our control is now complete inside the browser. Of course, they won't do anything because they are just regular HTML elements. We need to control these inside of our script. Let's jump into our script and we can grab each one of these elements with their unique ID. Open up our scripts and as well as accessing each one of these controls buttons, we also need a reference to our actual video. Need a reference to all video elements or the wrapper because these elements can access all the properties, methods, and events which are going to allow us to control the player. The document.querySelector, pass in the video. We'll do the same for each one of our controls. We need to access our progress bar because we need to update this with JavaScript, we need to access the play and pause. We want to access the volume input, all of the different speed buttons, and finally the back and the forward buttons. We'll do this from top to bottom. The next one is for the progress bar and we use the query selector. Next we have the play and pause buttons. This one is an ID, we use the hash, the ID of play and let's duplicate this. The second one is pause. On to the next, we need the volume. We'll grab the input type with the ID of volume, we duplicate this one, change this to volume. The next one, if we go back to our Index page, is going to be selecting all four of our buttons. We don't have an ID for each one of these, it'll be a lot simpler if we selected these by the class, so we can use query selector all to grab these. Then in the next video we'll detect which button has been selected. The next constant is forward speed and this time we need to use query selector all, use a dot since this is a class, and then the final two is for our back and our forward buttons. This time we are back to the IDs, so we use a hash. This is for our back button, duplicate this and change this to be forward. Good. We're making good progress with this video player. We've now added the controls. We have access to all of these controls through our variables, and in the next video, we can start to add events, properties, and methods to then control our video player.
54. Video player Project: Video Events, Properties & Methods : In the previous video, we briefly looked at these HTML media elements. We discussed that it had some properties and methods which we can take advantage of. This is what we're now going to do in our JavaScript. Properties wise, if we scroll down, we have something called the current time, and this is something which we can use to grab the current playback time in seconds. Go down a little bit further. We also have something called the duration. This is the total length of the video. We'll also need this later on in this video. A little bit further down towards the bottom, we should also have some methods available. Here we can take advantage of methods such as play and pause. Of course, these are really going to be useful for our project. Let's go over to our script.js and implement these inside of here. The play and pause is pretty straightforward. All we need to do is to grab our particular elements and then add an event listener. Let's now free click, and then we can run these methods. Inside of our video player, inside of our HTML, we already have these buttons setup to play and pause, and in our script we already have a reference to both of these elements. We can begin by accessing the Play button and then at event listener. We'll listen out for the click event. You could either add an inline function inside of here or you could add this separately. I'm just going to add this inline; function name of play. Then what do you want to do inside this function? Well, what we need to do is to access our video, which is our video elements, and since this inherits all the properties and methods from the HTML media elements, we can then use these methods which we just looked at, and what we need is play. We can try this out. Let's test our video player, refresh, click on "Play" and it instantly updates the video. Of course, the pause button doesn't work just yet, but if we go back to our JavaScript, we can access this and do exactly the same by adding an event listener. For the click event, we will run a function called pause. Pause will look pretty much the same. We just need to access our video and the post method. Then we can also test this is working too. Play, this is fine. Then pause, and this will then pause our video. As well as these two buttons may also be nice to play and pause the video when we click on the actual video at the top. Also some players allow you to do this with the space bar. This will create a function which you're going to toggle between the play and the pause state. Step one, we'll crate our function to toggle play. The first part of this function is going to detect if the video is already paused. If it is, we'll then run the play function. If not, we'll go ahead and pause. We'll create an if statement inside of here, which is going to check if the video is paused. How to know this will work. Well, if we go back over to the documentation and scroll down to the properties, we have access to a read-only property called paused, which will then return a true or false value. In our case, if the video is paused, we would then want to do the opposite and run the play method. If this is true, we can also return out of this if statement. Then just below, if this is not true, meaning the video is not paused, we don't want to pause the video. For this to work, we need to access our video elements, which is stored inside of this video constant. Place is down at the bottom, video.addeventlistener. We're going to list now for a click event on this video and then run our function which is toggle play. Save this and over to the browser, reload this. Since this is currently in the paused state, which is true inside the if statements, we should now be able to click on this and then play the video. Click on this and this should work. We'll then click on this again. The second click will do the opposite and pause. Good. This all now works. The next thing, as mentioned before, is to also toggle between the play and pause state when the user hits the space bar. When pressing the space bar, this is not attached to any single element. What we can do to listen out for the space bar is to add an event listener to the actual document. Let's grab this, select add event listener. We want to list down for a key down event. This key down is when any button on the keyboard is pressed. This will then run a function. Here, before we run our toggle play function, remember we're listening for any key to be pressed on the board. What we do need to do is to first detect if the space bar is being pressed or any other key. We can do this by accessing the event information, passes into the function. Then we can take a look inside the event information. Save this, refresh, open up the developer tools, jump into the console. What we need to do now is press any key inside of here. This has unfired our keyboard events. If we open this up, this code property on this object will tell us exactly which keyboard button has been pressed. My case, I press the space bar, which is the code of space. We can now access this inside of our function. Rather than the console log, we'll check if the event.code is equal to the string of space, which matches this string just here. Then what we want to do is to run our toggle play function. That's the result, down and refresh. Now if we press the Space bar, this will run our function once again, and it will pause. Also you'll find if you press any other keyboard buttons, it will not toggle this function. Good. Moving down, the next thing we have is this volume slider. If we go into the index page, we can see this is being controlled by the input with the type of range. The range which we've set here is a minimum of zero and a maximum of one. So zero being silent and number one being the maximum volume. As you use the slides, it will go up or down in increments of 0.1 of the script vertical reference to this with this volume constant. Select this. We'll then add an event listener. We want to listen out for an input event. This means that the user has moved the input. Again, this will trigger a function called change volume. Back over to the Mozilla documentation. We can see inside here. We also have access to a volume property. We need to make sure that the volume is exactly the same as our range slider. We can do this by accessing our video.volume, which is this property just here, and then we want to set this to be equal to a new value. This new value is the value of our volume range. Up at the top, we've got access to all volume, which is this input just here. This is just a reference to the actual element. If the value of the slider meet accesses with the dot value property. Let's try this out. Save and refresh. It can play. Now if you slide the volume up and down, if you built here a difference in the volume levels moving down the next thing we have is our four buttons, which is going to slow down and speed up the playback of the video. In our script we use query selector all to select all of these power buttons install these in the speed variable. This means that we have access to all four of these buttons. We'll also need a way to grab the particular values. This we can add a custom attribute called data speed. This is going to be equal to the value of 0.5 and then we'll just copy this, paste this into our next button. This one is the value of one. The third one is 1.5 and the last one is double the playback speed, which is two. This is just a custom attribute and we generally begin custom attributes with this data prefix. We know from previous videos that we can access the values of any one of these attributes. Now back over to the script and we can begin by adding an eventListener to any one of these buttons. The script down to the bottom, access all four buttons which you stored in the speed constant. Since we have multiple values, will loop over width forEach. Customer function which is going to run for each one of our buttons, I'm going to store a reference to each one of our buttons inside of a variable and then access all buttons. Add an EventListener. We will just now for a click event, and then run a function called setSelected. Also we haven't created this yet, so we'll just create this just above, setSelected as in the function body. This function is responsible for doing two things. First of all, if the video is not currently playing, we may click on any of these buttons, but we first want to begin the playback. We do this just as above with video.play, pass this into our function. Then the second thing we want to do is to select the particular playback speed. That is, we need access to our event information. Then as always, we use e.target to access the particular elements. We can then use getAttribute, which we've looked at in the past to grab our customer data-speed attribute. This should now give us access to our values which goes between 0.5 up to 2. We also need a way to set this value to our video. First of all, access our video and then inside the documentation, we have another property variable called PlaybackRate. So access this. This equal to the volume of our attribute. Let's try this out. Load the page. Then we'll try 0.5, which is really slow. Single speed, 1.5, and then double the speed. Good. As this video is playing, we also want to update the progress bar up at the very top. To do this, we can access some various events. We can do this by taking advantage of some properties called the duration and currentTime. Under the probability section, at the very top, we have the currentTime, which is the equivalent playback time in seconds, and also the duration of the video. We can use these two properties to calculate the value of the progress bar at any given point but we also need to do this on a regular basis. Unfortunately, there is some events which we can list now for if we scroll down to the events section. Down near the bottom under events, we have an event called timeupdate, which will fire each time the currentTime attribute has been updated. Meaning we can listen now for the current time to be updated and then recalculate the progress bar each time. Step 1, we'll create a new function which is going to actually update the progress bar and then we'll call this on each update. Great function called updateProgress. We could just immediately update the progress bar, but first we'll add a quick if statements inside, which is going to check if the video.currentTime is greater than the value of zero. This will only run if the video has started to play back, and then we can access our progress bar. This is stored in the progress constant. Set the value. This value can be calculated by dividing the currentTime by the duration. So video.currentTime easily properties which we just looked at, divide this by the video.duration. To run this function, we'll then need to add an event listener to a video player. Access the video, add EventListener and this time we're not actually list now for a click, we want to list now for one of the built-in methods. The built-in method is this timeupdate, which will then call our update progress function. Let's test this out into the browser. Click Play. As soon as this begins our playback, we'll then cause the update to our progress bar. Pause, and this will stop. Good. We'll also try to set the slow speed and it slows it down. Also the fastest speed will increase this too. We're almost there with our video player and the last thing to take care of is these back and forward buttons. The way to set these up is to also make use of the currentTime and then we'll deduct a number of seconds and also increase the number of seconds depending on which button has been clicked. We all have access to both of these buttons with the back and forward constants. It can be in with the back variable by adding an EventListener. Is now for a click, which is then going to run a function. We'll call this back and then access our video player answer the currentTime using the subtraction assignment operator. I set this equal to a value of five, and this will deduct five seconds, and then reset the currentTime to be equal to the new value. This is simply just a shortcut and it'd be exactly the same as doing video.currentTime is equal to video.currentTime take away five. So both of these are exactly the same. The opposite, we can just Copy and Paste this. This time we need to listen out for the forward button. Function can be called forward too. This time the only difference is we want to increase the time by five seconds. Let's try this out. Refresh, which I forward, and this will update the progress bar. Click back. This will end it up five seconds from our currentTime.
55. Shape Drop Game: Creating The UI: Welcome back. We've got a fun little game to end off this section, which is going to be a shape drop game. This is going to make use of the HTML drag-and-drop API, which means we can create all of these shapes. We've got a section at the top with empty outlines and then the shapes down at the bottom. The user can then drag onto these and drop them in the correct matching location. Each one of these shapes on the bottom has a corresponding shape up on the top. If you've got these right, we increase the score. You get these wrong, this score is deducted by one. Going to begin in this video by creating all the HTML, so basically the user interface. Then in the upcoming videos, we'll make all this work using JavaScript. This project is going to make use of another Web API, which is the drag-and-drop API. The drag and drop API gives us access to various drag events which we can use inside of JavaScript. We can listen out for when an element has began to drag. We can listen out for when the drag ends. We can listen out when an item is being dragged over, when it's left a particular target and also, listen out for when this item has been dropped to. This is what we're going to use in the upcoming videos. But for now, let's head over to the project files and we'll start inside of the index page. Inside the shape drop game, this is a pretty simple index page. Other half is our very basic structure which links to an empty script.js. Let's start this project. I've already added some styles into this. All we've done here is add some classes which link to various shapes. For example, we've got various rectangles, we've got pills, we've got, we've got squares. Each one of these is generally the width and the height. We've got a background color, and some of them also have a border-radius too. We'll jump into our HTML, we'll create all of these elements, and link these to the correct classes. The script is empty for the future videos, and we're going to start in the index.html. Let's jump into here and into the body section. The body section is going to be relatively straightforward. If we look at the final game, we have a header section with the score and some text and then we have two separate sections below. Each one of these sections is going to be a div big shape. Then we'll just link these to the class names to provide each one of these shapes and colors. In the body section, at the header, which will be for a very top section. As you can see, the first thing we need is a heading. It's h3. We'll say score, which will just be hard-coded text. But then just afterwards we need a dynamic value. We can surround this in a span, place in the ID of score and then we'll fill in the contents of the span later on using JavaScript. One thing we can't see on this final version is a button called Play Again. This is because he's put some will only appear at the very end of the game. But for now, we'll place this in and then we'll hide this later on to detect Play Again. Then let's open up our version inside the browser. Copy the path to our index. You should see all of the predefined styles have now kicked in. The last thing we need inside this header is the text. Just underneath button add a p element. The text of drag, the colorful shapes into the matching holes. Good, after we've done this, we then move down to our two sections. The top section is going to be the drop section because we dropped the shapes inside of here, and the bottom one is going to be the drag section. These are pretty much the same. They're going to have the same class names to create the shapes. We'll also add an additional class to the top section. They just have the outline rather than the solid background color. Let's check this out. Looking good. Now, just below the header, create our first, which is the top section inside of a div, and give us a class of the drop section. Duplicate this, and our second section is going to be for the drag section. We can use any elements which you want to for each one of these shapes, it's just going to be an empty element. I'm going to go for a div. We don't need any text or any content inside the div because we use the CSS class to link this and create the shape on the page. For example, about the class of square. Save this. Square now appears on the screen. We see this because this class of square inside of our styles.css, just here as the background color and also has a width and a height set. This will automatically place our shape on the screen. The same for all of the rest of the classes, duplicate this one and the second one. This one is for our rectangle, number 3 is for the circle, number 4, square number 2. Even though we've got some of the same shapes such as two different squares on here, you'll notice that they are different sizes to make the game a little bit more difficult. We've got the square number 2. The next one is for oval number 2 and rectangle 2, rectangle number 3. Next one is for pill, oval, then finally pill number 2. Let's save this and check out our project. Refresh. There's oval shapes now on the screen. The next thing to do is to basically copy all of these sections, all of the shapes, and paste them inside of our drag section. Even all of our shapes now in place. But we need to now mix up the second section because if we didn't we had all of these in the same order as above, it will be really easy game. Just mix up some of these. I'm going to make it the same as a final version. At the beginning we've got the rectangle, is at the top, the square, the third one is the pill, square 2. It doesn't matter if yours is different or the same. You can make it exactly how you would like to. Oval 2, pill number 2 next, circle, rectangle, and then rectangle. That's completely fine, as long as it's in a different order to the ones above. To keep our shapes consistent in both of the sections, we've used this same class name on the top and the bottom sections. But the problem we currently have in our version is the shapes on the top have this background color. What we want is just like the final version where we have an empty outline. We can drag these shapes in, which will then fill in the background color to give the illusion that the shape is being dropped into a hole. We can do this by adding an additional class. If we take a look inside of our style sheets and then go down to the bottom, we have this class of drop. This is certainly a purple border, which we see in the final version around each one of our shapes. We've also removed any background color. Now inside of our index page in the top section, we can add this class, I've dropped each one of our shapes. We can copy and paste this if you want to, or you can type this out. Places for each one of our shapes. We got to save, and let's check out our own version. Refresh. Now I've got an empty shape which we can now move any one of these elements inside. Of course, if we try to click and move any of these, we don't see the drag events that just yet. But this is something which will enable in the upcoming videos when we make use of JavaScript.
56. Shape Drop Game: Drag & Drop Events: As you would expect, just placing in regular HTML elements like we have here. When we try to click and drag any of those shapes, nothing happens. Make these shapes draggable, the first step is to add a attribute called draggable and set these to be equal to true. Because we all know the bottom sections be draggable, add into the drag section, and then jump into our first shape. Set draggable to be equal to a value true. Now if we try to refresh and click on any of these elements, we can now drag these around the page. We still need to setup things like the drop zone to allow these drop into place. But for now, this is our first step we need to take. Copy this and paste this into each one of our additional shapes. I'm to try this out. Good. We can now move them all, but we can't really do much with them just yet. This is because we need a setup exactly what we want to do at each stage. The drag and drop API has various events which we can listen out for. This is what we looked at initially in the first video. We can make use of these inside of our scripts, to jump into our scripts.js, which should be an empty file. Then at the very top, what we're going to do first is to crop all of our buttons with the class of drop. In the index page, all of the top sections have this class drop. We can use query select all to crop all of these elements, and then we can loop over these elements, and listen out for any element be dropped on the sections. Document.querySelectorAll as in the class of drop, and then we can store this inside of a constant called dropzones. Good, now we have access to all of these dropzones. We need to then loop over these and add an event listener, to listen out for a drop. Grab, all dropzones constant, loop over wait for each, is going to run function. Then each one of these shapes will pass to our function. Let's call these the element, drop the elements, so each individual 1, we can add an event listener, which it comes to this now, for the drop event. This drop events is enabled because of the drag and drop API. This is what we see here where an item is dropped on the valid drop target. Separated by a communist, is going to trigger a function called handleDrop. For each function just above, it will drop. Then all we do for now is placed in a simple console log, at least now this is working. The text of dropped, so this is the drop event now taken care of. The next thing we need to do is listen out for the drag event again. We can do this with an event called drag starts and back into the drag events section. This is one which we needed just here. This event is fired as soon as the user begins to drag in any one of our draggable items. What we're going to do is to access our full document and add an event listener to listen out for the drag start event on any one of our elements. Place in drag starts, which is then going to run a function called handleDragStart. To create this just above, handleDragStarts. For now we'll just place in a console log once again, check this is all working. Drag starts, and then we'll copy and paste this section we just created, and add this in just below. The only difference is going to replace drag start with drag end, the same for the console log and also the event name and function. This now in place, we can now test this out, make sure your file is saved and then it reload the browser, drop into the console, and now we can try this out. If we click on any of our draggable elements, we can move these and we see the drag start event has fired. Drop this over one of our elements. We see the end of the drag has also fired. But one thing we have missing is this console log or dropped. What we would expect these when we go over one of our drop zones, which is one of these top shapes, and we're dropping elements anywhere inside of these. We would expect this console log to be fired. The reason why we can not drop is because the default behavior is to not allow things to be dropped into any webpage by default. We need to prevent this default behavior on our dropzones. We can do this by listen out for an event called dragover, and this means we're dragging an element into a certain zone, where we want it to be dropped. At the very bottom, will again loop over all our dropzones and then do a for each loop to access our dropzones. For each, which is each one of our empty shapes. Run a function. This function will take a value for each one of our shapes. We can access value and then add an event listener. This event listener is going to list now for an event called dragover. This is the event just here, and it's called every time a dragged item is moved over a valid drop targets. Basically want to remove all items over this top section. It's going to fire this event called dragover, separated by comma Great function called allowDrop, which we can then create just above. Now when we click on any one of these elements, in our version and drag them over any one of these dropszones with anyone to access the event information, and then we can call prevent default. Remember the default behavior was to not allow this to be dropped. We're now overriding is to allow all function about the top to now be called. Let's give this a try, save and refresh. Drag any of these, and then drop them onto a target. We now see the text of dropped, and our function is now working correctly. Good. Now we know this function is working and all the rest of the ones are also firing too. We can now begin to make things happen inside of our game. What we want to do is to only allow a certain shape to be dropped onto a certain dropzone. For example, we only want the rectangle to be dropped on the rectangle and a circle to be dropped on the circle, inside of our index.html. One way of doing this is to match the particular classes, so if we drag the class of rectangle, we only want this to be dropped on the rectangle class in the dropzone. To make this happen over in our handle drop function, what we need to do is to have access to both of our elements. We need to have access to the element which has been dragged, and also the elements which we are dropping over. We can then compare the both of the classes are the same. Before we allow this drop, we can do this inside of our function by accessing the events information, and this will give us access to all elements with e.target. We can then access our class list. Let's check this out over in the browser. Refresh, drag the rectangle and drop this over any one of our elements. We've dropped this over the square in top-left, and we'll get back a class list which includes drop and also square. This is exactly the same as what we see inside of our HTML. Let's try one more. We tried the rectangle, and this one also works too. This is how we can access the classes for the dropped elements. Well, how do we go about accessing the classes for the dragged elements? Well, a nice way of doing this is by store this inside a variable at the top of our page. Just above our dropzones, we say let selected. We can update this value inside of the function called handle drag start. Remember, this is fired as soon as we begin to click on any one of our elements at the bottom to begin the drag process, and to do this, we need to access the event information. We can remove the console log, and then update our selective variable to be equal to e.target. This now means if we go back to a handle drop function near the top, we now have access to both of these elements. We have access to the class list of the drop elements, and also up at the top we have access to the dragged elements with this variable called selected. Now we can create an if statement to check if both of these elements contain the same classes. I can do this first by accessing our class list, f e.target.classList, then we have access to a method called contains. What we want to do here is we are checking if the particular element we have selected, which is this one just here, contains the same class as this one just here. We can pass it in selected.className. We can use the single class name for this one, because we know that any one of these drag elements is only going to contain a single class. If this is true, we'll open up the calibraces, pass in the console log, and we can change this to be the text of correct. We can then return out of this if statement, if this is true. If this is not true, will then run the code, just below, where we'll do a console log with the text of incorrect. Let's try this out, just refresh. First of all, we'll try the correct behavior, so a square, we'll drag this onto the correct square, which is this one, and we see correct. Let's drag this onto a incorrect item, we'll get the text of incorrect. You can see if we go to the final game just here, as soon as we get any one of these correct, by dragging these into the right or just above. This shape is now removed from the bottom section. The way we can do this, inside of our if statements, we can now remove the console log. We can grab the selected elements and they call the remove method. Let's test this out, refresh again, and drag a rectangle into a rectangle, and it's then removes the rectangle from the bottom section. Good. The next thing to do when we have one of our shapes in the correct hole, is to make sure that the background color is changed to the same color as the shape which has been dropped into place. If we drop this in, it's now inheriting red background color, gives the illusion that this is dropped into a particular shape. Now the way we can do this, if we take a look at our styles.css, the only difference between these two shapes, such as this one and this one, is this background of none. This is provided with the class of drop, which is on all of the top sections. All we need to do when the user drops the correct shape into the correct hole, is to remove this class of drop, and open our script. This is the correct section inside the if statement. What we're going to do is to grab our elements with e.target.classList. This class list has a method called remove, as in the class of drop, which would then remove this class including the background color, leaving the background color to be filled. Let's try this out. Drag one of these shapes into the correct hole. The shape is now removed from the bottom, and we now have the background color displaying inside the browser. Let's check if this is okay when we try an incorrect one. Good. This is now all working well, and if we take a look at the final version, the very last thing I want to do is to change the opacity when the shape has been dragged. For example, if we move this away, we can see the shape in the original place just here has now changed to be a lighter color. The same if we move red, we can see the lighter red shape has been left in place, and this lets the user know which shape they are currently dragging. We can do this by setting the opacity inside of our script, and we'll begin when we start to handle the drag start. First of all, select the element with e.targets.style.opacity. Well, we'll set the opacity to be equal to 0.5. Then we can copy this, and we'll set this back to one inside of handle drag end. We no longer need a console log, paste this in where we can set the value to be equal to one. Now since we're accessing the event information, we also need to pass this into our function. Save. Let's try this out and into our version. As soon as it begins to move one of our shapes, the shape which is now left in place is now a lot lighter. This is the drag and drop functionality now in place, and in the next one will improve this game by adding to the user score, handling the end of game, and also restarting the game 2 with our Play Again button.
57. Shape Drop Game: Handling The Score & End Of Game: The game is not functional in terms of the drag-and-drop. But to make it even better, we could keep track of the score and also reset the game at the end too. First, let's begin by tackling the score. At the top of the script, we need a variable to store this, so I'll jump to the very top and we'll create a variable using that and we'll initialize a score with a value of zero. Inside of our index, jump into this page, we already have a score section over the top. We've got the score text inside the level three heading. Now we have a span with the ID of score, which we are going to update inside of our script and a place to obtain the score is going to be inside of a handle drop section. Jump inside here. This is going to be where we check if the correct shape has been dropped inside of the if statement. If this is true, just above our return statement will access our score variable and increase this by the value of one. We then need to update our span section, so appears inside the browser. We can do this by grabbing document.querySelector as an ID of score. But I want to set the inner text to equal to our score variable. We can copy these two lines, well function and then we could do the opposite just below. If we remove the console log of incorrect and places outside the if statement, the only difference is we're going to deduct one from the score. Let's try this, refresh the browser, and if you try one of the correct shapes, this increases the score. Let's try a second number 2. This is all good and if we try an incorrect shape, drop this in the score is deducted by the value of one each time. Also, if we refresh the browser as soon as we begin the game, we also want to make sure that the current score is set to be zero. Since we already have our score to be initialized as the value of zero. We can also copy this update and we can set this just above our function, so refresh. This begins with the value zero. Try to drag a shape in, and this is still updated correctly. The next thing is this Play Button up at the very top. We only want to make sure that this is visible once the game has ended. Currently, if we refresh the page, we don't want to see the Play Again button because we can already start the game by dragging any of these shapes. We'll do outside of our functions at the top of the page is we'll begin by grabbing our button. Document.querySelector passing in a button. This is the element we used for the section just here and then we'll store this inside of a constant. Let's call this StartGameBtn. Initially, we need to access our start game button and set the display type to be equal to none. The style property of display equal to none. This will hide all button at the very start of the game. Then we're going to create two new functions. One function is going to handle what to do with the start of the game, and then a function to handle the end of the game. Function and game as you set these up for now. Then a second function just below, which is for start game. Start with the end game function and open up the curly braces and at the end of the game, we want to re-introduce button so the user can restart the game. All we need to do is to copy this line here where we set the display type and we'll replace this by changing this to be in line. Then inside of the start game function, we need to reset everything back to its original state. This includes the score. This includes removing the Play Again button and also moving these shapes back into position. We could do all this manually if you wanted to, or it will be a lot simpler if we refresh the page to give it the same effect. To do this, we need to access the Window Object, then select the current location, and then a method called reload. Now we've got our two functions, and actually we need to do is to actually call them at the right times. The start game is pretty simple, we just call it when the Play Again button is clicked. I have reference this inside of start game button to access this, and then we'll listen for a click by attend an event listener as in a click. Then we'll run our function, which is start game. The end game is a little bit more tricky. If we go over to the index.html and into the drag-section. Each time we successfully drag one of these into the same shape, such as this one just here. The div in the bottom section will then disappear. One by one, we're moving each one of these shapes. The game is basically over when the wrapper, which is the drag-section has no more child elements left. The drag we'll first begin by accessing our drag-section of the script. We'll do this inside of a handle drop. It has things out. We'll begin inside of a console log where we'll select our wrapper so document.querySelector. This has the class of drag-section and then our elements have access to a property by the number of child elements it contains, which is called childElementCount. At the end.childElementCount. I'll just make this a little bit bigger so it's more visible. Let's save this and test this out inside the browser. Open up the Developer Tools, jump into the console. Let's try this out, our console log is run at the start of the drop function. As soon as we drop any one of these shapes into place, if you then run the function and give us the value of 10. Our second one should be nine and the value is always one higher than the amount we see on the screen. Currently, we have the value of nine, we see eight elements on the screen. The reason why is because we're doing a console log of the top of the function before we actually remove this element. Effectively, the game is over when the current value is one. Instead of the console log, we can remove this and turn this into an if statement at the very end open up the curly braces and we'll check if this value is equal to one. If it is, we'll then call our end game function. Let's try this out, what we now want to do is to make sure that we get to the end of the game. Once we drop the last shape into place, we should now run the end game function, which will link it with access to the Play Again button. So refresh, and I'll go through each one of these one by one, making sure that all of these are correct. That's one, and if we dropped the last one into place, we now see the Play Again button has appeared at the top. We also could remove this border down at the bottom, but this is okay for now. We can just take this is working, the play again. The Play Again function will now reload our page and reinstate everything back to the original state. If you want to do if the border down at the very bottom, we can do is also in the end game function, we can grab the drag-section with document.querySelector. Since this is a class, we use dot and grab the drag-section. But the style, the border to be equal to the value of none. Let's try this one more time, access the start of the game. Complete this game by dragging all the shapes up to the top. Plus one, there we go. Our game now ended in the board has now been removed from the bottom of the page.