Modern JavaScript For Beginners: Part 1 | Chris Dixon | Skillshare
Drawer
Search

Playback Speed


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

Modern JavaScript For Beginners: Part 1

teacher avatar Chris Dixon, Web Developer & Online Teacher

Watch this class and thousands more

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

Watch this class and thousands more

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

Lessons in This Class

    • 1.

      Welcome To The Class!

      1:59

    • 2.

      Share Your Work On Skillshare!

      1:09

    • 3.

      Let's See What Javascript Can Do!

      11:12

    • 4.

      Download The Starter Files

      1:52

    • 5.

      Where To Add Javascript

      11:31

    • 6.

      Async & Defer

      8:15

    • 7.

      Working With Strings

      6:48

    • 8.

      Storing Data With Variables

      10:35

    • 9.

      Mixing Strings With Variables

      4:00

    • 10.

      Data Types: Numbers

      6:40

    • 11.

      Data Types: Boolean, Null & Undefined

      7:27

    • 12.

      Comments, Semi-colons & ASI

      8:15

    • 13.

      Operators: Assignment & Comparison

      9:29

    • 14.

      Operators: Logical & Arithmetic

      8:23

    • 15.

      Introduction To Arrays & Object Types

      5:33

    • 16.

      Introduction To Objects

      7:19

    • 17.

      Introduction To Functions

      13:22

    • 18.

      The Array Constructor

      5:22

    • 19.

      Introduction To Properties, Methods & The Prototype

      5:21

    • 20.

      Modifying Arrays

      12:07

    • 21.

      Returning New values

      9:21

    • 22.

      Iteration Methods

      14:29

    • 23.

      Reducers

      7:31

    • 24.

      Map & forEach

      9:36

    • 25.

      Array Destructuring

      4:27

    • 26.

      Unique Values With Set

      4:33

    • 27.

      Two Dimensional Arrays

      3:49

    • 28.

      The Global Object & Built In Functions

      9:40

    • 29.

      Function Expressions

      8:50

    • 30.

      Immediately Invoked Function Expressions

      5:58

    • 31.

      Anonymous Or Named?

      8:30

    • 32.

      A Function Or a Method?

      8:13

    • 33.

      Arrow Functions

      6:08

    • 34.

      Default Parameter Values & Using Rest

      8:02

    • 35.

      What Is The DOM?

      2:54

    • 36.

      Selecting Elements

      9:35

    • 37.

      Changing Values & Attributes

      14:00

    • 38.

      Changing An Elements CSS

      7:45

    • 39.

      Creating New Elements

      18:17

    • 40.

      Adding Elements To The Page

      7:06

    • 41.

      Cloning & Removing Elements

      4:04

    • 42.

      Mini Challenge

      1:42

    • 43.

      Looping With DOM Elements

      10:30

    • 44.

      Introduction To Events

      1:43

    • 45.

      Listening For Events

      10:42

    • 46.

      Listening For Multiple Events & Event Data

      8:07

    • 47.

      Event Propagation

      8:42

    • 48.

      Running Events Once

      1:51

    • 49.

      Preventing Default Behaviour & The Passive Option

      12:09

    • 50.

      Removing Event Listeners

      5:44

    • 51.

      HTML Collection or NodeList?

      6:02

    • 52.

      Mini Challenge: Create a Dark Mode Button

      8:24

    • 53.

      Video Player Project: Creating The UI

      14:41

    • 54.

      Video player Project: Video Events, Properties & Methods

      15:34

    • 55.

      Shape Drop Game: Creating The UI

      8:15

    • 56.

      Shape Drop Game: Drag & Drop Events

      13:47

    • 57.

      Shape Drop Game: Handling The Score & End Of Game

      8:27

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

Community Generated

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

4,031

Students

19

Projects

About This Class

Welcome to Modern JavaScript For Beginners!

Grab the starter files here.

Learning any new skill can be tough and Javascript is no exception!

Javascript has such a wide range of features and things it can do, meaning sometimes as beginners we have no idea where to even begin.

This is why I have created this class…

Working 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.

The class is beginner focused for anybody new to Javascript, or if you have a little experience and looking for an all round class to take you to the next level. You should have at least a little experience with HTML & CSS to get the most out of this class.

If you have not taken one of my classes before, my name is Chris and I have been building websites for over 20 years.

Alongside I have been teaching new developers for over 7 years, both in video classes and leading web development boot camps too.

This is part 1 of 2 and this will give you a great foundation in Javascript covering all the basics including arrays, functions, objects, events & the DOM, web API’s and all of the details you need to know in between.

All of these topics are covered in a clear and structured way, all while building practical projects as we go.

Including real world example use cases and mini challenges too.

At the end, we also put all of these skills together by building a working video player, including fully custom controls. And also a fun shape drop game using drag and drop.

It includes a project folder we will add to as we go, which will serve as a useful reference in the future too.

Thank you for your interest in this class, and I will see you in the first lesson…

Meet Your Teacher

Teacher Profile Image

Chris Dixon

Web Developer & Online Teacher

Top Teacher

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

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

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

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

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

Level: Beginner

Class Ratings

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

Why Join Skillshare?

Take award-winning Skillshare Original Classes

Each class has short lessons, hands-on projects

Your membership supports Skillshare teachers

Learn From Anywhere

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

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 differen