Transcripts
1. Class Introduction: Welcome, welcome, welcome my disk Kielce students to pluck 12 and JavaScript series. And in this plot, we're going to be discussing a vital term when it comes to JavaScript. And that term is functions. What are functions? Or functions allow you at its very basic scenes, to execute code again and again and again without rewriting the code. So for example, if you have to sign up buttons on the webpage and when a user clicks on a button, you want the same thing to happen. You don't want to duplicate code. You'd rather write one block of code rapid within a function and execute that function every time that the Sign Up button is clicked. That's just one example. So what are we going to cover in this particular class? We are going to be talking about what functions off. We're gonna be looking at the difference between function declarations and function expressions. We're going to be looking at the binding of the this keyword in JavaScript. We're going to be looking at the arrow syntax. We even going to be looking at in volts JavaScript functions, like the math function, that's going to be super, super interesting. So who is this last fall? The good news is, it is for all levels. If you are an experienced developer, I'm sure you're going to learn something new if you're just starting out. Don't stress, you know, my style already started the basics and I pulled upon it and I keep getting more and more thoughts. I'm super, super excited. I can't wait to see you in the very first data. Adios.
2. What is a function? : Welcome to the first lecture on functions. And as we kind of saw the direction analogy I gave you all a function is as a block of code that you can save and reuse later whenever you want. And as I mentioned previously, functions are the bread and butter of programming. You have to know how to deal with functions because you do not want to be duplicating code every time you want to perform a repetitive task. So what this means is that you write a function once and you can use it as many times in the future. And just as an FYI on the side, remember semi-colons, we did this in a Syntax section. Generally semi-colons are used to separate executable JavaScript statements. But since a function is not an executable statement, and by that I just mean it's not automatically run. You have to actually call it will invoke that, we'll see that shortly. And because of this, it's not common to end functions with a semicolon, although sometimes you'll even catch me doing it by mistake and other developers. So it's not the end of the world, but just bear in mind, you don't have to end a function with a semicolon. And as we just said, functions are not executed immediately, is you do get IFIS immediately invoked function expressions, but we're not getting into that now. In general, functions are not executed immediately. So how does a function look? How do we write it down? Well, firstly, you need to tell JavaScript that you are creating a function. How do you do that? Well, the simple answer is that we just use the function keyword. Now before I go further, there are a few ways you can create a function in JavaScript. We're going to look at them. But no matter which way you use, whichever method you use to create a function, these general concepts that I'm teaching in our applied to each different method. So if you understand what I'm teaching you now, you can apply this to any method of creating a function and you'll pick it up that much quicker. So here we're just going to use a function declaration. In order to declare function, we've got the function keyword, great, sonar JavaScript knows that we wanting to create a function. But you'll agree with me that we probably gonna wanna create hundreds, if not thousands, of functions in our application. For example, he might want to create one function that greets your user when he enters your page, you might want to create another function that determines whether he's a member or not. You might want to create another function to determine whether he's deactivating his account or not. And if he does, you want to give him another message or an alert. These are different functions and because of that, you need to distinguish between one function from another. You need to know which function to call which function you want to execute. And how do we do this? Well, that's right. We need to give our function a name so we know which function to execute when you need it. And let's call our function test for argument's sake. Now what's the next thing we need? Well, as you start developing, you'll wanna be passing arguments to this function. For example, what about if we wanted to give a welcome alert towel user? We don't want the alert to say, hi, random user. We would want the alert to say something like hi John, high 10x. And what allows us to do that as we have to pass in arguments, we have to pass in variables. And in order to pass in variables, you need to have parentheses. And that's a gas. You have a function keyword. We calling our function taste at customer. We can call it whatever we want. And then you have to have the parentheses. But now say we want to pass in the user's name. So let's just put that in a variable called name. And yes, it goes in between the parentheses. And what's the last thing we need to do? Well, if you just lift it at this, then.. JavaScript wouldn't know what to do. Great. We've defined the function, we'd call the taste. What's it going to do? What the moment it does nothing. And this is where curly braces come into it and don't get confused with objects. This is not an object when JavaScript sees at function keyword, it's going to know that those curly braces, or just a place where we define our code. And in programming, that place between the curly braces is just called a block, called a block of code. And that's with the meat and the heart of our JavaScript code will live. Continuing on with our example. Let's just alert hi to the user. And here we're going to use template literals, which we've seen in the Syntax section. And that's it. That is literally how you write a function. It's not that difficult route. It's intuitive, it's easy. And best of all, it makes a lot of sense. But at this point in time, we've only defined a function. We haven't run it, we haven't called it an in programming languages to run a function is known as invoking or calling that function. Again, don't get intimidated by these words. That's all invoking means. But let's jump in and see how we actually invoke this function. So as I mentioned, invoking a function just means running it or executing it. Let's look at our function again, function test, where we just alert hi name to remind you that taste is just a custom name we gave to our function. We can call it whatever we want. And how do we run this function? Will we take our name, in this case, taste? All we do is we follow it by parentheses. It is that simple. You are not telling the JavaScript engine to go and run this function. But hang on. We did define that this function needs a variable called name, an argument called name. So let's do that. Let's just put in men. And that's it. That is all you do to invoke a function. Great, we've covered the theory that now, as always, let's see some examples.
3. Invoking vs returning a function: Before we move on, just a very quick example, Remember how we just said that to invoke a function, you need to do the double parentheses. Or what happens if you don't include the double parentheses? Let me show you. Solidify now function called wolf. And all Wolff does as console logs to the screen. Now if we don't include the parentheses, what's going to happen? Linux instances not going to execute the function, it will literally return the function itself to you. So just bear that in mind if you wanting to create instances of this function and put it into variables, make sure you don't put the parentheses behind because as soon as you put the parentheses behind, it executes the function. Let me show you. If we go off and we put in parentheses, what's going to happen? Well, let's going to console log to the screen, how they make sense. But there's plenty more to go. Let's get on with it.
4. Fun lecture - click and change text: Functions, we'll see some examples. Actually want to show you two examples. Now, one will be relatively simple, the other one is going to be a bit more complex because now I kinda feel you getting into it. I feel like you really and I'm going to be structuring files as we would in a real website. So you can also get a feel as to how we link JavaScript with our HTML. Okay, example number one, I just wanted to have simple text. When we click on that text, I want it to be replaced with other text and I want to do that by writing a function. So yeah, I've just got a blank Visual Studio Code document. All we need to do now is let's create a folder and let's call it our project. Let's say it's four J under no function. Because the old stuff, Project function in name, let's have an index dot HTML file because that's way apostle begins. We have to start here. And this is create a standard HTML template in our body that's creates a header. We'll call it function example. Let's have a paragraph. This is an example of changing text via a function. Changing text by using a function credits. And if we click on OK. Go Live server, then we display this in a website. This is what we see function example. This is an example of changing text. Great, that if I click anyway, nothing happens. So going back to our text editor, what do we need to do now will now need to create a JavaScript file. And let's say within this big folder structure, we've got another folder called public. And within that folder, you've got your script file. We, we write all our JavaScript. And now I want us to create a function that just replaces taste. And remember, what do we need in order to create a function? Let's raccoons tell JavaScript that we are writing a function, so we use the function keyword. Now we need to name our function. It's just cool it show because we want to show takes. Remember we need the parentheses after the name, just in case we want to parse through arguments. And then we've got to actually write our code in between curly parentheses. And all we wanna do is we wanna document.write ISL function. As been invoked. Walden. And he's a function that again, if we go back here, it's not going to work because we haven't yet made the link between our index HTML page, clicking this paragraph, hen our JavaScript file. So let's do that. Let's go back. Yeah, it's good. Our index file. And once the pasta's gone through our entire HDL and all of that is loaded on screen. It's then going to hit this script tag. And the script tag is going to reference our JavaScript file. So it's in the public folder and within the public folder and a file called script.js. So what's great about this is if we go to our website and we refresh stall clicking doesn't do anything because we haven't told the browser that when we click, we want that function to be executed. A chicken. This, This is cool. If we inspect this document, then you go to your Network tab and we refresh. You can see that our script file is being loaded. If you click on the script file yet GCF function that we've written within it in radishes. A bit of interesting information for you. Now, let's make the link between ticking this text and this takes changing. So if we go back to our editor and we look at this paragraph text, this paragraph is where we went out JavaScript to be triggered. Within here, we can define an on click event and list just execute our show function. Bear in mind that with an onclick event, anything in nice quotation marks is JavaScript. So we don't even have to refresh show. For example, let's just do an alert. We can, we can write JavaScript directly within these quotation marks. And if we go back here and we click on here, these are alert. So it's working. If we go back to our file, we don't execute the alert. We actually want to execute our own custom function called show, which is in our JavaScript file over here. And if we go here and we click, there we go. Document.write. The whole text has been replaced by our function, has been invoked, well-done. So I hope this is making scenes. We started with an index HTML file. We've defined our paragraph, we've referenced now.
5. Fun - display a random quote: What about if we want a button and every time you hit that button, you want the paragraph text to change. So say we've got four or five quotes. Every time you hit that button, thickness, randomly select one of those quotes and display it to the screen. How would we do that? Let's do it together. So the first step is let's create a brand new folder. And it's called us project function advanced. Ok, within, yeah, let's have an index.html file. We've been through this, we know that this is where we have to begin create a standard template. And here let's have a button. And let's call this button show quote. And now wants a container where we can show the quotes n. So let's just have a paragraph tag for now. We see this online. Let's just have a look at what it looks like. We should just see an empty button that does nothing when we click. So show quote, nothing happens. We haven't defined anything yet, but we know we've got a button below the button. We're going to have a paragraph tag that is now empty, but that's going to be showing our quotes. Let's go back to our editor and let's work on our quote. So let's create again. Let's just say we've got a public folder. And within the public folder, let's say we've got your script, your JavaScript, where we rattle our JavaScript. And in here we want to show up quite so let's define a function. We start with the function keyword, we call it, now whatever we want. Let's just call it show quote n within the curly braces. That's where we have all our code, our meat. And this is way we going to be getting into using different data types that we've learned? This is why it's important we learned those things previously unknown now. So the first step is we need a place to store all of our quotes into. We would we do that? How would we do that? Remember, quotes are just strings. String datatype. How can we stall multiple quotes is in an array, cuz an array stores multiple values. So let's call our array quotes. And it start off by making our new array empty. We haven't got any quotes in the neat. And now let's add our quotes. How do we add quotes? Will we call our array? We state that the first item in the array, and remember, it starts with index 0 because it references where in memory we're going to access this from a now it's 0, we're gonna access it directly from its very starting point, which is white 0. First quote is, when you reach the, the end of your rope, tie a knot in it. And let's add another quote. At another quote, we access our new array, which now has one item in it. And now we want it to be the second item in the array. And this quote can be, is nothing permanent but change? Is nothing permanent. But let's add another quote. We access our array. Now is saying we want it to be the third element. And let this quote BY something else. Say luck is a dividend of sweet. And let's just do one more axis, our array. We want this to be the fourth element in the array. And this quote can just be, it's, takes as much energy to wish as it does to flat. So there we go. We've got our quotes, we've got four quotes within this array. Now what we want it to do is we just wanting to display them randomly when this show quote function is executed, when it's invoked. How do you do that? Well, we need to create a random number between 03 to access each one of these quotes. How they do that will let me write down first, then I'll explain to you what it is we've done images, get rid of this year. So all we're gonna do is define a random variable that keeps changing. And this random variable will be the one that calls our quotes array. So in effect, it's, this rand is going to replace these numbers, 012 or three, that randomly a number that keeps changing. It's all we're trying to do. We can access JavaScript's math object. And we're going to access the full method on it, which just makes it around whole number. Otherwise, it's going to produce random numbers that are not a whole number and we won't be able to access it in our array. That's all that this floor function does. Then we're going to make excess JavaScript's math random function. And because math dot random produces number between 01, we need to multiply by our array length in order to allow this random variable to take values. The same length is our array. So that's why we're going to multiply by the quotes length. And that's it. We've literally defined our random variable. Now, what is the last step? Let me just comment this. You know what's happening? Create a random number between 03 and now. What do we have to do? Well now we've got an XY is our paragraph. Remember that paragraph tag? Show you again in the index file, we've got this paragraph tag. We want to display the quote in that paragraph tag. Sir. Yeah, we have to identify the paragraph tag and insert our quote inside it. Okay, great, so how do we identify the paragraph tag? Well, we've done this in one of the previous lectures. But just to remind you, JavaScript has an inbuilt getElementsByTagName method, and that method can be accessed on the document object. So getElementsByTagName. We wanna get the paragraph. And remember what I said before, this produces a node list. So we have, we have to actually access the first item on this list. Then we want to change the inner HTML attribute of this paragraph. And we want that to be equal to what? That's right. We access our array of quotes and we pass in this random variable. And this should be at the should work. Let me just explain all actually firstly, let's see if it works and then I'll explain how this whole Math Floor math random thing works. So let's go to our index page. If we go back to our website and we click this, nothing's going to happen because we haven't drawn a link between clicking this button in executing that function, which is why we've got to go back to our index page. First thing we need to do is reference our script file. And that's in the public folder, and it's in a file called script.js. Now, all we have to do is we have to define when the function is called and we're gonna do that whenever the button is clicked. So we insert an onclick event on this button. And now we need to execute our function. What did we call our function will have a look. We call that function show quirk. So we need to go back to our index file and we need to execute. Sure, quit. Whenever that button is clicked. But see if this works. Let's go to the website. Refresh. Click on show awkward. In the ego paragraph gets the quote inserted into it. Nothing permanent but change. And every time I click on this quote, it changes. How awesome is this? To understand our powerful functions all we don't have to rewrite code every time you click a button. It's just executing that function again and again and again. Okay, so you're probably wondering how did this math function work over here. Rent, Math.floor, math dot random. What does all this?
6. Math.random: Okay, so it show you what method random is. Let's just create a new file very quickly. And now this is a long lecture, so I won't be OMP long. We'll just call it Meteor.js. Let's just close everything else. Just explained the general concept of what we've done. I want to start co-occur. And now let me show you what it is we did. Firstly, what does math dot random dude, it's inbuilt into JavaScript. So we had access to this object automatically. Let's just say late number equal math.pi, random and late console modus number. The Yeager and he read Tommy, save the file, we get a new random number. But you'll notice that these numbers are between 01. So when we have our array, and it's just delicious, say LIT array equals 135. To access these, we have to either use 01 or two. For example, if I wanted a console, log out the first element in, inside the brackets, square brackets, I have to have whole integers. In this case, I either have to have 0. One would do. And that retrieves the value out of that array. So you agree with me already with conscious use number because number and upkeep saving now, so you can see it's always between 01. So that's precisely why we multiplied the math.pi random by number. And what number should we multiply by? Well, we had four quotes, so we multiplied it by four. We console log array.length. Here we've got three, but to keep it similar to the previous example, I'll show you this. Just put one more. Now we've got full. So we multiply this by four, but instead of actually writing the number four, we just say it again. Well, let's just multiply it by its length. Now we know that the largest number, this can be as full, a smallest number, this can be a 0. You with me so far greater. But now, can you see how these produce such random numbers? If we tried to go array and we tried to access a number like this, weren't able to, doesn't exist. It has to be a whole number. And that's why we use Math.floor. And the Math.floor always returns the largest integer less than or equal to as a number. So for example, on the screen at the moment we see numbers 2.940 using meth floor just return to sustain to make scenes. So all we did was we included a Math.floor function in front of a whole description here. And the UGA. So now the number variable will always be between 03. How awesome is that? That's exactly what we did, which allowed us to access all the elements in the array. Hope is making sense. Let's move on.
7. What is the RETURN keyword: The return keyword is important to understand. But why? We'll take a look. Let's create a function that just adds a and b. Remember to credit function, we need the function keyword. Now we need to name it. Let's just call it add. And let's add two numbers, a and b that will pass into the function. And look at this. I'm gonna return. Javascript understands what this means and I'm going to explain shortly what it means. And we're going to return a plus b. And if we execute this function, it's dot co-occur. And let's add 510. And its console is loud, console log. They regard. It comes up with an answer of 15, as we would expect. But what does this return keyword actually mean? Let's have a look. There are turned keyword simply aims execution and you guessed it returns a value. What about if these narrow to invade in that instance, undefined as returned, not now, undefined. And something else to bear in mind is that the return statement is affected by automatic semicolon insertion. What I mean, let's take our function example where it returns a plus B. If we had to write return and on a new line, we wrote a plus B. What's going to happen? Will the parser is going to interpret that is returned semicolon and name a plus b semi-colon. And the important point to realize with this is that the a plus b in this instance would be an reachable. So how can we return something that spread across multiple lines? Well, in that case, you just need to enclose it in parenthesis. That would work. Let's have a look at another example quickly. All right, so a few more examples on the return keyword. Remember how we said that when you use the return keyword at stops the execution of the function. What does that mean? Well, that firstly means if we've got other variables, we define hairless equals ten, d equals 20, and we console log c plus d. You can really see my IDE is kind of grayed out these statements. And the reason it's great disasters that these are not going to be executed. If we add 510 again at stall shows us 15. If we wanted to see both, we would have to then reposition these above the return statement. Only now does it console log c plus d and return 15. And you must always just be careful with return keyword. Because if you don't have it, it can cause weird things. What I mean, let's get a plank. Remember clunker, we haven't used that for a while. Just on the homepage and remix clicking this new button here. And we can just default to a standard empty HTML, CSS, and JavaScript file. And what's nice about Planck is on the left you can kind of see you project file layout. You can kind of see you sit up, you've got your index file. And if we click on our index file, you can see it references the JavaScript file within the lib folder. It's just a nice overview for you. It's nice to see how everything fits in. But now what I wanna do is I want to create in the index file, let's just create a paragraph with ID demo. So all I'm wanting to do, and in our JavaScript file, which we know is already referenced in our index file. So we know this is going to be executed. Let's define a function called test. And in taste we're going to pass in a variable name an argument. Remember how we saw this example earlier? And here all I wanna do is I wanna write into that paragraph Hello Neighbor. It's all we wanted to do. So now we've defined our function. All we need to do now's access their paragraph tag and insert this text into it. So how do we access a paragraph tag? We remember, we start off with the document because that's the overarching application. We access an inbuilt method on that get element by ID. And then we can write whatever we want inside it. So here we're going to start with document. Get element by ID, in this case the ID Decebalus demo. And in there we wonder right within its inner HTML, we want to execute this function and let's say the user's Wally. Now all we need to do is preview this. You can see is hello clunker. There was inserted in the index.HTML file, and there we go and find. It's another reason why if you don't have the return keyword, Remember what I said? It returns undefined. I've just proven a two-year And this is weird. You think Ys and not returning Hello 10x. And the reason is, as you guessed it, you need the return keyword. So if we now return hello name and it refreshes, we should get hello dolly and we do the eager. And one more example. Let's just open up Chrome's console. And he has another example is creative function. Let's call our function taste for lack of a better word. And in, yeah, let's just define a dog. And let's say his name's doggy. Okay. Now, if I run this function, what do you expect to be returned? Which we haven't included the return keyword. So yes, I'd expect undefined to be thrown. And that's exactly what happened. So what about if we create another function? And let's just call it tastes too. And I'm not being very creative here with the names. And it's highly doped to equal worth. Now instead of closing and ending the function, let's put in that return keyword. And what do we want? Return will, let's just say we want the dog to return here D2, which is its name. So when I run taste to what do you think should happen now? It's right, we should see we're fourth. Th, two will fourth. So these were just three quick examples of how the return keyword can affect the outcome of your function execution to the speed at a mine. It's quite an important point to note. Let's move on.
8. 2 types of functions - declaration vs expression: Now before we move on, which is going to have a quick look at the types of functions. Remember what objects there were different ways to create an objects. We had literals, we had constructors, we had the create method, we had the class, or the same with functions. We've got different ways to create a function. But what's nice is it's here. It's bit more simple because there are only two ways to define a function in JavaScript. We've got a declaration and we have an expression. The declaration we've been seeing often through our examples that when we have the function keyword, then we have the name of our function yet say hi, we've got the PR indices where we pass in a parameter. And then we've got the curly braces where we actually define our function here. We just defining Hai Nan by using template literals. So that's a function declaration. Well, how would we write the same function but using a function expression? Well, yeah, you can see how similar it is. We just define a variable called sayHi and we assign net the function. You can see in both instances, we have to use the function keyword is this arrow syntax which we're gonna get onto you. But before we get onto that, you can see the traditional way to create both functions means that we had to use the function keyword. So let's just dive into these in a bit more detail. We've got a function declaration on the lift and melodic function expression on the right. And the meaning of both these functions are exactly the same. And by that, I just mean that both created function and they stole it function in a variable called a variable. Say hi. So you're probably asking, well then why have one method over the other? And the answer is there's a more subtle difference. And that difference is the timing of when the function is created. And a function can be created immediately or later. And with a function declaration, it's created immediately. And with a function expression, it's only created, It's called. And I'm gonna show you examples of what this means in the next lecture. So don't worry if you don't fully understand what this means now that just at a very, very high level, that just means that the function declaration, you can actually call the function even though you've defined it later on in your code. Okay, but now let's look at function expressions in a little bit more detail. The first thing you'll notice is that you can store the function in a variable. How we've called it, say hi. And the other thing to bear in mind is x_k with function expressions. Do you notice how we don't give the actual function and m? Look at the function declaration where we say function and we follow that by the function name called sayHi. Yeah, we just define a function. Well, in programming jargon, that's just known as an anonymous function, is just a function without a name. We kind of have given it a name because we put it in a variable that we haven't directly given the function a name like we have for the function declaration. And one of the other massive advantages with a function expression is an iffy. And again, don't get intimidated by these weird word. All that means is that when you want to use a function once, you often do it via method called iffy immediately invoked function expression. That's what it stands for. And I don't want to be getting into immediately invoked function expressions right now. If you're anything like me, you don't want to be curious as to what this actually means for the sake of scratching at each. Let me just give you a quick example. Say we have a paragraph element with an ID of taste in our HTML. And all we wanna do is we want JavaScript to run code that places a string called the Yj in their paragraph. How do we go about doing that? Well, of course, we first need to start off with the script tag. Dean Leeds, define a function expression. We are not doing a declaration here. We're doing a function expression. We're going to access JavaScript's document object, which is your overall webpage. And in UNEP document, we automatically get access to a get element by ID method. The ID, we want a good taste, and then we want to change its inner HTML to yea. So there you go. These are function expression. We close the script tag and we done. But the problem with this is we haven't called this function heavy. We've now just define a function expression. So with an immediately invoked function expression, we want to tell the engine to run this immediately, automatically. How we go about doing that, we'll, all you have to do is you have to enclose your code in parentheses. And then you go, you've told JavaScript this is an iffy and execute a function. Remember what we had to do? They track, we had to follow that function by parentheses. And it's the same thing with an iffy. You follow the function with parentheses and Bob's your uncle. You've just created your first self invoking function. So let me show you a few examples now, practical examples of the differences between an expression and a function declaration.
9. Function declarations vs function expressions: Function expressions on the one hand, function declarations on other, Johann, this can get quite confusing. So I just thought limit resonant examples at you. Let's first look at a function declaration because that's what we used to function declaration. And let's just have a function called dog, that console logs it sound. What's the first step with the function declaration? We have to tell JavaScript that we're about to define a function in. We need to call a function something. So let's call it talk. We need the parentheses because we may want to pass arguments to a letter. And then we define our code within the curly braces, say sound equals. And then all we wanna do is we want to console log the sound to the screen. And to execute or to invoke this function, what do we need to do? That's right, we need to use our same name, an include, parenthesis. And then you go console logs. So that's the function declaration. We've been seeing a lot of function declarations. We should be comfortable with that. Bonobo, what about a function expression? Let's have a look. Function. Function expression will, the biggest syntactical difference in how it looks is that we putting it into a variable and it's an anonymous function, that's ever luck. So let's define ket. And there can be a function. But now in this case, bear in mind, we haven't called our function anything, and that's why it's called an anonymous function. In the function declaration above, we add function and we called our function dog. Yeah, we just have a function that we are assigning it to a variable called cat. So it's almost the same thing. It's just structured differently. And let's do the same thing later. Sound meow. And we want to console log the South. Nothing new there into execute a function expression. Again, we just use the name of our variable and we enclose it in parentheses. Miao, Hou. So then he probably thinking, Okay, cool, they both look kind of similar. They feel the same. Why have to waste to declare a function? Isn't this just any more confusion? Will it isn't as isn't. It depends what you want to do with these functions. And like we just said in the lecture, the main difference is the timing of when you can use these functions. Let me show you. So let's just scroll down. And let me just say timing is the main difference. So function declarations can be used in the entire scope. And what I mean by that is, let's just say function Declaration's can be used in its entire scope. And yeah, we're just going to be dealing with the global scope. And I'll show you an example. This just returned to us say hi function and said if we want to pass in the user's name and just console log a welcome message. So the first step of the function declaration is to tell JavaScript recreating a function by the function keyword. We call it, say hi, we call it whatever we want. In this instance, we want to pass in a name and then we write our code in-between these curly braces. And all we wanna do here is we want to console log. And we're going to use template literals. And we're just going to say hi, name, reasonable function. And let's invoke the function. Let's see what happens. Say hi and we pass in Tang. And yes, it's gonna console log. Hi Tom. But let me ask you this, what happens if we executed that function? The four even declared the function? What's going to happen? Well, look at the comic function declarations can be used in its entire scope. She had global. So if we move the say hi Tom to the top, it's going to work because the parser, when it hits this function, when it's passing the file, even before it's executed and rendered to the screen. It's gonna have already stored the say hi function. That's going to know exactly what that function is. So when you go and call it, even before we've defined it in our code, it will be valid code, what happens with function expressions? Will function expressions. Function expressions are accessible and usable when it is defined. And what I mean by this, well, let's create exactly the same function. Instead of say hi, let's just call it, say bye. So we're gonna say, say By equals function, an anonymous function, because now we haven't named this function. It's going to be paused in the name. And here we just want to console log using template literals by. And they name. Again a very simple function. And if you wanting to execute, say bye with the word Tom, it works. Everything at this point works. And you wouldn't have any preference to use one or the other in this scenario. But what happens if we execute that? We try and execute, say buy before we've declared the variable, before we declared the function. Let's have a look. Let's move this up and knock we're being thrown in Iraq. Say bi is not defined. And that is the point I'm trying to make with this. We cannot access function expressions before it is declared. Just y, let us happen. I don't know. It just weren't just going to deal with it. Cool. And let's carry on.
10. Functions are like values: This is just gonna be a quick lecture this evening. I wanted to mention the net is functions in JavaScript are available. And what it means is that we can deal with them. And that sounds strange, but we can deal with him as a value. And all I mean by that is you can throw functions around, you can pass them into other functions. You can assign him to variables. And this makes functions in JavaScript awesome an unmatched with his other languages aren't as flexible. You can't do this with functions. Let me show you what I mean. I'll just give you an example of assigning a function into a variable. We can define any function we went. So let's just work with a function declaration because it's very easy and intuitive to do these and excludes function dog. And this is just going to console log. Well, nothing new then. But now we can treat this function as a value and assign it to another variable. How awesome stuff. So we can literally go LET sausage dog, dog. And now at this point in time, sausage dogs heads been assigned the value of that function. So to execute this Voc, I'll function. We use the normal parentheses. Cell, it's X's are sausage dog. And executed. The ego console logs wealth. And of course, we've got the sausage dog, but we also have our dog function which we can execute. And that also executes with to the console and they have it. I just wanted to show you this before we move on because I know this might seem simple, but it has profound impacts on you and I as developers because JavaScript's awesome like us, it allows us so much flexibility to work with functions and throw them around and put them into variables really is great. So before we went on to more complicated things, I just wanted to share this with you.
11. The new ARROW syntax explained: This section on functions would not be complete if we didn't discuss arrow functions. Error functions are just a concise way, a quick way to define function expressions. And is one of the most practical changes introduced by ES6 or ES 2015. And the way I like to see it is that it introduces two major benefits. Benefit number one, which is the most intuitive and obvious one, It's just shorter to write, takes us less time and it's easier. Let's take our say hi function expression. We know how that's written. We've seen this before. So you can see with arrow syntax, we taking double parentheses and we put all our arguments in NY, we use the arrow syntax. And then we define our code in the curly braces. So it's very similar to the old way. It's just a little bit quicker. But depending on what we wanna do with our code, we can even simplify it further. For example, if you have no parameters, meaning we're not wanting to pass in variables or arguments, then you can do this. Let me show you an example. If you don't have perimeters, creating function expressions via the arrow syntax is super-simple. Let's have a look. Let's define a variable called sayHi. And now ordinarily, we would have to now include the keyword function. Yeah, wouldn't we? Not with error syntax. That's what's so cool. We can just have opening and closing brackets. We now have to include the arrow syntax. And then we have opening and closing curly brackets once again. And this is just going to console log highly. And now, what have I done wrong here? For the brackets, console log, say high ego, and if I execute, say hi, it console logs, hi there. No problem with that. But we don't even have to have the opening, closing brackets, Dewey. We can just have the underscore and other examples. Let's go let say by equal. And yeah, you can just have the underscore. Can't be much simpler. Net cannot have the arrow syntax, the opening and closing curly brackets. And yeah, we're just going to console log by the. And that's at, if we execute this function expression, we get pi Day. Or if you have one parameter in the opening brackets or even optional, you don't even have to have opening brackets. Let me show you another example. Okey-dokey. What about if you only have one parameter? Well, it's very simple. It's defined a variable again called sayHi. Remember ordinarily now we would need the function keyword, but because we're using error syntax, we're replacing that with the error. So what do we do? Well, when you've got one parameter, you don't even need opening and closing parentheses. You can just write the argument, Use the arrow syntax. And again, our opinion closing curly brackets. And then now all we wanna do is console log in will use template literals. High. Named. There you go. We've literally done it. We've replaced the whole complicated and cumbersome way of function expressions into one line. And we can console out this out to see if it works. And it says, hi, undefined. Oh, we forgot to pass in a name. We pass in the name of wildly NSA's highway. So we know that works. And the most simple way we can draw it as if we are only returning an expression. We don't even have to have the curly braces. Let's have a look at a quick example of what that looks like. And now, if you are a turning an expression only, you don't even need curly brackets. How insane is that? Let me give you another example. So let's say we have a function expression and we have a, we're going to put that into a variable could add. Now ordinarily would need to put function. We don't have to put function could be using arrow syntax. Say we've got two arguments, num1 and num2. And all you wanting to do now is we wanted to return the addition of these two. So you and I both know ordinarily we would put it in curly brackets and we can. But the point is with arrow syntax, we can do away with that because now we're just returning an expression. We are returning null m1 plus m2. And I mean, that is just so elegant, isn't it? It's beautiful. It's like art. And if we execute this function and we pass in 12, we get back three, the ego, the habit, the aerosol index is much, much easier to use. Okay, so those are some syntactical differences with the arrow syntax, but now something a bit more meaningful. Benefit number two, there is no binding of this keyword. This is so crucial. The error function does not bind. Thus. And of course, this is theory. Let me show you exactly what this means.
12. What does binding of THIS mean?: What is this keyword will about? What do we, what are we doing? How does it work, and what does the error syntax soul for us? What does it mean when it says that there is no binding of this? Let's have a look at what this all means. But let's start at a very simple constructor function. Remember, with a extractor function, the value of this is bound to the newly created object being created. And this makes sense, right? Well, let's create a Person constructor function where we sit this name equal. And remember what the second step was with a constructor function. It was to use the new keyword, that tribe. And when we do that, when we say let user equals new person, what we're actually doing is the value of this is being bound to the newly created object to that means when we refer to this in our function call, this is referring to the user, the newly created object. And if we console log user out, we can see that we've now set this name property, which is name of user to Molly. So that makes sense, you know this. But now let's dig deeper. Let's now sit a timer using set interval and sit intervals in bulk JavaScript function. We'll see how it works now. So let's comment this out so we don't get conflicting variable names. And again, let's define Harrison function. And let's say this firstName is boiling. And now what I wanna do is I just want to say for even go and use what? I just want to console log hi, every 1 second to the console. How would we do that? We'll just define a method called display. And we'll make that equal to JavaScript in Bolt sit interval. And you can see my IDE has really picked it up for me. I'm set interval. So how sick interval works as you've gotta have parenthesis and you can see my IDs already saying that the first argument has to be our handler. In other words, it's going to be our function. It's called a recipient. Tissues have a function that's called sheriff. We can call it whatever we want. It actually doesn't matter in this instance. And we went to console, log to the screen. Hi, so we're gonna do for now. And the second argument in this set interval function. And if I just put a comma ID already tells me it's the timeout. That's how many seconds dominant labs before this function gets called again. And this is in milliseconds. 100 milliseconds is 1 second. And they have it. He has our function. What's going to happen though when we create a new object and we execute this, let's have a look. So let user equals mu person. And what I'm gonna do now actually is I want to put this in Google Chrome's console, just going to be easier for us to see the results of us. So yeah, yoga, he has our console. So all I wanna do is I want to copy this function. Let's go to our console and it's pasted in here. And what's going to happen now is every second high is going to be displayed to the console. And you can see that's exactly what's happening. It's what we would expect. But what happens if we wanted to display? The firstname, Wally, every secret. Do you think we could do that? Yeah. By the way, in case you're wondering why this has been executed every second, just take a step back and think about what it is we've done. We've defined a constructor function. We've defined a new user, and we have executed this constructor function. The problem is with the SEC interval is like when the parcel goes through it and executed, it never stops. We haven't even defined it to stop to Sue's going to continue indefinitely. Anyway. Getting back to the point at hand, what happens if we wanted to display not high but high volume? So we wanted to access the firstname. Well, your first thought might be OK, cool. Let's just use template literals and going in console log and go high. And we log out this firstname, right? Kinda make scenes that seemed let's copy this function. That's good. Our console again stopped us in clear the console. Now let's paste our newly-created function. What's going to happen? Hi, undefined. And this is the point I'm trying to make with function expressions. This seat interval method is just a normal function. There's nothing special about it. But what's happening is that this keyword is being set to the global object, is not being sent to the newly created object at almost ignores the current scope it's in. And it just references this as to the global object. And let me prove this to you, not which gave a talk on top. And now remember how I said that within this function expression, that this keyword, when we use a function expression that's referencing the global object, will let me prove that to you. And to prove it to you, or we need to do is get rid of it. She just get rid of the whole console boat and just control this. So we doing. And let's copy that expression and it's pasted in Google Chrome. Now what's going to happen? The ego, this is the window object that's being consoled every second to the screen. Again, back to the console. So we are back in the console and we know what the problem is. We don't want this to be bound to the global object. We almost want this. Women, almost we do want this to be bound to the original context. We don't want it replace by needing us. And that is exactly what we mean when we say the arrow syntax does not bind this. So say now we wanted this to be bound in its original context. This is the whole point of an arrow syntax. So let me show you, instead of having this syntax function show, let's replace it with arrow syntax. So we don't need the function and we don't even need to name it. All. We need opening and closing parenthesis and the error. That's the only change we need to make. Now if we copy this function and we paste this in the browser, still going from our previous example. Let's refresh the page. Clear the console, paste dysfunction in need. What's going to happen now? This is perfect because now we have console logging the newly created user object. And let's just stop this again. Let me refresh the page. Clear the console. We go back here. Now we are able to use literal syntax. And we can say, hi, this firstName. And we copy this, paste it in our browser. We should get hi Wally, every single second. How amazing as us and I hope that sunk in that this is what the error syntax is doing. If we go back to our console is just one more thing I want to show you. Another way to prove that this is pointing to the person object is within our function expression. Yeah, after we define first Nemo, even before it doesn't matter, we can just say late scope equal this. And what we can do is we can console log scope equal to the, this keyword. Do these two equal. And again, let's copy this. Paste it in our console. Will dishes clear at first, pasted in our console. And we should get true. And we do. So there you go, there you have it. We've gone in depth as to what this means and the arrow syntax and how it impacts the this keyword. I hope you've had fun.
13. Recap time: Who, sir, we've learned an incredible amount in a short space of time. And sometimes it's just good to take a breather step back and figure out where everything fits in. So that's what I thought this would be a very, very quick recap. Often people get confused between variables, objects, and functions. Let's just see what they offer them. Variables member, we said we should be using constant. Let it, this is the new syntax introduced by ES6, const and late or variables. And all a variable is, is a container to store a piece of information. Think about in your pantry. You put food in a container. You label that container and you put it on the shelf. That is all a variable, is just a container. When we use const, we know that we don't want that to ever change, for example, my name. But when you use the let keyword, you stating that you actually can reassign that variable if you want to. So for example, every year your age is going to change. Stats variable, you've got that covered. What about an object? Or an object is also kind of like a container. But it doesn't just store one value that stores a whole lot of name value pairs and you separate each name value pair by common. We've seen this. And to define an object, you have to use those curly brackets. That's what tells JavaScript, hey, this is an object treated as an object. And finally we have functions which we've just been through. And a function and I like to think of as a doing word that does something. And we learned about the new arrow syntax. And we learned that the different ways to define a function are you looking at now where we say let with and we've used the arrow syntax, that's a function expression. And we've seen we should be using the return keyword aims the execution of the function. And how do we invoke a function? How do we call it? How do we execute it? Can you see all of these names are just fancy words, but they all mean the same thing. Well, to invoke the function with, we have to use the name off because we have to tell JavaScript which function we want to call. And then we just follow that by parenthesis. And that's it. So take a step back, look at these on one piece of paper. Have a bird's eye view. And then you can kind of start to feel why we need all three. We can't just do away with one. Hope this has been really, really cool section. And I hope you've enjoyed the course. I've had a tremendous amount of fun putting it together. I love the stuff. And the good news is, we are not yet finished. I'll see you soon.
14. toLowerCase() method - intro: Who I guess what I just heard this morning from our very first time, I did a yoga session and I'm shattered. We did this thing called, I think was called the Bird of Paradise. Pyres blew my mind. So anyway, I'm in a lot of pain right now. But that should not stop us learning about JavaScript. And very specifically, I want us to learn about this method called two lower case. It sounds simple, but I just want you to understand exactly how it works because it's a very, very useful method provided to us straight out of the box by JavaScript. Now although it doesn't take any arguments, it is a super practical method. Why? Well, in many cases, you want your text or you want your strings to be case insensitive. Aka, You don't want capitals to a fake, whatever it is you're doing. For example, if you've got a list and a user types in a certain word, sometimes you want to see or you want to compare whether that word is in the list and you don't want capitals to ruin your formulas. In that case, why not just convert everything to lowercase? And in order to do that, if we use the two lowercase emitted. So without further ado, let's jump into the presentation quickly and let's start talking about the two lowercase method enjoying. So what exactly is this toLowerCase method? Very simplistically all it does, and it's very intuitive. It converts your taste all into lowercase. In other words, the toLowerCase method returns the calling string, the string you've called it on. It converts that strings value all into lowercase. And I could just stop here, but I want you to know just a little bit more about those toLowerCase method. Firstly, it is a JavaScript function that's provided to us by the JavaScript language. Seconds IQ does not take any arguments, but don't let that fool you. It's still a very powerful method. And what I really want you to understand yet, and I want to pause on this point, is that the toLowerCase method does not alter the original string. Instead, it generates the new modified string. Yeast was all lowercase letters. Let me hop over to the console and let me show you what I mean by this. Okay, so we know that the lowercase method does not affect the original string. I just want to prove it to you now, how am I going to do then? We'll, let's create a string and let's just call it a sentence original. And this just say, make that equal to crazy frogs or just, well, you know, crazy. How's that? And then let's create a new sentence. So this cool it sentence lower. And yeah, I want us to access our original sentence. And this is what I want us to do next on one axis, the two lower case method. And what's really awesome is that because we have a string and this sentence original is taut string, we automatically have access to JavaScripts toLowerCase method. How do we access it? Will we exit with the dot notation? And of course, we can just start typing toLowerCase and our IDE already picks up this method. So I can just click Tab. Open and closed parentheses to execute that method. And we are done and dusted. Now, I can open up a browser and we can console log things to the screen. But I want to use something called Crocker. We go to my extinctions tab here. And I just start typing Crocker. And you can see I've installed co-occur in my IDE. It's really, really useful, so highly recommended. And all we need to do to run Crocker is we literally call up the search box here. I've pushed Control Shift key on my keyboard and I want to start a clock or on the current file. It's just an extra plug-in and it allows us to execute JavaScript in real time in this file. It's all it does. So here we go and all I wanna do is I want to log out the sentence original. And you can see the blue takes data. That's what's being consoled, legs what's being returned to us by JavaScript. And this is Crocker working. It just allows us to see our effects in real time for your very useful. Now, what do you think's going to happen when we return sentence lower? Well, I'm sure you probably already guessed it. All. It's going to happen is we get exactly the same thing that all in lowercase. But what I've managed to prove to you is that our sentence original, that original sentence that we wrote together is unchanged. This toLowerCase method does not alter that original string. Okay, kinda making saints are observed. Let's continue. Okay, cool. So we've seen that it doesn't alter the original string. Infected generates a new one. But at this point in time, you still may be scratching your head. You may be getting caught and noise provided by JavaScript. But we exactly does it come from. And the answer to this is drumroll please. That comes from the string object in JavaScript. And just remember that the string object is a global object for all strings. Again, let me hop over to the console and images show you where we can find it. Let's pick up exactly where we left off. Remember we wrote the sentence, we converted it to lowercase. Now, I just want to prove to you that it has to be on a string. So one way to do it is we use the type of operator. So let's console log. And let's go and type of. And we want to look at what our original time is. And we can see what's returned to us by JavaScript is a string type. So we know our symptoms original variable string, and that is why we could execute this toLowerCase method. But you probably wondering way is this exact method from an how do you see it? Will, it is very, very simple. Let's just go and open up a browser. So I'm just going to right-click on my Chrome mu called Nieto. And let's go to the console cookie. Let's go up and up the console. The museum India, so you can see what's going on. And it's very simple. All I wanna do is I want to console and do, by the way, is different to console log. It gives us whatever we wanna do hot. But in JSON like format, in a tree-like format. And of course what I wanna do is I want to get the JavaScript string object. Because remember we know our original sentence is a string. So we know it's of type string. And if we open up string, and again it's not much on here. We've got linked, we've got name. But what we want to look at is this prototype because it inherits a lot of methods and properties. And because it's a string, it's prototype as a string here, we get lots of methods and properties from the string type. And if we scroll down, we should find to lowercase. And there it is. And we've literally found it, you know, exactly where it comes from. Making seems that we're not quite done. So let's jump back into the lecture. We've seen that it comes from a string object and a high case, it's quite intuitive that only works with strings. If you try parse in other daughter types, such as null undefined, we even a number that JavaScript parser wall throw you an error. In fact, you'll get a type error. So just make sure you take the type before parsing it into this function. Otherwise your app will crash. What am I talking about? Well, let me jump over to the console once again and leads toward coding together just to see this in action. One last thing before we finish this off, remember we saying that it can only be used on a string type. So let's scroll up with actually just finished off will be picking up exactly where we left off. It's clear the console. So what does this mean? Well, this means if we have a number, let's just say 85 and we try and access to lowercase. What do you think's going to happen? Well, we get a syntax error, invalid or unexpected token. We can't call it toLowerCase method on a number. Make sense. What about kinda of an array? So say we've got a moraine just with one item in it called BU. And we try access to lowercase as economic. No, we get a type error. We cannot call this function on that. What about undefined? Well, if we try and access again to lowercase on undefined, again, it's not going to work. And what about now if we try null? I think that'll work. So this is the point I'm trying to make. We can only access the toLowerCase method on strings. I hope you're getting fun and argued any a lot. So this is just a little bit more detail on toLowerCase method that you might have not known previously. Keychain stay motivated and I'll see you in the next lecture.
15. Array.from() method - intro: I hope you're having a lot of fun in this course. As much as I am. I love putting these things together and I left teaching what I've kind of learned over many, many years. Anyway, the next thing I wanted us to discuss very briefly is another very useful bed, a little bit advanced function in JavaScript called array from. And what does this method do? What the very, very, very basic level, all it does is it creates an array, but not from an array, because they would be pointless. It creates an array from two types of different things. Creates an array from one and array-like object. And all I mean by that is that it's an object that has a length property. And two, you can create an array from an iterable object. Thanks Doc met pulsate. Anyway, this is not important right now. The important thing to understand is that the array from method takes something and it converts it into an array. Then why do we want to do that? Will, if we can create it into something like an array, we can have certain methods and properties available to us that we can use on that newly created object, a whole Tetrahedron created array. So say kinda making saints. Don't worry if it's not the first thing I want you to understand what the array from method is, that it is on the array itself. What I mean by this limit, jump over to the console and quickly show you. I've got my console open. Yeah, and the only thing I want to show you is a way to find this from mated. And as I mentioned, it's on the array object within JavaScript itself. How can I prove it to? Well, first, let's just console out the array. And if we do that as the array provided to us by JavaScript, we open that up. We scroll down. And there it is. The, is the from makes it pretty simple, right? So there we go. We know that the array from method as found on JavaScript's array object kinda makes sense, right? But we are not finished yet. Let me jump into the lecture and let's talk about this method in a little bit more detail.
16. Array.from() - how does it work? : So what exactly is the subarray from method all about? We'll very intuitively, and basically all it does is it creates an array from an array-like object on iterable object. But I'm not going to get into that now. Similarly, just like the toLowerCase method, the array from methodology is a pure JavaScript function. In fact, it was introduced as part of ES6. Es6, by the way, was just a major overhaul and upgrade to ES five. And you're probably not scratching your head, but you may have already forgotten where does it come from. And we just saw it comes from the array object itself. But these are all things that you already know. So how does it work? Well, it's very easy to access this method. We start off by accessing JavaScript's array object within xi's, the from method. And the front method takes an argument and its argument is an array-like object. But before we talk more about what it does, it top over to the coding editor and leads towards seeing how it works in action. Before we start getting into more detail on the array from method, I just want you to understand how it works. So remember what I said. It has to be an array-like object on iterable object in order for us to use this array from method. So how does it work? Well, let's define an array-like object. And this just be very, very simple here. Let's just say what? Okay, so we know it's a string in this case. How does the array from Luke like? Well, firstly, I just want to say Aflac Corker, open cooker just allows us to run JavaScript in real time within our text editor. So we don't have to keep jumping to the browser. It's just a lot quicker to kind of rise up your code. It's really handy. Anyway. How does it work? Well, let's console log something and let's access JavaScript's array object on name. We know there's a method called from. And we wanting to pass in our array like and as you can see, it takes our array-like object are worth and it converts it into an array, which is really, really awesome. And you can see here, our array just consists of each liter in that string. And it's all, it's done. The top back to the lecture. Cools and making things. We looked at a very simple example. But just bear in mind that what does this array-like object mean? Just means that the object needs to have a length property and indexed elements. What do I mean by this? Well, lets hop over to the console again in this just look at exactly what I'm talking about. Fluoride. So we've looked at this example here, but how and why does it work? Remember, the array from method will not work on everything. In fact, as the description kinda season, as we spoken about, it only works on array like objects. And what that means is at the object needs to have a length property and D4 index elements. What do I mean? Well, it's got a console. So let me right-click on Google Chrome here. New Incognito IMRT. Let me go to a console. And kind of making scenes. Can you see that? And remember what we said. Let's just define dog or array-like object as worth. And we know that the array from method works on us. We just saw an example of that. Would y. Well, to show you, let's console do out this array like object and I want to look at its proton. And if we load this out, we know it is of type string. And if we open up the string method, what's awesome is that we've got this link property. That's what I mean by an array-like object ID has to have this link property in order for the array from makes it to work. There you go. Hope is making scenes. Let's jump back into the lecture or odds. I hope it's starting to kind of make more sense to you. And remember what I said earlier that it does take more than one argument. Actually, it can take up to three arguments, can take a map, and it can take what you want this to refer to. And bear in mind, these arguments are optional. You don't have to put them into this function at all. And a lot of people actually combine the, this optional argument into that map function itself. So oftentimes you'll just see two arguments in the array from method. Anyway, I don't want to go into too much detail about this. I can quickly show you what the map is all about. So on the top over to the text editor again. And let's have a look at how that would work. Last but not least, let's see how the second argument to the array from function works. What is it all about? Well, let's delete everything we had on our screen previously. And this define an array is just say that our array has a dog and you guessed it. A cat. Freeway, simple. Now what I wanna do is I want to define a handler function. I want to take everything inside this array and I want to log something out to the screen so that it's used JavaScript's function keyword. That's cool. It handler, we can call it whatever we want. The hand is going to take an animal in each case. And all I wanna do is I just want to return a statement and I'm going to be using template literals here. And what I'm going to say is I'm going to say a animal walking, walking. So there you go. That's nothing too profound. It is a very, very simple function. Now what do I want to do? Well, let's console log exist the array from method. We know we want to access this array type. A hand has, you can see here, if we just keep it with one argument, literally does not make sense for us to do so because it is an array already. So there's no point of creating an array from an array. But it's the second argument that map that I want us to understand. And the second argument is what we've defined as this handler function. And there we go. Returned to us. On the screen is a dog walking and a cackling walking. This is a new array. Now, it's created a brand new array, and it's taken, each item in the original array costs through a map function, and it's returned to us a new array. Does that kinda make sense? And that's what it's all about. Hope you're having fun. And I think by now you kind of have a good intuitive feel. Follows works. So well done. I'm very, very impressed. I hope it's dying to make a bit more scenes. And don't worry, as you come across these in your coding career, you'll start using it more and more and it will become a lot more intuitive. I just wanted you to know about the array from MRD because it is an, it can be extremely handy, which brings me on to the next topic. And that is why we need to know about the array from MTD. Why did I even discuss it in this course? We'll sometimes we want to work with methods that are available from the array object. For example, the for each method is only available on the array object. And in order to access that method, we sometimes have to convert what we working within our code into an array. Does that kinda make sense? And over and above this, the array from method is extremely useful. It allows you to do lots of other things like cloning arrays, removing duplicates, even filling an array, etcetera, etcetera, that are a lot of things you can do. And most definitely you are going to be using less when working with DOM collections. And it brings me back to that first, sometimes we want to use methods that are only available on the array object. So when you're working with a DOM collection, for example, and HTMLCollection. Sometimes we need to convert that into an array object in order to access methods we want. So I guess what I'm trying to say is that it comes in handy when you encounter and work with array-like object. It is providing a little bit more clarity on what this method does. Don't worry, we're only just getting into it. So don't panic if you don't fully understand it. Gh, it'll come through time. I hope you enjoyed this cool so far Huike, staying motivated and I'll see you in the next lecture.
17. indexOf() method - intro: Another very incredible function in JavaScript is known as this index of function. And what does it do? Well at very basic level, that tells you if a given item can be found in an array or a string. The index of method was added to the 8ma 262nd standard in the fifth edition. The, what that means is said to Eleusis added on December third of 2009. So what I'm trying to say is you don't have to worry about browsers not incorporating this method. Every browser today will allow you to use the index of method. Okay, great client, old browsers can accept a dog. What does it look like when we start using it? Will firstly, you call the index of method by typing its words, it's keywords index off. That Dean takes two arguments. The first argument is the search item and aka the item you want to search for. And the second argument is optional. It's the starting point of your search. Don't worry, we're going to be seeing examples of this shortly. So the ego, that's kinda what it looks like, high-level. And as I mentioned, we're going to be looking at examples. But before we do, that is something very important you need to understand. And that is this indexOf method only exists for two daughter types in JavaScript. The first daughter type that exists on erase. What is an array? In JavaScript? And array is just a single variable that is used to store different elements and bear in mind, the JavaScript array is a global object, meaning you can kind of access it from any way you like. But enough talk. I actually want to jump over to our text editor and I wanna start coding a raise with you. And I want to start looking at this index of method, specifically on arrays. Let's jump over to the console and it's still playing around.
18. Using indexOf() with arrays: Okay, so here we are. And I want us to start coding together, but I want us to go step-by-step, slowly, slowly catch a monkey. The first thing we mentioned is that this index of exists on $2 types in JavaScript. And the first auto top we're looking at is the array. So let me prove it to you before we go further in our coding, I went to console log. All it's just console do out the array object. If we open this and we look at its prototype is a index of method, they, we go, can you see us? So now I've just proven to you that it does exist on the array, that global array object in JavaScript. It's way it comes from. Alright, so now let's go to our coding. It, it's up. I've just got a blank app.js file open here, and I'm running coca caucus. Very useful by the way, varies. Hugely useful. I keep saying it, but it is very good. Okay, the first thing I want to kind of get across to you is one as an array, will 50. Let's create an array and we use it by the square brackets. Yeah, and I just want to say, I am the first element. The second element. And you guessed it, I am the third element, C. Here we go, we've created an array. We use those square brackets. And how do we access arrays? We'll first thing I wanna mention is that JavaScript arrays or Sarah. What do I mean by that? I just mean that the first element of an array is always index at 0. And the last element can always be found at the index that's equal to the value of the array's length property minus1. Let me show you what I mean. So let's console log our array. And remember how I said that it's 0 indexed x is the first item in the array. We type 0. I'm the first element. And of course we didn't do that for the next items, right? We can go 012 on the first and the second and the third element. Does it make sense? And the other thing I wanna mention is that every array has a length property. So if we console log out our array and we access this property called links, we know that our array has three items. So a very handy tip when it comes to coding. And I'm even gonna come in here, we can always Xs the last item in NRA like this. And this is very, very useful. So please remember this for type out the solution. Just think about what it is we've just done. We know the array's length is three. And if you look at their console log just above, we know we've accessed the last item, I using array and the index two. And remember, JavaScript arrays are always index at 0. So we know the last item in the array is that array length, which is three minus one, which gets us to two. So all I'm trying to say is to access the last item in array. All we have to do is access our array. And now if you don't know what the link is, it's very handy to access the link property, which in this case is undefined because there is no fourth item in the array. So you always minus1. Does it make sense? I hope so. And herbicides get a more intuitive feel about how arrays work. The other thing I wanna mention, logistics leaders. Men hate deleting stuff sometimes. Have we spent so long to try and get points across and I just deleted, it's a bit sad, man up the fluoride, but anyway, let's create a new array, 123. The other thing I want to just mention with arrays that are quite peculiar is that you cannot use the dot notation to access items. This is an important point. So for example, we console log our array and we try and get the first item. It's not going to let us do it. We actually get a syntax error. So just bear that in mind. And it's not, you know, there's nothing special about this. Infect. Javascript properties that begin with a digit can never be referenced with documentation must always exist in using bracket notation. The nuance of JavaScript, don't worry. Ok, but you are probably wondering client, I don't want to learn about arrays. We're on the topic of index of n. You are a 100% correct. I just wanted to kind of get you familiar with arrays before we jump into it. Okay? The point I wanna make with index falls is that it returns the first index at which a given element can be found in the array or doesn't exist in the array. Minus1 is returned. What do I mean? We'll let us define an array called animals. And it's got a warthogs that's got a giraffe. And it says got a buffalo. And it says it's got a line. How does it work? Well, let's look. Let's console log so we can actually see the result of what we are producing. The first thing in order to access our index of is to access an array. And the array we're going to access is our animals array. We want to now access the index of method which has inbuilt into all arrays. And let's search for talk. What would you expect to see? Where is warthogs located? That's right, it's located at index 0. Remember JavaScript arrays are always indexed at Bass Sarah. So if we try and find warthogs, we can see returned to us is 0. That makes a lot of sense. And I'm just going to duplicate this code. Let's now search for Buffalo. What do you think the index number that will be? Let's write our expected number to see if that's right. Now what I wanna do is, let's search for dog. What do you think's going to happen with dog? Well, as I mentioned, if it's not found, negative one is returned to us as a mixins. So just remember, negative one means it's not found. And the last thing I want to mention just before we move on is that the index of method compares elements in your array using strict equality. In other words, using the same method used by the triple equal sign. Just remember that. Okay, Clyde, This is all well and good, but we are only using one argument in this index of array. I want to use both and I want to understand it in more detail while it is good to hear my fellow student. Let's delete all these consoles. Let's now look for this war-torn animal. But let's tell our index of method. We only want to start in the second item in our array, a from index one onwards. What do you think will happen then? Let's go to our second argument in this method. And let's say we wanted to start from the second item in the array. Well, of course it doesn't exist because we know we're looking from giraffe onwards and there is no wall tug. This look at another example that's now look at Mozilla. And let's tell our index of mated to search from say, the third item in the array number two. And in this case, it does return our index number. So it's very, very cool. And we know does exist. This is kind of how a second argument works. Zai Kai, making sense. I hope so we've worked a lot with arrays, but now I'm going to jump back to the late channel one is to look at the second daughter type, where we can start using this index of method.
19. Using indexOf() with strings: I'm having tons of fun. Hope you learned a lot. Let's just go back to where we started. Remember we said it only exists on two daughter types. This index of method, the first-order top we've looked at as arrays. What do you think the second-order diapers? Well, it is unrolled, please. So this one slide you're looking at here is a very important one, gives you a very high-level overview of this index of method. We've looked at a ton of examples with arrays. I want to finish off this lecture now by looking at examples with us working with strings, they start seeing how that works. It's gonna be a lot of fun. Trust me. Hey, wow, this is really cool. We've just done arrays, but now I want us to get onto strings. How does that work? And it's really exciting. You'll see not. So let's jump into it. Cou, okay, where do we start? The first thing I want to show you here is if we got our console, we console, the array, is just actually clear a console and let's do the same with the strengths. Pretty straightforward. We have been a string. We look at its prototype. We scroll down and they, my dear students is index of this is a second daughter talk and JavaScript that gives us access to this awesome useful method. So you go, I just wanted to prove to you that it is found on this dotted type as well. If we go back to our coding editor, LET dot looking at this in action. So let's delete our Eurasia. We've looked at arrays. It's now creates, I don't know, a sentence. And it's just say, Hello, world. The universe. Often know what's wrong with my topic today. Welcomes you. Today's I'll sentence, we know this is of type string. How do we know that? All of its console log type of sentence. And it's pretty obvious that we know it's a string. Because we know it's a string. We know we have access to this index of method. So let's define a variable called AIM, that's excess al sentence. And let's search for something. Let's search for little word welcomes. Let's see as deaths, in what way do you think that would be? Console log in out to the screen and we get a number 26. Why 26? Will? It's not counting together. We know this is index 012345678910111213141516 17181920. Twenty one, twenty two, twenty three, twenty four, twenty five. And of course 26 is way welcomes begins. Very, very useful. Method is define a constant called adenoma sentence. Again, and let's just say, hey, are you learning a lot in this course? I hope to keep learning. Let's start using this index list dot. Getting more intuitive field, let's define a new JavaScript variable called search word. This is what we want to search for. And let's say we want to search for the word learning. We can see firstly, straight off the bat, we have two words, don't we? Learning and learning. So just bear that in mind. Let's define a new variable called first-time. And let's access our sentence constant. That's access this index of method. And let's search will search word. Let's console logs first timeout. It's eight, and we know it's eight because it's the eighth character from the very beginning is this first learning word. But now, how do we access the second learning word? How will we do that? Let me give you a clue. Let's utilize the second argument in the index OLS method. So all we have to do is define a new variable called second time. Let's exit our sentence. Just realized a spotless incorrectly sentence. So let's excess index off. What we wanna do now is we want to search for all search word. Don't worry. This time, we want to utilize the starting point. And where do we want to start with? Let's start off the, it's founded first item, which is the first time, plus one. So now we know it's going to search through our array, but only starting after we've passed the first learning word. Hope that's making sense. If we console log this out, we get to 44, which is exactly what we'd expect. Using index odds this way can be very useful in your code and you can do a lot of things with it. I don't know. Let's give you an example. Let's define a variable cool solution one, let's use template literals and let's say the index of the first. And we'll use the variable search word. Word from the beginning is. And it will go first time. And if we return this to the screen, we literally get console.log to us. The index of the first learning Word from the beginning is 80. How awesome is this? We combining a lot of things that we combining template literals, combining the dollar sign curly braces to incorporate expressions and variables with in our template literal. It's very, very cool and it's going to help you a lot along the way. Of course, we can do the same for solution to solution to. What did we just copy this instead of doing it all again. We know this is the second search where from the beginning is not first time, second time. And if we return that, we get exactly the same thing. But now we are referencing the second learning word. Cuz I know sometimes we get carried away and I'm maybe going a bit more advanced than you need to know right now. But trust me, this will help you in your coding Korea. And I want you to become a master at all the stuff. I hope it's time to make sense. The other thing I want to show you is let's delete everything. I want to show you that index path is case sensitive. So what do I mean? Will, if we have a word and The word is raped dog. If we now console log and we access our word string, we access the index method and we search for dog. We know that it exists. Again, this would make sense, but what about if we did the same? But yeah, we went to look for the word red. As you can see, it's case-sensitive. We'd returned negative one, AKA it does not exist. If we change the small r to big R, it does exist. It's infantum, the very first item in our array. I hope that your learning at time. Last thing I want to get across is that 0 does not evaluate to true and negative one doesn't evaluate to false. Remember if we've got a small r, it's a negative ones that doesn't coerce to false. It's kind of a weird nuance when it comes to this method. So how do I prove this to you? Will let me prove it to you by using JavaScripts if statement. And what I want to convey here, I want to say if it's a word, right, contains, say, rate. If dense evaluates to false, then let's execute this code. Let's say console log. This is the correct onset. Onset. Else console log, this is the wrong onset. And now you'll see a problem. You'll see that because of cloaca, what is returned to us is the wrong answer. We know that the small r should not exist in our string because it only has the capital on our radar. So why are we hitting the second console log in our if statement? The reason is, is that the negative one does not evaluate to false. They fall, we'll hitting this onset and it's the wrong answer. Therefore, the point I'm trying to make is that when checking if a specific string exists within another string, the correct way is to use minus1. For example, if we replace false with minus1 lies it's not working. Minus1 d we go, we get the correct answer this time. Very, very important points I've just shared with you. Please keep that in mind. So z you have it. We've just used index over the rays. We just used it with strings. We've discussed various ways you can use a. We know that as k scenes that have window that you can't kind of coercive negative one to false. And these are pretty advanced topics. So don't take it for granted. Celebrate the small wins. Anyway, let's move on and I'll see you in the next lecture.