Hướng dẫn functional programming in javascript a practical guide - lập trình chức năng trong javascript một hướng dẫn thực tế

Show

Transcripts 1. Course Introduction: Hi. My name is Stephen Hancock. And welcome to this course. I would like to take a moment to explain approach. I've chosen for this course in order to teach functional programming in Java script. Now, I've been a job script program for years, and maybe because of that, the functional programming paradigm was difficult for me to grasp and implement. I would use some functional programming techniques in my code because I could see the value . But when I would try to dive deeper, it was harder for me to grasp. In this course, you are going to learn techniques that you can apply today. You may not apply everything at once, but that is as it should be. You need time to get used to this now. More importantly, at least for my perspective is you are going toe learn the concepts associated with functional programming concepts. It took me a while to learn the techniques will be introduced with these concepts. The approach I have taken with this course is to dissect a definition of functional programming and use that as the structure of this course. We will break it down into pieces, focus on a single concept, learn it, doing exercise on it and then move on. Each new concept will build on the previous concepts. In the end, you will see all these concepts come together. So the main concepts will be covering this course are side effects shared state avoiding immutable data function composition. Imperative programming versus declared A program. And we'll also tackle JavaScript. Libraries have been geared to functional programming. As we move through these concepts, you'll learn techniques used in functional programming. I'm glad you've chosen to take this course and once again welcome. 2. Introducing Functional Programming: in this section, I'm going to introduce you to functional programming. Functional programming is a programming paradigm or a way to approach programming problems . Specific programming languages have been written to take advantage of this paradigm, just like C Plus Plus and Java were written to take advantage of an old P paradigm. Other languages, like Haskell, were written to take advantage of a functional programming paradigm. JavaScript is a multi use language. It can use the Opie paradigm. It can also use the functional approach JavaScript is built to do either and more. Now, you've probably been doing fine with your own quoting practices. Maybe you use an O. P paradigm, and that's been working fine. So why learn functional programming? Well, for this reason, a person that only knows one way to do a thing is at a greater disadvantage than a person that knows multiple ways to accomplish the same thing. Now some might argue that if a person focuses on a single technique encoding, they become an expert at it. Now that's true. But when we apply it to this situation, it assumes that learning functional programming concept will take away from the other concepts already learned. I don't believe that it will add to what you already know. I've never been big on restricting myself coding wise. Remember, with JavaScript, you can use functional programming techniques in code that follows an O. P paradigm, and you can use objects in code that follow a functional paradigm. That is the best argument for learning both. So, with that theoretical discussion out of the way, let's take a look at what functional programming is now defining functional programming as a program built from function. Is Onley providing 10% of the picture? That is a very simple definition, but the problem with most definitions of functional programming is that they don't really clear things up because they're not easy to understand. You have to learn functional programming, it seems toe understand the definition. Let's take a look at one of these definitions. This was provided by Eric Elliott's in his Blawg, and he defines functional programming this way. Functional programming is the process of building software by composing pure functions, avoiding shared state mutable data and side effects. Functional programming is declare a tive rather than imperative, and application state flows through pure functions. Now, the problem with this definition is a defines functional programming. Assuming you already know the concepts that make up functional programming. However, we can use this definition. Let's pull apart the definition. Let's look at the individual parts, and this will help us understand functional programming. So this definition really identifies the approaches made and functional programming. Let's look at what some of those approaches are. Functional programming avoids side effects. Functional programming avoids mutations. Functional programming avoids shared state. Those are things we try to avoid with functional programming. Now here are some things we try to achieve. Functional programming uses pure functions. Functional programming uses, function composition and functional programming uses the clarity of code instead of imperative coat. Now I've broken these out, but you still may not understand what some of those terms mean. What the clarity of coat is as as opposed to imperative code. What shared state is You may still not understand some of those terms, and I understand that. So in the next several movies we will go through each of these to make sure they're understood, and we will look at principles and techniques used in functional programming. It's the principles and techniques you will end up applying to your own code, but you need to understand the approach for a couple reasons. First, it will help you understand the principles and techniques. And second, as an advanced JavaScript programmer, you want to be conversant in multiple approaches. Now, if you go on and decide to use a functional paradigm for all your quoting projects, that's fantastic. But remember, Java script was not written just for a functional approach, just like it wasn't written just for an object oriented approach. At times, you will need or should take shortcuts when using JavaScript with a functional approach, and that's OK. You need to be okay with that. Because JavaScript was not written solely to take advantage of a functional approach. There are certain things of functional programming languages have. The Java script does not have or does not do very well. So in those cases, I believe, and many others that work and functional programming have stated that it's OK to take shortcuts. All right, let's take a look at these approaches that air espoused by functional programming in JavaScript 3. Avoiding Side Effects and Using Pure Functions: as mentioned in the introduction movie, one of the important approaches and functional programming is avoiding side effects. This can be done using pure functions. So let's look at these two concepts first. So let me enter some code that shows an obvious side effect. We have a variable declared, then we have a function increments, and that function increments the variable and then returns the variable. That is all it does now. This shows an obvious side effect. The variable C and T is being changed by this function. The variable CNT is outside the scope of this function. CNT could be used by other functions, other code elsewhere. That is a side effect, because we are changing that that can cause a side effect. So a side effect is an observable change. Outside the function side effects create certain disadvantages. It makes code more difficult to predict. It makes code harder to debug, and it makes code more difficult to reason about. Let me give you an example. So I was recently working on a project where the code was new to me. I was contracting toe add some functionality. But before I could do that, I needed to understand what the code was doing, so I would know where and how to make the change. So I found the object that was keeping track of the data that I needed to work with, and I found a function that was working with that data. However, I then spent several hours just understanding how the code work because that object was changed in multiple places and the function that I found was dependent on so many other things. For example, the function depended on another function or another variable before it could make a change and that existed somewhere else in the coat. So I would have to go look at that part of the code. And then I would find that something else affected when that invoked, or when that made a change. So I was running around the code, trying to figure out what it does. That was because there were so many side effects. It made it very difficult to reason about that code. It made it difficult to debug. As I was adding new functionality. It made it difficult to predict what the code was going to do, because so much of the code and the functions were changing things outside the scope of those functions. Now a function without side effects is easy to reason about. If I do something, it will do this. I know the end result based upon the input. If there are side effects, I don't know that because I don't know what those side effects could be. So with side effects, I have to ask a lot of what if questions without side effects, it makes it easier. So let me illustrate this. Using another example, this one was given by Kyle Simpson in the writings. He's done about side effects. So I'm going to pace that in, go ahead and comment this All right. Now look at this simple code. We declare variable here to assign it value, then call a function. We logged the consul call a function, logged a concert, college function longer the console. So let me ask you this question. How sure can you be of the value that will be printed to the console, which, with each of these console log statements No, If you think about it, you can't be absolutely sure unless you know that those functions don't cause any side effects because how do we know that one of these functions doesn't change the value of X? We don't unless we know those functions do not cause side effects. So we would need to go to each of those functions and see what they do. Before we could be certain what those logs statements were going to be. So, basically, if we knew those three functions did not have side effects did not affect anything outside of the scope of the function itself, we would be okay. All right, let's look at one more example I put together to help illustrate the issue of side effects . Another way to think about how side effects can cause problems. I'm gonna pace this code and again here we're using the module pattern at the top. We have a current user variable set to zero, and then we have a user's array, which contains three objects, all three. The objects represent users. Then we have several functions. Then we have four functions that affect the users. The 1st 1 updates the score. The 2nd 1 returns the users so we can take a look at it. The 3rd 1 updates to tries and the 4th 1 updates which of the users were pointing to current user. If it were used as the pointer, which it is used in some of these functions would point right now to the first object, the first user. So update user allows us to change that. Okay, now, down here, I have some set time out functions. Noticed what we're doing. We're calling update user. We're setting it too, too. So it'll be the third user in the array were then updating the score. And then we're updating the tries All right, now. So if we look at that, we should be updating Henry updating it a score of 20. So it should become 100 and then updating the tries, so that should become four. Let's go ahead and save that. Let's refresh and open the consul and let's call return users to get the objects. So Henry was supposed to update to 100 and tries to four. But that is not what happened. What happened is James updated in both both the score and the tries. Now, you probably already saw why that happened, but I did that for a reason. So let me first explain why I happened. If you look, we're using set time out to call these functions. Notice that the update user function the one that determines which user is being modified happens 300 milliseconds. The other two happened 100 milliseconds and 200 milliseconds. So die. Yeah, I set it up toe fell. I set it up so that it wouldn't update the correct user. But the reason I did that is because I wanted to illustrate what can happen in real life. Sometimes sometimes what we think is going to occur doesn't. And so then we spend a lot of time trying to debug it. Well, it would be much easier if these did not have side effects. If we were to call this in a way that we'd eliminate a lot of the side effects, it could make this better. It could make it more predictable. It could make it so that if something like this occurred where the timing was not what we thought it would be, we would still get the results. We want it by avoiding side effects. Okay, now, so let me go ahead and comment this out and let's go back to our original function here. How would we make this function so it didn't have side effects. Well, let me show you a way. We could do that. I'm going to define the function again. This time, I'm going to have a value passed into it. And what am I going to return? Number plus one. So this function doesn't have side effects. And it could be used for the same purpose as the one up here. It doesn't modify anything outside the scope of the function. It will return a value, and then we can do something. With that value, it doesnt modify a value that is already out there. Now, this is called a pure function. What I've just created here. Let's take a look at another pure function. Let me copy that in. So this function computes the average of a bunch of scores. So let's say we were passing in something like this. This would compute the average of those scores and let's look at how it does it. So we declare a variable total. Then inside this loop, we looped through all the scores, adding them to total, and then we return total divided by the scores dot length. We don't modify this array, so we don't modify data outside the function and we return the average. So everything that's affected is inside the scope of this function. There are no side effects now. The loop causes us to mutate or change the variable I and we also change the variable total . But those air contained within the function and and don't produce side effects. And we'll talk about mutation later but allows us to keep this function pure because we've eliminated side effects. So what makes a function pure? Let's take a look at that. First off, the function depends on the input provided and not on external data that changes. So jumping back depends on the input provided and not on external data. See, here's one that depends on external data. This example up here. Okay, the function doesn't cost side effects. It doesn't cause change beyond its scope. So we're not changing anything beyond the scope in either of these and finally, given the same input, the function will always return the same output. So, in both of these cases, if we and if we have an input of five, it will always return. Six. If we have the same array of values, it will always return the same average. So that is what makes a pure function. Okay, now we've talked a lot about side effects and how we prevent them with pure function. So let's look at some possible side effects as we conclude this movie. So here are some side effects changing a value globally that's the common. When we looked at, that could be a variable that could be a property of an object that could be some sort of data structure, changing the original value of the functions argument. So if something's passed in and then we change that value, that's considered a side effect throwing an exception. So if an exception occurs in our code that is considered in a side effect now we're going to get in some side effects that may make you wonder. So hold on just a minute. Well, describe these printing to the screen or logging, logging something to the consul, for example, that's considered a side effect effects. It affect something outside of the function, triggering an external process that is considered a side effect, invoking other functions that have side effects. So if we invoke a function from inside a function and the function we invoke has side effects, the function that we created now has side effects and therefore is not pure. So, knowing these things, how can you accomplish anything in code without side effects? Well, the quick answer is, you can't. You must have side effects. It has toe happen. The goal of functional programming is just to manage it better to avoid side effects. A lot of the common practices we you side effects to accomplish our purpose. And really, that needs to be done. But we use them so widely it causes problems. So we have to manage those. We have to reduce us one way that functional programmers many side effects is The code with side effects is contained together, so everything else does not have side effects and can be relied upon can be tested easier is easier to reason about those air. The advantages. So by managing side effects with pure functions, your cold becomes more predictable. It is easier to test and it's much more readable. Those are the advantages of functional programming and avoiding side effects by using pure functions helps achieve that. Now, before we leave this, let's look at our definition of functional program again to see how work coming closer to understanding this definition. Functional programming is a process of building software by composing pure functions. So we've talked about pure functions and what they are. We haven't talked about composing yet avoiding shared state. Haven't talked about that yet, avoiding mutable data, avoiding side effects. We have talked about that functional programming is declared up rather than imperative. An application state flows through pure functions to help us further with this definition. I think the next thing to talk about is state and shared state, so let's move on. 4. Exercise 1 Start: Let's take a moment and practice using pure functions. I'm going to have you changed some code and implement that code using pure functions and avoiding side effects. It will make the code more reliable. Now, here is the code I'd like you to work with. And this is an example that comes from our last topic. Now it's changed a bit. In the last topic, the code actually used a name space pattern. I removed that because I want us to focus on the task at hand. I don't want any ancillary coating to distract from that. Now, these functions are not pure. So let me first explain what's going on here. And then I'll tell you what I'd like you to dio. So basically what we're doing here is we have an array of users and we have some functions . Allow us update data about those users score and tries. Specifically, we have a variable that keeps track of which user we're working on, and then we have an array that lists all the users. Currently, there's three in here. This is just our sample data, so just think of it that way. The users raised just sample data. It's possible in a real application that could be coming from a database or somewhere else . This is where our sample data is now. Let's look at the functions. First. We have updates. Score. What happens is that receives an amount and then updates the score off a user, which is identified by the current user. Variable with that new amount. Obviously, that's not pure. There is no guarantee you'll get the same output with the same input every time. That's not gonna happen. And there are side effects. It's modifying things outside of this function, so not pure. The Return users function basically returns the users Ray, so we can view it. This particular function was necessary when we're using name space Pattern not necessary now so that one could be eliminated. Were able to just look at the user's array anytime we want, because it's in global scope right now. Update tries similar tough day score, but this just update the tries property and is not pure update users. This updates the current user variable to change, which usually were working on. Obviously, that's not pure because it's changing something outside of the function. So what I want you to do is modify this code so it uses pure functions. Now, first thinking about what we want accomplish here. I want to keep track of some information about users, and I want to be able to update that information now, knowing that that's the goal. How would we approach this to make these functions pure? Well, one way to think about functions to help make them more pure is to think of a function as receiving data and returning data and what happens inside that function on? Lee acts on what is received and then returns the results. So it's not modifying anything outside the function, and therefore anything passed into the function will return the same results no matter what has passed him. Now, for example, in order to act on a user to update the score, what are we gonna have to pass in what we need to pass in the new amount? But we may also have to pass in the original mountain some way, So we're working on the same data, and it always returns the same results. So that's a way to think about the functions in order to help you make pure functions that avoid side effects. Now, since we want to update the array, it may be that not all your functions will be pure. You may have a function that updates this array, and that one would not be pure because the arrays outside of it the date is outside without function. That's a side effect, but that may be necessary to accomplish what we're trying to do here. I don't want this exercise to result in something that is pure, completely pure, using a functional paradigm. The idea is to learn these functional concepts and to be able to apply them to our javascript coating to make that coding better to avoid problems which commonly happen with impure functions. That's what we're trying to do, so we may have a function, er, to that isn't pure. But let's make sure the functions that can be pure are pure, so we don't have to worry about side effects that could have happened could happen. Now, keep in mind, this isn't approach to the problem, so you may have to approach it in a different way. You may come up with something that's quite a bit different, and that's fine I don't want you to get the exact same thing that I get. That's not the intent of this exercise. Basically, you will learn something from going through the process of trying to make pure functions. And then when you review what I do following the completion of that, hopefully you'll learn something more. That's the idea, so let's get started. 5. Exercise 1 Finish: I hope you learn something by going through that exercise by trying to apply peer functions . Now, I would like to show you what I did in hopes that you can learn something from that as well . Now, first off, I'm gonna take a slightly different approach to this. I'm not going to use current user to keep track of which user I'm working on. That's an issue with trying to use pure functions. And so I'm gonna get rid of that completely. Now, what I'm going to do is I'm gonna identify the user by the name. Now, I know names are not unique. That's not That would not be the correct piece of data to use If are doing this in real life, I'd want an I D or something like that toe identify the user. But just to simplify things, not to add more to this explanation, I'm going to use the name. That's how will identify the users. All right, so get rid of current user first. Now I'm going to set up to areas in my code. I mean, comments modifies data, any functions that are not pure, we're going to go there and then I'm also going to have a section, that's for sure. Okay, Now, the first peer function I want to set up is I want to create one that gets the user. I need to grab a user from this rate to be able to update a score, update tries. And I don't want those functions changing this array here because that would be a side effect. I want to be able to pass in the user and have it change it and then return the user. So in order to do that, I need to create a function is going to retrieve a user. So I'm gonna call that get user, and I'm gonna pass in. And, Ray, this is the ray I'll be passing in. But the idea is here. I could be passing in any sort of day that I'm trying to retrieve from. In this case, it's that array. And then I want to pass in the name of the user I want to grab Once again, I'm using the name as a unique identifier. Not something I want to do in real life. It will work for this example. We only have three users here now in order to grab that user, I'm just gonna cycle through the array. So I mean, use a four look for that, and then increments I So I'm gonna cycle through all the male elements of that array. I'm gonna grab the one that has the name equal to whatever I pass in. No, I could also use the four each method of a raise That would be a great way to it Rate through the rate as well. But I just chose to use a for loop here. Now I'm going to check if that element of the array dot name, then I'm gonna do to lower case just to be to make sure I'm checking like data is equal to name dot to lower case. So if those two things are equal, then what do we want to dio? Well, in that case, we want to return that element of the array. So that user So that's how we would get the user. Now, for some reason, it doesn't find the user. I'm just gonna have it return no, to indicate that nothing was found. So I'm passing in and in an array and I'm passing in a name. If the same data is passed in every time, it will return the same results. There are no side effects here. I'm not modifying stuff outside of this function. So there we have our first pure function. Now, let's change update score here so that it is pure in order. Do that. I'm gonna pass in a user. So I'm not gonna modify the user outside of the function. I'm gonna pass it in. I'm still passing in that new amount. And then basically, what we do is user dot score, and then we add that new amount to it. And then we returned the user. So we're sending the data back out now. Those of you that are well versed in javascript probably realize when we modify this user, we're actually modifying something outside the function because of the way objects work in JavaScript. This is really not the exact object that's being passed in here. It's just a reference to it, since it's a reference it modifies whatever was passed in whatever that variable was referencing. So it will modify that user, which is outside of this function. Now that is the nature of Java script. That's something we deal with with Java script later on, we're going to look at how we can get around that. But for now, this is accomplishing our purposes. Now, one more thing I'm probably gonna do here as I just want to check if User, I want to make sure that user exists. Because when we're doing get user, we return. No, if we don't find that user so I don't want to try to change something on No, that would give me an heir. So I'm just checking that. So there's update scores, This particular function here, we can just get rid of update tries. Very similar structure of update scores. So I'm just gonna copy that pace that in, We need to do tries here, and we do simply Plus Plus, we're just incremental the tries, all we're doing, and then we return the user. But one thing we need to do is pass in the user. So we need to set up a parameter for that to grab that user when it's passed in. So we have a get user and update score. An update tries. Now, this function here, I'm also getting rid of I'm going to use a different one. And this is the one that will actually modify the array. And I'm gonna call that store user now, a store user. We're going to pass in an array, which will be this data for our test here and pass in a user. And then it's going to find that user in the array and then replace it with the one that we've passed in so once getting me use A for loop. In fact, let me just copy this here is gonna be very similar. It's looping through that array, and we simply check to see if name dot to lower Case is equal to user dot named to lower case. So users passed in. And so we want to check to see if those two things are equal to if they are and we're not returning array. What we're doing is we are assigning the user to that position in the race, and then at that point, we can break out of our loop because we've been able to story the user. All right, Now let me set up the code here. It allows to test this. I'm setting up a variable us are compressing returns. So let's get this up a little bit higher so you can see it. And this variables going to store the user that I retrieve using gap user passing in The users of Ray and the one I want to get is Henry. That's the first user I'm gonna grab. That's the one we're gonna change here. Then I'm creating in another variable because this one's going to store the return user from of date score. So I'm gonna update the score and get the user back The results back because the function returns those results. So I'm passing in the user I retrieved here, and then I'm getting it back. All right, one more time. I'm gonna update the tries. I'm passing in us. Are one user that I retreat from update scores and then finally, store user, we're gonna going to put all this back into the array using store user. Let me save that. Let me grab the file path to this so we can take a look and see what's going on here. So pay set in and let's go ahead and open the console. And now let's take a look at the user's array. Now, if we open that up, we can see Henry has a score of 1 10 and tries equal four. So if we look at our original data back in here, Henry had a score of 80 and tries of three, so that has been updated for us. Now, before I leave this, I just want to show you one thing that will need to be aware of later. Notice that I use three different variables to keep track of the data that was returned from each function. No, technically, that's all different, right? Well, let's take a look at U. S. R. As you can see, that has the updated score and the updated tries. Even though that was the variable that was used to store the user retreat from get user. It was not the one that had the update score or that date tries. That's these two here. So why is it showing all that updated information will, Once again, that's something that's that you need to understand about JavaScript is that with objects the variable stores a reference to that object, And so since that object is mutable, since that object can be changed every reference to that object will show those changes when they occur. It doesn't matter that we use different variables here. The reason I set it up this way instruction it this way. Even though that doesn't happen in JavaScript is that later on, we will look a concept that allow us to do that, allow us to get around that little bit of functionality and JavaScript. So the main thing to grab from this is we approach these functions, trying to make them pure so that we can rely on those functions. We can see what happens in those functions. Something is passed in and it returns something. So those functions air easier to reason about because they are pure. All right, let's move on. 6. Exercise 1 Follow Up: Other Possible Solutions and the Problems: I want to take a few minutes on a follow up to exercise one. I want to show a couple of other possible solutions but also show the problem with those solutions. The problems are going to show our problems that are correctable, and we will learn later how to correct them. As we learn more about functional programming techniques, I think this process can help solidify the concepts of pure functions and avoiding side effects. I will show a possible solution. Then I will discuss the problem. So let's look at the first possible solution. This one seems to be a lot simpler, right? I have limited it to ah couple of functions, basically, what we're doing here, let me explain when we want to update a score, we pass in the array, we pass in a name and we pass an amount. And then that array, which is now stored in the a r r variable we use for each to iterated through it, checking the value each value in that array using for each and so each value will be one of those objects. And so we do val dot named to lower case. We check to see if the names match. If they match, then we update the score for Val by adding amount to it. And then we return this array. Okay. Basic same idea with tries. We passed set in. We update the tries we return dear A Now, in hopes that we're avoiding side effects with pure functions, we are passing the rate in to a different variable. When we receive the new array back, we're assigning it to a different variable. So we're not affecting this out here. So we're trying to do some things to avoid side effects. But let's go ahead and take a look and see what is really happening. Okay, So let me grab the file path and let's pull up this file and just take a look at what we've got here. Is gonna open the consul. And let's look at one of those variables. New Array knew Ray one. And you should notice something about it. Um, if you remember, here's the data we started with. Henry had a score of 80 and tries of three. So remember that now we're looking at Henry with score of 1 10 and tries of four. This is with new array, one new Array one. We had only modified the score. Now, if we display new array to, we'll see the exact same thing. If we look at the user's array, we will see the exact same thing. So once again, the problem that we have encountered that I mentioned several times is that with JavaScript , objects are passed by reference. And since objects are immutable, when that object is changed, anything pointing to that object, anything referencing that object will show the changes well. And so we passed the array into this variable. But it is getting changed because this is referencing the same array. This array right here as this is referencing. And then this is referencing the same array as this is referencing and that is referencing so they're all referencing the same array. And so that's why we're seeing the same information. And so we are getting side effects. Because of that, I like a description of side effects that I read on the Internet. It was a short article on functional programming, but the way it described a side effect is examples of observable side effects include modifying a global object or a parameter passed by reference passed by reference. That was the part that stood out to me, reading that through a long blogged. You could easily read over that and not realize the significance of that passed by reference. Here we're on Lee modifying an object which is part of an array. But once again, everything is passed by reference. So that's a problem that we need to be aware with JavaScript. That's the problem you'd overcome. Now let me show one more example. So close these files. This will be exercise one B. So if you want to look at these files, you can. Now, let me explain how we're doing this one. So we do have one function that set up here that is specified as modifying the data so that will be used to modify the data. Basically, of approach we took care is we have a function that gets a user. So we pass in the array and we pass in the name and it's supposed to find the correct user object and then return that that's all it does. So it returns the crack user object if it finds it. If not, it returns. No. Then we can update the score by passing in that user object and a new amount. And so it's just acting on the user object. It's not acting on the whole array in the same thing with the tries we can pass in that user, and then we'll update the tries for that user. You know, the idea being we can keep this within a user. And then when we want to update the array, we call the store user function and that basically finds the correct user and then replaces that object. So the idea being avoid side effects until we want a side effect to occur until we specifically want to change something in this global variable. Now the same issue we've been talking about occurs here is, well, these users, although there entirely different variables. They store the user that has returned. So once the score is updated, it returns user. Once the tries is updated, it returns the user so it stores that user and then we use it to pass into the next one. But once again, they all reference the same object. So let's take a look at that one really quick. Grab the file path here go out again. So here variables User, user. One user to So if I do us are we can see what it contains. Henry 1 10 and four U. S. R. 22 Contains exam thing. Us are one contains the same thing because they're referencing the same object we can see. The users array has been updated because of the call to store user. Right, Well, let's take a moment and see what happens if we commented out this. So we're not even calling store user were not in calling this function year, which goes into the rate and replaces it. Let's see what happens. You say that, Then let's refresh this again. Display users Look at Henry. It's already been changed. It has already been changed because of the reference that we've been talking about so that there is a great example of a side effect, even not intending to make a change to the array trying to avoid it. And yet we still made a change theory. Like I said, these problems we've talked about there's a way around him as we learn additional techniques. So let's move on to the next topic 7. Avoiding Shared State: the next part of the definition we're going to talk about is shared state now, before we can understand shared state, we have to understand what state is in programming terms. First State refers to the current condition of something. When we ask what is the state of a car? We're asking what condition it is currently in. The state of a door could be opened or closed. State has a similar meaning in programming terms, so let's look a definition pieced together from sources on the Internet. So first off, a program is considered state full if it is designed to remember data from events or user interactions. The remembered information is called the state of the program. So when we're talking about state, we're talking about its condition that programs condition, which is controlled by the data. All right. Another definition. A JavaScript program stores data in variables and objects. The contents of these storage locations at any given moment while the program is running is considered its state. So the data that is being stored that is, the state of the program that determines the condition of the program that determines what the program is at that moment in time. So let's look at some code from our previous movie and identify the state in that coat. Now, in this code, we have two variables. Current user and users. This is the state. These variables contain the data that identifies the state of this program. When current user changes, it's state changes. Any time we update a score update, tries update the user that is changing the state of this program because it's changing the data and these variables remember that data and therefore control the state. So that is the state of this code. That's what we're referring to when we're talking about state. So now that we describe state, I think shared state is easier to grasp this state. In this code current user users is shared. It resides in a scope that is shared among multiple functions and scopes, so we're accessing it and changing it in multiple places. Therefore, that state is shared. Now let's look at a definition for shared state from Eric Elliott again, this is what he has to say. Shared state is any variable object or memory space that exists in a shared scope or as the property of an object being passed between scopes. I'm going to dive into that in just a moment. A shared scope can include global scope or closure scopes. So in the code we were looking at, our shared scope is closure scope. It's not global scope, but it is closure scope. Now let me jump back to the first part of this definition. So any variable object or memory space that exists in a shared scope. So that's what we're seeing here. This exists in a shared scope or as the property of an object being passed between scopes. Now, what does that mean? Well, in JavaScript, we can pass objects between functions, and maybe we don't share that except by passing it between functions. Well, how does that become a shared state? Well, because of the way objects are, objects are immutable, Meaning when you change, an object in one place is reflected everywhere else. That object has been passed, so when you're passing an object, you're really passing a reference to that object. Therefore, when you update that reference, it updates object any other place within the code that it is being referenced. So that is why an object being passed between scopes constitutes shared scope as well. Now the problem with shared state is that in order to understand the effects of function, you have to know all about that function. You have to know the history of all of its variables and the functions used to affect them . So you have to know a lot toe, understand what's going on when state is shared. And so that is the problem with shared state. Obviously, one of the advantages is it allows you to solve a programming problem, but sometimes it can create other problems. All right, let's look at our definition again. Now we've covered another part of that definition. So functional programming is a process of building software by composing pure function. We've talked about pure functions what they are but not composing, yet avoiding shared state. We just talked about that avoiding mutable data, avoiding side effects. We've talked about that functional programming is declared of rather than imperative, an application state. Now, this applies to what we just discussed is well, application state. So the state of our application flows through pure functions. So we passed the state from one function to another. We don't share it. So let me jump out here. So a way to help this code meat the criteria functional programming is to pass our state between the functions as we call there from functions. We pass it between the functions. We don't share it now. Another way that's accomplished and functional programming is when we pass an object, for example, we clone it. Otherwise we'd be passing a reference. That object would be updating it. But if we clone it, then the object is used inside this function, and then it returns. It returns the cloned object so that the original one is not updated. So that is one way we deal with state in an application without sharing that state. All right, let's move on to the next part of the definition. 8. Avoiding Mutations: in functional programming. We want to avoid immutable data. Data is immutable if it can be changed after has been created. Data is immutable if it can't be changed after it's been created. So in functional programming we're striving for in mutability. But why? What is the advantage? Some of the same advantages we've already talked about apply to avoiding immutable data. The code is more predictable. It is easier to reason about, and mutable data can have side effects now. Achieving in mutability can sometimes be deceiving. In JavaScript, for instance, since yes six, we have the constant keyword for declaring variables, this makes it so the variable can't be reassigned. That term reassigned is important in understanding const. It communicates that you can't change it, which is true for primitive values. But it's not necessarily true for objects. Let's look an example of that. I'm gonna create a variable, declare it with constant, all set it equal to 50. Then on the very next line, we'll try to change that value, save that refresh and open the console. Notice the air message assignment to constant variable, so it's not allowing us to do that. It's producing an heir when we try to reassign that variable so numb is immutable. Now let's create an object will create an array. This applies to any kind of object in JavaScript but will use an array to illustrate. And I'm just gonna put some put some numbers in this array. Now let's log the array to the console so we can take a look at it. And then let's sort the ray. Now, this sort method of a raise sorts the array itself. So it moves the elements inside the array. It doesn't create a new array. And so we declared this ray with const. Will that prevent it from sorting it to rearranging the order of these elements Will, Let's do one more console log statement to find out. Save that refresh. Here's our to consul statements. This is how the array originally looked. And this is how the ray looks after it was sorted. So why did that happen? Why did it allow the changing of this ray when we declared it with const? Well, it is because objects in javascript are immutable, meaning they can be changed. Cons will prevent us from reassigning to that variable, so I can't a sign something else to the a r r variable. It won't allow me to do that, but because it is an object, I can change the properties. I can change the order of these elements. I can change the parts of the object. I just cannot reassign that variable. Okay, let's try something else so I can show the nature of this. Let's pass this array into a function and then have the function return the sordid array. Let's see if that will solve the problem for us. So I'm gonna use CONST to declare this function because we're doing functional programming . And Constant is used quite extensively and functional programming because we're trying to achieve in mutability we're going to pass in an array and all we're going to do is return the sorting of that array. Now let's see what happens. So it will create will declare a new variable. Don't set that equal to sort array. Calling the function and passing in the array, we declared, All right, let's then log to the console both of those so we can see what happens. Well, first log knew gnomes and see what shows up there. And then we will log the original array. Say that Jump out, refresh notice. There. Look, they look exactly the same. Both of those who raise are the same. This ray here got changed even though we pass it into a function assigned it to a new variable. Here we use the same variable name. Maybe I should change that really quick just to verify or just to illustrate that has nothing to do with that. The scope of this array is this function. And so this is a different array. So we assigned it to a new variable. We sorted that new variable, but both of them were changed. Now why does that happen? Well, the reason that happens is because in Java, script objects are passed by reference. So when we pass in this array here, it retains a reference this variable retains a reference to this just like this retains a reference to this. And so we are sorting the exact same thing. And it allows us to do that because objects air mutable so are able to sort that. So that doesn't solve the problem for us either. Now, the object class in Javascript has a static method freeze, which basically makes the object immutable. So when you pass an object to object dot freeze, it locks down the properties. That object prevents you from adding new properties or deleting existing properties. So let's see if that helps us. I'm going to add you strict up here because it will force it to return and air if it's not going to allow us to make a change to that array, and then I'm going to freeze what's object up? Freeze that array and let's see what happens. All right, you cannot assign to read only property, one of object, blah blah. So it gives us an air message. It's not allowing us to sort right here. Line six. It's not allowing us to sort that array because we did a freeze on it, so that works in making the object immutable. But what good is that if we can't sort the array? So what we're trying to do here is sort the array, but in functional programming, we want to avoid mutating data. So how do we accomplish both now, since objects in JavaScript are passed by reference so we can't just assign it to a new variable name, it will still have a reference that object that doesn't allow us to to get a copy of it. But that is the idea. We want to get a copy of the object and change the copy, not change the original one. That will help us to avoid mutating that object. So a common practice in JavaScript is to clone the object. Now, since this is pretty common, let's take a look at how this is done, and we'll do that in the next topic. 9. Cloning Objects: one way to help us avoid mutating objects. Changing objects is to clone the object. We have seen the problem we encounter as result of Java script referencing objects. So in order to avoid mutating an object, we clone the object. Make an entirely new object that looks the same. There are a few ways to clone and object before we get back to the code from the last topic , I want to first take a look at object. A sign now The purpose of object assigns to combine objects so you could take three different objects and put them in tow. One object object gotta sign a large to do that. But object that assigned can also be used to clone object. Let's look at it. So first, let me copy in an object. Really simple Object has a few properties there, and let's go ahead and make a copy of that object a clone of it by using object out a sign So we'll call the new 10 B. J two, and I'll set that equal to object dot Best sign and then we will pass in a blank object. So this is the object that things will be copied to, and then it will return it. And so that will be what object O. B. J two refers to. Now. What are we going to copy into that blank object? Well, well, BJ So let's go ahead and save that. Let's refresh this and open the console. Let's just take a look at O B. J. First, we can see there's our original object and LBJ to, and there we have it as well. Now the real trick is to see if we can change a property on one of these without changing the other one to see if they reference the same object or not. So let's change over j two dot score set that equal to 90. Now let's take a look at over J two there we have of 90 and then O B. J, and we still have 85. So that's working for us. That allowed us to clone an object. And then we can change the new object and do what we need to with that noodle, that new object without affecting the original object. Now we need to take a look at the problem that we encounter with object at a sign. There is a problem with it, and that's when we need to do a deep cloning, which means there's an object inside of another object. So let me do this. Let me modify this object. I'm going to add a questions property, and that is going to be an object. And it will have Q one, which is another object success. True Value one. So this is basically a list of questions. We'll just do two of them success for this one. Let's put that as faults in value was. But that was one also. Okay, so there is an object inside of that object. Now, before we go any farther, Liming correct that property there. So we have different properties. Save this. Let's jump out and Refresh knows. Look at the original. There we go. We can open that up. We can see the question object. And then if we take a look at O B. J. Two, we can see the question object as well. Now we can still change the score. Property. Let's do O b J two dot score set that equal to 90 like we did before, and then O b. J to when we look at it shows 90 0 b j. When we look at it shows 85. But let's look what happens if we change one of the Children objects one of the sub objects . So if I do o b j two dot questions dot let's change Q one. Let's set the value equal to five. So let's take a look at over j two. And if we open that object up, we can see that the value for a Q one is five. But now let's take a look o B j. Now, if I open up questions, we can also see Q one is equal to five. So when we have Children objects inside the object, we can see that using object dot A sign doesn't clone everything. So this sub object was child. Object is still being referred to in a manner that doesn't allow us to have a separate object, a cloned object. So the solution to this may seem a bit strange in Java script. We have a Jason object. Its purpose is to allow us to work with Jason Data, and that object provides a Jason dot string. If I method now the purpose. That method is to convert an object to a Jason String to a string. It's a literal text string. We can then convert the string back to an object using Jason dot parse. So the process of converting it to a string and then converting it back to an object makes it possible to clone an object. And that also avoids the problem we encounter with object out a sign. So let's look at that really quick. Let me do a new object O b J three. And this time we're going to use the Jason methods. So first Jason dot string. If I can be used to convert O B J to US String and then once it's converted to a string, we want to convert it back to an object using Jason. Don't parse. So I put that on the outside of my Jason dot string. If I results so that will take the results of Jason dot string. If I and then converted back to an object. Now let's see what happened. Okay, let's save this and let's go ahead and check to see if we can change o b j three questions . Something inside of that without affecting O B J. So let's refresh Get the new coat in there now will change over j three dot questions dot q one dot value equals five and let's take a look at that. Open that up and we can see the inside of questions que on value equals five. So now let's take a look o b j Open that one up down here to questions, and we can see that value for Q one equals one. So that allowed us to do what object Not a sign would not allow us to do so, Jason, that string of I, Jason dot parse is a better method for cloning these. Now, let me just show you one more example. This will be with an array so that we can jump back to our original code where we're looking at a raise. But if I have this array here and set that equal to and inside of the ray, I'm just going to do some simple objects and B equals no to Okay, so they're having a ray Now if we clone that array using object, got a sign or clone it using the Jason object. Let's see the difference And so are you gonna sign. Will be Obi J. Two and using Jason will be over J three. Let's just see what happens. So if I say that, I refresh and then if I change array, let me just show it really quick. Let's say I go into a ray the first element and change a to five. If I look at array, let's just see if that's changed. Yes, it has. Now, if we look at O b J two now remember O B J to WAAS cloned using object out of sign. We can see that that has changed. But if we look at O. B. J three it was cloned using the Jason object, we can see that still has its original value. So that is working with an array. So let's jump back to our cold were working with in a previous topic and see how we can accomplish what we're trying to do using the Jason object for cloning it. So if you remember, we're trying to sort this array without modifying the original object, the original array. So we need to clone it. So then we consort it have a copy of it that assorted and still have the original. That is not so. What I want to do is set up a function that will allow us to clone this object and any object I'm just gonna copy and paste it in I'm going to replace are sort of a function. So here's how we would clone an object. This function we pass in an object, and what it does is it changes the object to intermediary format using Jason dot string. If I so I changed it to a string. Therefore, it's no longer an object. Once we do Jason Jason dot string. If I it is no longer an object, it's a string. Then we take that string and we parse it back to an object using Jason dot parts. So because we went between those two formats, the reference to the object is lost. And so we don't run into that problem of changing the original object because the reference is still pointing to the original object. Now, let's go ahead and use this to cloner object. We're going to pass in a are and that's going to return an array and so we can immediately do dot sort on the end of it. Then we'll log to the consul to see if both were changed. Or if now we've been able to sort the array without changing the original Ray, let me say that. And sure enough, we were able to do that. All right, Now, that probably seems like a lot of work to just make it so that you're not mutating something. And sometimes when we're doing functional programming, JavaScript we aren't s stringent about some of these goals of functional programming. If we know that, changing that array is not going to affect anything else then would probably go ahead and just sort theory itself instead of going to this trouble. But there are times when we don't want to do that. We want to make sure that the data is immutable, and that's where cloning is important. That way we can take advantage of what functional programming has to offer without going overboard and it causing us to take much more time to even write the code. Now we've covered another concept in our definition. So let's take a look at the definition again. Functional programming is a process of building software by composing pure functions. We've talked about pure functions. We still have to talk about function composition, avoiding shared state. We've looked at that avoiding mutable data. We just barely talked about that. Avoiding side effects. We have discussed that functional programming is declared of rather than imperative. We still need to talk about how it's declared of what that means, as opposed to imperative and application state flows through pure functions. We've dealt with that we talked about state and how that state flows through pure functions instead of changing shared state. So let's move on to the next video. 10. Exercise 2 Start: in exercise to like you to take a moment and practice avoiding mutations. So it's a follow up to exercise one. I presented a couple of additional ways that you might try to do exercise one, but I also explain that they didn't work because mutations were happening because of the way Java script handles objects. So what I'd like you to do is those two additional examples. I would like you to modify them to the point that they avoid mutations. So let's look at those really quick so you'll find those and exercise two A and two B start folders. That's where they'll be. So if we look first at two a. Remember to a is the example where we were getting a user so would go through the array and pull out a user and use that user to make changes. And then when we wanted to finalize the change, we would then write the user back to the array. So the problem we're encountering is that each of these users would show the modifications because they're all referencing the same object, so make modifications so that that does not occur. And it does not modify the original rate until you intend to now in exercise to be the approach that was taken there is we would take that full array, and we would pass it in each time. The idea being that we were thinking as we passed that array in that would be a new race or wouldn't modify the existing array well, make changes so that that is the case. And so these rays that are generated here, our new race so that you have a new array that will track the additional data for this particular exercise. There's no need to update the existing array as you will have a new array that will represent the new information. All right, go ahead and give those a try, and then when you're ready, you can review, if needed my attempts. 11. Exercise 2 Finish: all right. Hopefully, you had some practice making your code so it doesn't mutate objects if you don't want them changed. Now, let's take a few minutes. I will just show you how I would have completed these two assignments. So first off, I'm going to do exercise to A. This was the exercise that used the user. It would pull the user out of the array, and then we would modify the data in the user. And then when we wanted to change the ray, we would store it back. Okay, So the first thing I'm gonna do, I'm gonna change this to a concert for its definition so that the users array cannot be reassigned. You remember that doesn't prevent it from being changed, because in a raise, an object. And in javascript, objects are immutable. Therefore, it can be changed. It just can't be reassigned to something else. And generally and functional programming constant use a lot when you define something, use CONST so that it cannot be reassigned until these functions could be done that way as well. Now, the first thing I want to do is create a function that's going to be used for cloning the object. So I'm going to call this clone O B J for clone object. And this is gonna be a function. It allows us to pass in an object, and then it will return a clone of that object which is passed in. So the way we do that, simply return Jason dot parts. This is on the outside. And then inside the princes of that we do J Sonda string. If I So we converted to a string first, the object that has passed in and then that string is then converted back into an object using Jay summed up parts. So that's a simple function which we have learned and that will allow us to clone those objects. So with that created, the rest is pretty simple down here, where we have these different objects, we just need to make sure that we clone them. Now, the point where you want to clone them is before the object is changed. For example, if I clone this object, but I don't clone, the U. S. Are that has passed in, then the change I make here will effect this one here. So that's the trick. Is knowing when to clone it and so simply clone it before you make a change. And so I'm going to simply put clone O B J inside of these parentheses here. So the first thing we call is the clone O B J function to clone this object here. So the object that gets passed in tow, update score is a completely new object is a cloned object, and therefore it's change will not be reflected here. And I'll do the same thing down here for update tries clone LBJ double princes at the end there. And that should allow us to have three separate objects without them referencing the same object. And they're forcing the changes in all places and also the change within the rap here. All right, so let's just try that. I'm going to refresh makes or the code has been invoked. And then let's type usr. So there we see the object for us. Our us are one with, and there we can see that the score has been updated. So thirties been added to that, and then us are too. And there we can see that the tries and the score been updated in that particular object. Now, if we still look at the user's array and open that up, we can see that Henry still has 80 and three. So I hasn't affected that array. If we wanted to change the array, we're ready to do that. Then we could use this store user function and pass in. This isn't quite set up, right? Cause we have store user. We pass in the array and the user, so we want a passing users and then the object. Now, if we wanted to create a new array, we could clone this object here before it's changed. And then we'd have this array and the results of the array that had the user story. Okay, so that was exercised to a just going to save that close. That, and we'll take a look at exercise to be now. Now, remember, this one uses the array, the entire thing it passes in that entire array and then makes modifications. And so what we want to do here is make sure that we have a new array. Each time has passed in a clone of that original users array. And so to do that once again, the same process. We want to set up a clone object function. So this is gonna be the same thing. We did nothing different. We returned Jason bars and in inside of that Jason dot string. If I and we're string defying the whole BJ, this past him. And so that's basically everything we need there. Let's change this to Const. Let's go down here now. James is the const to now. The first thing I want to do is clone this array before we modify the score. So we do it this way. Clone O B J put Principe's around that, and then we also want to clone this array before it's passed in. Or we could just keep that array. And this is the ray we're changing. That's possible, too. It depends on what you're trying to dio. We know that since we just created this array, we're not using it in other places in our code, so side effects would be very minimal, so we could just continue to modify this array Here. I've chosen the creative brand New array, so we have two different race and that will allow us to look all three raise and see that they're all different. So let's go ahead and save that. I mean, open this new page for that exercise so we can take a look at it. Now let's go and look at the user's array. We can see the original hair. Nothing has changed. We see Henry is the same. Let's look at new or a one. See what's changed there. Henry has the score updated to 1 10 and then new array to and here we should be able to see all the changes. So this score and the tries have been updated. So this final Nuri to has are changes in it. So that clone object function is a function you can use to do deep cloning, not the shallow cloning. The object dot a sign does, but the deep cloning that clones and object and objects inside of that object. If they do occur. All right, let's move on to the next topic 12. Using Reduce, Map and Filter: before I cover the next concept associated with our functional programming definition, I want to cover some functional tools that are already available in JavaScript. Specifically, we're going to look at reduce map and filter. Now, when using a functional programming paradigm, we work with a raise a lot. And instead of using traditional loops, toe iterated through an array, we use functions as the paradigm name implies. Reduce map and filter. Allow us to work with the rays doing things we might traditionally use a loop for. These three functions are found on the ray prototype so they could be accessed for any array. Now, these are not the only methods for a raise, but thes mirror traditional functional tools found Fort raise and functional programming libraries. So I would like to teach these tools using the JavaScript approach, and then later you can easily transition to a library if you begin to use a functional paradigm in the majority of your code. Now, if you're not familiar with these three methods, I would encourage that you get to know them and become comfortable with these methods. The more and more you use these methods, the more intuitive they are, and soon the word map or filter or reduce becomes declared of to you. You see it and you know what is going on. It may not start out that way, but that is what it will become over time. Now, before we look at some examples, let me first describe what each method does. First off, these are all higher order functions. They take a function as a parameter now, each method reduced map and filter iterating over the elements in the array. Each element is then passed to the function you provided as a parameter to that function. Now, another important point is that none of these methods modify or mutate the original array. You probably expected that since we've been talking about the functional programming paradigm now let's look at a quick description of each method, and then we will do some simple examples. So first reduce and included with that is reduced right. They combined the elements of an array using the function you specify. So the end result is a combination of those elements were provided just a reminder. Reduced starts on the left side of the rate reduce right starts on the right side of the race. Now map map passes each element of the array to the function you provided and returns a new array that consists of the values returned by that function. And so you do something with each element as it's passed to it. You do something to it without function you provide, and that determines what values get placed in the new array that's created. So, basically, map. You're taking one array and creating a new array from it, very similar to filter filter returns a new array, but it is usually up subset of the existing array. So the function that you pass into filter, though some kind of check on each element and then builds a second array, a new array that usually consists of a subset of those elements based on whatever type of check your doing in that, that function that you pass him. So that's a quick description. Let's look at some actual examples, and we're going to use this very simple array consists of five values, five elements 12345 and we're going to use each one of these three methods on this rate to do something with it. now it's not going to mutate this rate. So even after we've done all of these, this Ray will still be an attack and will still contain the values that we currently show here. So let's first take a look at reduced. Let's say we wanted to get the total of these numbers of every element. The ray. We're just going to add them all together and get the total. Let's look at how we would do that. So we first specify the array than dot reduce because reduces a method on the ray prototype . It's a little way we access. It is with dot syntax. Now we need to pass in a function, and I'm going to define the anonymous function. I'm passing in using the standard key words that were used to. I'm not going to do a narrow function, cause I don't want to complicate this at all for you. I wanted to be a simple as possible so you can understand what the method is doing, as opposed to trying to figure out what the function is saying. Now remember, with reduce the function we pass in can accept at least at least two parameters. One is that the accumulator value? This is the ongoing result. As each elements passed into this function, whatever we do with that element is returned to the function and has brought to the next element as the accumulator and then the second value is actually the element of the array. So it is cycling through each element in this array and does something with them. Now what are we going to do with them? While pretty simple, we use a return statement because that's what returns the ongoing value to the accumulator . And what weird returning is the accumulator plus the element. We're just adding those two together now, the first time through the array when L m. Is equal to one the first time through it, What does accumulator equal? Well, by default, it would work out fine, but we can specify what that value is. As the second parameter, we pass into the reduce method. We pass in the function and we can pass in the initial value of accumulator, which we're going to make zero All right, so that should give us a total which should equal 15. Let's just see what we get. Refresh that open the console and let's display total and sure enough, it's 15 so that's reduce. What you do with that function you pass into the reduce method has a wide variety. It's not simply just adding them together. You can do a number of different things to it. All right, let's look at map next. So map as indicated, returns a new array. So I'm gonna set the return value to a new array variable, and then we access map the same way dot syntax. Now, with map, we pass in a single parameter, and that is the function that we will be using to create the new Array. Now that function will receive each element in the ray as one of its parameters. And so I'm going to set each element the rate to the Val variable. So as it relates to this array, it will first be 1234 and five. Now what we're going to do with mapas, we're going to create a new array which is each of these values squared Now. Since we're creating a new array, we have to return that new value, and that value is going to be each element raised to the second power. And so the way we would do that is V A. L. And then with the S six. There is a new exponentially ation operator, and then we indicate what power wants. Raise that, too. And so the double asterisk indicates exponentially ation. And so we are raising each one of these values to the second power, and that's what the new Array will consist of. So we will have the same number of elements. It's just that they will be squared. All right, let's go ahead and save that and take a look at that one. Now I'm going to type in new array, and there we have. It has five elements in the ray. One squared is 12 squared, three squared, four squared, five squared. So that's map. So when you see map, you should think, Oh, I'm getting a new array that's based upon this existing array. It's going to do something with all of the values in that existing array, and it's going to create a new ray out of it. That's the way you should think about map. Now let's look at filter once again, this is going to return an array. It will be a subset of the existing array. I'm going to assign it to the variable filter array. Once again, we specify the array dot filter, and we pass in a function just like with the other two. So here's my function. I specify a variable to account for each element of the array that's passed in now. What am I going to do in this function now with filter, the function that you pass in to filter should be a practical function on what is a practical function mean? While it's simply this a practical function returns either true or false or something that evaluates to true or false. So what filter is going to do is if the value returned is true, then it will go ahead and place that value in the new array. That element that was it was just acting on. It will place it in the new array. If the function returns fault, it will not place it in the new array. And so that's why we get a subset array of the original rate. So we need to have a function that returns either true or false. So let's say We wanted to get a subset of this Ray, and we only wanted to include numbers that were less than three. Let's do that so we could return either true or false by simply checking if the element that is passed in is less than three. If that returns true, then that element will be placed in the sub array. If it returns fault, it will not. All right, let's go ahead and save that refresh. Now let's take a look at Filter Array, and we end up with two elements in that array, the only two that are less than three. All right, so we've done three different things to the original Ray here using reduce map and filter. But as you can see, the original Ray has not changed something else. We have iterated through each element. That's rate without a loop. There are no loops as a part of this, and traditionally, if we would have wanted accomplish what each of these things does, we would need to use a loop to do that. But using reduced map and filter, we do not Now, as I've been introducing these, I have mentioned that the functions that you pass in, receive at least one parameter, and that's the value or the element in the array as iterating over that array with reduced . We also have the accumulator that we have to account for now. With each one of these, you actually could receive three values. You could receive the actual element. You could receive the index of that element, and then you could receive the entire array itself. If for some reason you needed that in your function, what I want to do is with map. I'm just going to log these out so you can see that it a rates over each one of those. So consul dot log now consul dot log index in consul dot log array. So now, as we move through the map method, we're going to get a log statement each time and iterated through these elements in the array. So let's take a look at save that. So here the first element is one and as an index of zero, and there's the entire array. Second element is to as index of one, there's the entire race. You can see that as iterating over that array. The log statements are what we would expect them to be, so that is reduced. Map and filter get comfortable with them. They're important to any coding you do in JavaScript, but especially if you're using the functional paradigm. Now let's move on to the next movie, where we will look at an exercise. 13. Exercise 3 Start: for exercise. Three. I want to give you a chance to practice using map, filter and reduce. So let me explain what I like toe have you do, and then I'll give you a chance to go ahead and give it a try and then we'll review it. So first off, I've provided an array. This is an array of scores. Now these scores need to be modified to be able to be usable. That's the idea behind this. Now what I want you to do is just act on this array. Don't worry about creating a function that will accept any rate and act on that. Let's just act on this raid and that will give you practice with those three methods later on. We may modify that, but for now, just use the array as it is. So the first thing you want to do is any scores that are below 10 need to be multiplied by 10 and then the new value included in that array. So you're gonna go through this array and so any scores like six and eight year old multiply by 10 and return that and also return the other values as well so I don't want you to modify the existing array. That's why I want you to use map, filter and reduce solar created new array. And then you'll use that new rate to remove any scores that are over 100 and that will create an array. Then use that new rate room to remove any scores that are zero or below and then use that array to some the scores and then use that same array to provide a count of the number of scores that are still remaining in the race. So obviously, with those two values three count and the some you could then later do an average. Now, obviously, the count of an array. The number of elements in an array is simply the length of the ray that property. But I would like you to use the reduce method to figure that out because I want to give you some practice with reduce. That's all I'd like you to do. This will require you to use map, filter and reduce and give us some practice. We go ahead and give that a try, and when you feel you're already go to the next movie to review the solution 14. Exercise 3 Finish: All right, let's take a look at this solution. So the first task is to create a new array from the scores array that will take any score that is blow 10 and multiply it by 10. So since we're producing an array, another array from an existing array, that should tell us we need to use map. So let's go ahead and do that. And like I said, we're not gonna create a function for this. We're just going to use the map filter and reduce methods for all of these and produce new A raise or new values. So this new ram gonna create is boosts single scores. That's what I'm gonna call it, since that's what we're doing to scores race. So I enter scores dot math. Now, remember, map is a higher order functions, so we need to pass a function in to map that will act on each of those values as it iterated through all of the values in the scores array, so function, and then inside the parentheses that function that we provide map will sand each element. Each value as it liberates through the ray, will send each element to that function so we need variable toe. Hold that And so I'm gonna call it Val. Now we can define the function. No, I want to keep these. A simple is possible. So I'm going to use the turn Eri operator in Javascript to do this. So basically what we're doing is we're taking any value that is below 10 and before we return it, we're multiplying it by Tim. But if it's already above 10 10 or above, then we go ahead and return it. So let's look at how we do that. So we need to return something. In order to create a new array, we have to return a value every time we get a rate through and look at each element in this array every time through that, we need to return something. We either return the actual value or return the value multiplied by 10. So we obviously want to use a conditional. That's why I'm going to use the Turn Eri operator. So if Val is less than 10 so if the value this past into the function is less than 10 then I'm going to multiply it by 10 before I return it. And so the way we do that is Val multiplied by 10. Otherwise, we simply return vow. Okay, so that should give us an array with those single digits boosted by 10. Let's just check that out really quick and make sure that's working before we move on. So let's grab this HTML page, since that's the one that JavaScript files attached to. And we're just going to take a look at the console and then the boost single scores array. And it looks like wherever we had a single digit, it has been multiplied by 10 based on the results of its that's working. Now we can move on to the next task, which is drew any score that is over 100. Now this will return a new array as well. We're gonna act on this Ray we have here and return a new array so we could use map to do this. But a really simple way to do it is using filter. And so that's what I'm gonna do, const. And let's call this RMB over scores, just for to account for those that are over 100 we'll set that equal to boost single scores that array dot filter now, just like map with filter, we need to pass an a function, so let me set that up. So as with map, we were capturing the value as it was passed in. We need to do that with filter as well, so we go ahead and put a variable there. Vow. Now the differences with filter the function we pass in is a predicate function, meaning it needs to return either truer faults if it returns. True, the value it is acting on gets included in the new Marie. If it returns Faults, the value it is acting on is excluded from the new array, so basically want to exclude anything that's over 100. So that's pretty simple. We simply need to return either a true or a false so will return the value, and we want it to be true. If it's less than or equal to 100 we can put less than or equal to 100 like this, so that will cause it to return true for any value that is less center equal toe 100 return falls to anything that's over 100 so this value here should get excluded. We'll save that now. The next task is very similar. So let's do that one. Before we take a look at it, remove any scores that are zero or below. So that's gonna be very similar construction. Let's go ahead and just copy this and then we want to call this something else is call it removed zero scores and we wanted to act on this. Ray here is this our new array we're working with? It was gonna pass in the value. Then, basically, we want it to return. True if it's greater than zero. So we can do this because if it returns true, it's going to return the value. If it returns, faults it, we're not. It will not return the value, and obviously it's gonna return false if it's zero or below. All right, let's save that. Len, let's check out those two arrays we've just created. So going to refresh that. And then let's look at RMB over scores first and we can see if the 110 is removed and then that feeds into the next one and our MB zero scores. We can see that removes zeros. All right, so we only have two things left to do. One is to some the scores and wants to ride a count of the number of scores still remaining . And we're going to act on this array for both of those. So both of these we will use reduce. So let's set a another constant scores some. And we'll set that equal to this ray up here, this zero beret where we've removed the zero scores dot reduced now remember, reduce takes all the values in array and then combines them somehow, depending on what we specify in the function that we pass into reduce. So just like map and filter, we need to pass in a function. However, unlike map and filter, we need to include at least two values in that function. Remember, the first value is the accumulator values. So as reduce moves through the array and does something with it, it then returns the results for the next time through. And it continues to do that. And so we just call that accumulator value. It could be named anything, but that helps me remember it Now, In the case of this, since we're summing the scores, I'm going to indicate that that variable is some and then also indicate invariable for vow for the value from the array. And then what we do inside the function is pretty simple. We simply need to return some plus foul. So it'll just add those together and then the sun will go through the next time it'll grab the next value, sum those together, pass it to some again, grab the next value some things together, pass it to some again, grab the next value and so on. So that's how reduce is working. Now we may want to provide a value an initial value for some. In fact, I like to do that. And so I'm going to put zero. Here is the initial value for some. As we start, some will be equal to zero. It will not have a value yet. All right, so that should give us the some. Now the count is similar. It's using reduce as well. So let's just copy this up here, paste it down here and we're going. Teoh, call this scores CNT for count, and we're acting on the same array were using reduce. I'm gonna change this variable to CNT So I understand it's account that I'm gathering this time and not a some. It's still the accumulator value that gets passed back in each time we iterated through that rape. Now the difference says we're not going to do anything with the value. I'm including Eric is it gets passed in, but we're not going to do anything with it. We're simply going to do CNT plus one. Each time through it will add one toe our count, and at the end, we should get a count of the number in that array. Now, obviously would be very simple to do a length of this array. So why am I going through this? Trouble of using reduce while simply cause I wanted you to get some practice with reduced and get some practice with it, not just adding values doing something else, and that's what we're doing here. We're doing something else came all right. Let's save this and check out those last two values. I'll jump out and refresh, and then we need to look at score some that someday everything to 6 35 and then scores count. We need to look at as well, and that's 10 and there are 10 values in that array once we've done all the modifications, All right, so hopefully you were able to do each one of those task, and that gave you some additional experience with map, filter and reduce. All right, let's move on to the next movie. 15. Exercise 4 Start: okay to exercise files in a row. I know it isn't fair, but I wanted you to apply some of those things we just learned with map and reduce to the cold. We've been working on to the cold we've been looking at throughout this course. So here's what I'd like you to do. Let me pull up sublime. Here is the code in the state. It was in the last from the last exercise exercise to when it's the first ah, part of exercise too. So, as you remember, we have this array and then we're doing certain things with it. We've now been able to avoid many mutations because we have a clone O B J function, which allows us to clone the object. So we're not mutating too much now you'll notice is you Look at this. There is a four loop here in the get user function and there's another four loop here in the store user function and the story user function also still mutates Data. What I'd like you to do is revises store user function, use the map method of a raise to change that, and that should return a new array. So this function should in the and return a new array that does not modify the users of rain. And then we could have that new array with the new data in it. Okay, so that's one thing I want you to do, um, and so down here, you'll have to account for that. You'll need to return a new array when you call store user. The other thing I'd like you to do is to use the reduce method. Now, this is a hint. Here. Use the reduce method to retrieve the correct object from the array that you're going to be working on. All right. Reduces the way to do that. Give that a try, see if you're able to be successful. Once you're ready, restart the next movie and we'll go through the solution. 16. Exercise 4 Finish: All right, let's take a look at the solution. Now. The 1st 1 I'd like to work on is store User and, as I indicated, used map for that. Basically, basically, because what we're doing is we're taking an array. The users array and were returning another ray. The differences. We're going to put the user in place of the one we modified. In the case of our example, it's actually Henry, and so it ends should end up with Score 1 10 and tries of four. So since we're creating a new ray that says map, so let's go ahead and see how we do that. Let me comment out this four Luke pair first and then we have the rape Aston dot matt. And then, of course, map requires us to pass in a function, and the functional we pass in needs to have a variable to accept each element of the ray as map illiterates through the race. So I'm just gonna call that vow that should work for us. Now let's go ahead and define that array and what we're going to do. So a lot of the functionality is is similar. We want tohave an if statement in here or I'm going to do it with an if statement. So it's easier to understand we could use a Turn eri operator like I did in one of the previous exercises. But let's do if val dot name. So this is the object that's passed in one of the objects from the array, and we're checking the name property of that, and we're going to convert it to lower case to normalize the data. We're gonna check to see if that is equal to the user that is passed in dot name got to lower case, so that part of the process is very similar now, if it is equal, if we do find its equal than what we return, well, we returned the user because we want the user to be going into that new array if these two are equal. Otherwise, if they're not equal, then we're going to return the value itself So the object gets returned and put back into that new array. If it's not equal to the the user that's passed in okay, that should do it for us, except one thing. This is going to create a new array But how do we get that new ray out of this functionally set up? Well, we simply need to return. They're now a new array will be returned from the store user function. Okay. All right. Let's jump down now to get user and once again comment this out. Now, remember, what we're doing here is we are iterating through that array and we're trying to find the object that matches the name that's passed in. Once we find that object, we returned that object. So we're going to use reduce sold that the entire Reagan's reduced down to one object. And that's the object we want. So let's look at how you do that. So here's our ray that that is passed in dot reduced, and then we need to pass in a function not remember, with reduced or reduce right. We have two variables we need to define. We define the accumulator value and we define the value from the array is passed in. So for the accumulator at value, I'm gonna call it LBJ since its since we're trying to find an object, and then we also have out here. All right, let's go ahead and put her curly braces in and begin defining this function. So if the value dot name is equal to name that's passed in, then that is the object we want and that's the one will return. So let's just set up that conditional valve that named up to lower case. Normalize the data again and check to see if that's equal to named up to lower case. And if those two things are equal, then we will return. Now. Simple is that now, remember, with reduced, we can pass in and initialized value value. That initialize is the accumulator in this case will be J. What I'm going to do is simply pass. And no, we had a returning null down here if it couldn't find a particular object. So I'm gonna pass in. No as that value. So if nothing is found, that's basically what gets returned. Because once again, in order to return what is produced with reduce, we need to add a return statement here like that. Now, before we're done with the get user function, there's one more thing we need to look at. So right now we have this if statement that returns a value if the names are equal and then that value gets placed in the accumulator in O B. J. But what happens if there's nothing equal to For example? Let's say we put in James James goes through the first time it found something equal returns that object the next time through on Mary It doesn't find anything. What happens? That accumulator We need to make sure we return the value that we've already achieved so that we don't lose it. So we need toe add ehlz return O b j So if we find a name, we return that actual object. If we don't, we return the accumulator. Now, if we never find the name, the accumulator that will be returned is no. So we know we never encountered it. All right, That should do it for our get user function. Now, one final thing we need to create a new ray and this is going to store the data that has been modified so this array will have the modified data in it. Let's go ahead and save that and take a look at this. See how we did we open the console, so I'm gonna go through all the objects again. Make sure we're not mutating data. So there's us are 80 and three. Us are one, 1 10 and three us are 2110 and four. Now let's look at the user's array now. Remember before we were mutating this? But look, Henry is the same as it was before, 80 and three. But do we have the new data? Let's look at no rain. Look at new rate. And sure enough, Henry 1 10 and four. All right. So I I feel in a funk from a functional perspective. We've improved our coat. We've avoided additional mutations. All right, let's move on to the next movie. 17. Exercise 4 Follow Up: before we move on to the next topic, I want to do a quick follow up on exercise four. There's something I need to mention about in regards to the code the final bit of code that we came to an exercise for. So let me jump to that code and we'll discuss that now. The two parts of the code that I want to talk about are the updates, score function and the update tries function. Now. Technically, these two functions are not pure. Can you see why they're not? If you look at it, we're modifying this user that has passed in. We're modifying that. Then we compensated for that because we cloned the object down here. And so the end result would compensated for that so that we're not mutating data. But technically we are mutating data. Technically, these air, not pure what really should be done is to clone the object inside of the function. That way, when we return the user, we're returning a new piece of data were not modifying. What has passed in and the advantage of doing it that way is that we then no longer half to clone the object down here, and so we take care of it in the function. We eliminate it down here. Now I want you to be aware of that. We're going to address these functions and redo them in exercise. Nine will be working with the same code next size seven. Again. We won't deal with it there, but we will deal with it. Exercise nine, where we'll redo these functions using one of the library's that's available, and when we re do it, we will make it so that it is pure. It's not mutating anything that has passed him, but I want to make you aware that is currently doing that. And I also want to make you aware of a way to avoid that. If you wanted to modify this function and eliminate the clone object down here, that would solve the problem. All right, let's move on 18. Important JavaScript Concepts: before continuing with functional programming concepts. I wanted to take a little bit of a time out here and mentioned some important JavaScript concepts that are critical when you're trying to understand some of these functional programming concepts we're gonna getting into, such as function, composition and, later, some of the other concepts. Now, functional programming obviously deals with functions as its central point. Therefore, it's important to understand the nature of functions in Java script. So I would recommend if you don't feel really comfortable with functions that you review some concepts in my Advanced Topics course specifically understand why functions and job script our first class understand the concept of higher order functions in JavaScript and make sure you understand the concept of closure that such a critical and an important point in JavaScript and the strength of closures is used throughout any code that is super complex. So those Air three concepts I'd recommend that you understand regarding functions. If you feel comfortable with functions and comfortable JavaScript, then go ahead and continue on. Otherwise, you may want to jump out to the Advanced Topics course, review some things about functions there and then come back. All right, let's continue on 19. Function Composition Part 1: we have almost completed the dissection of the functional programming definition. As you have probably noticed. By dissecting this definition and showing examples, I'm also teaching the concepts of functional programming. In this topic, we will discuss function, composition, function. Composition is the combining of functions for the purpose of producing a new function or performing some computation. Now one of the first questions that may come to mind is what is the purpose of combining functions? Why do we need to do that? And what does it accomplish before I answer that I need to take a step back and look at creating functions When using a functional programming paradigm, Functions can be looked at in one of two ways. As a procedure or a function in functional programming. We want to create functions, not procedures. So from a functional perspective, what is the difference? Most likely, the kind of functions you have been creating would be considered procedures. A procedure is a collection of functionality. It may have inputs, or it may not. It may have a return value, or it may not. It frequently does its work by working on a shared state, but a procedure normally accomplishes more than one thing and requires multiple statements to do that. Functions in the functional programming paradigm are different. They're based on the ideas that come from mathematical functions. Let's look at what these functions air like, first off these functions, having input. Second, these functions return a value, so there is an input and there's a return value. Those are important when we're creating functions for functional programming because we piece thes functions together, which is basically what were talking about this topic. Now, another important part of functions and functional programming is that they're simplified to a single task. So with procedures, we use multiple statements and loops and so forth to accomplish something that we're trying to accomplish with that particular function in functional programming, those things would be broken out into multiple pieces. Multiple functions. They are simplified to performing a single task, not doing more than one task in the same function. So to do functional programming, it is important to create functions and not procedures, and they need to be pure functions now because function are so specific, meaning they only accomplish a small amount of work, it makes them easy to reuse think about that concept if it performs a single task, it's more likely that you're going to be able to reuse that, however, because they are small and specific. If you want a function that accomplishes, ah, larger task and it's one that you would like to use frequently. You will need to combine several functions together to do that, and this is functional composition. So putting those functions together toe accomplish a task, and to make another function that's reusable is functional composition. Let me illustrate this graphically by breaking down a procedure and then turning those into simple functions. So on the left we have an image of a simple procedure. This one's not even that complex. We've written a course and in the process of that course. So we're teaching learners and in the process that we need them to recite something that we've been trying to get them to memorize. And so we use the check words function to make sure it's correct, and to do that, we first do a trim, get rid of unnecessary spaces. Then we split that phrase into an array, and then we check the length of it to make sure that the number of words that are supposed to be in the phrase are there now. We would go on further and do more checking, but I'm going to leave it simple, and we're simply going to do that much. Check the length so those three things would be done in three different statements. Inside of our function are procedure now. Those could be broken out into simple functions so we can do a trim. We can do one that splits up the phrase, and then we can do one that checks the length of the phrase. So those air Very simple, right? Very simple functions notice something else that happens with these simple functions. There is an input in there is an output. So with our procedure, we had a string is the input, and then the end result may be that we're modifying some shared state. Some object in case, whether it's correct or not, or something like that. Well, from a functional perspective, we have an input of a string, and then this simple function outputs a string. This next function the splits, function inputs, a string and it outputs an array, and then the next function inputs an array and outputs. A Boolean, for example, doesn't match the number of words that should be in that array. And so that's why outputs a Boolean, so notice how these simple functions can be connected. The output of one becomes the input of another so we can string them together in order to accomplish the larger task. Now, how does it look when we put those back together? We have these simple functions, and we put it back together to accomplish the same thing. How does that look? Let me just type that in so it would look something like this. There's our string. There's our input to our stream that gets passed into the trim function. The output of trim becomes the input for splits, and so that's what executes next. Then the output of splits becomes the input for check, and that's what executes next. So that's how we would string those back together. Now, the simplified functions. It's easier to tell what the function is doing simply by looking at the name of the function. We have a better idea what's going on, and that's one of the nice things about functional programming. However, however, this is rather difficult to read once you agree the code is backwards and it's nested. So the first thing that happens is actually at the right hand side of the statement here. And so that's what I mean by backwards. And then everything is nested. Now we could put in returns to break it out, to make it a little bit easier to read like that. That is a little bit easier to read, but the readability is not the best. So in part two of function composition, we're going to look at what we do in functional programming to improve the readability when we're doing function composition, their techniques that have been developed to bring simple functions back together because it's such a common thing in front functional programming. Now, before we leave the first part of this topic, let me address again why we're doing this. What value these simple functions and functional composition brings to the table. And to do that, I want to use an example from Kyle Simpson. He's done some riding on functional programming in JavaScript and his writings air available on Get Hub, and I'll go ahead and include a link with this video so you can go out and read that if you like, but this is one thing, he says. When talking about this topic, he says, a functional programmer sees every function in their program like a little simple Lego piece. So those simple functions we talked about, they recognize the blue two by two brick at a glance and know exactly how it works and what they can do with it. As they go about building a bigger, complex Lego model as they need each next piece, they already have an instinct for which of their many spare pieces to grab. So this grab bag of functions that they're drawing on that may be something they can reuse or something they immediately can create because they're so familiar with it now going on, he says. But sometimes you take the blue two by two brick and the gray for by one brick and put them together in a certain way, and you realize that's a useful piece that I need often and therefore you would turn that into a re reusable function, and you can do that with function composition. So this is the idea, this metaphor that Kyle Simpson's use. This is the the idea of functional programming that you need to try to get used to. It's very different approach, but it has a lot to offer. All right, let's move on to Part two and look at combining functions and making them readable. 20. Arrow Functions: before we move into the second part of functional composition, I want to cover Errol functions. If you already work with Arrow functions, you can skip this topic now. The reason I want to touch on a row function is that we will be using them in the next topic, so I want to make sure I introduced them. Errol functions are also widely used in functional programming, so it is important to understand and be able to use them. Let's first take a look at how aero functions differ from regular functions, So first here is a simple function. Some, it adds two numbers together. That air passed into the function and returns the value. Now how would the same thing be accomplished with Errol Functions? Well, now, first off, aero functions provide a minimal syntax so we can do the same thing that is shown in this function with typing a lot less. That's one of the advantages of Errol functions. So here we have a function. Let's look at the same function defined as a narrow function, accomplishing exactly the same thing. So in both cases, we've assigned the function to a variable. No arrow functions must be function expressions. They cannot be function declarations. And so obviously we have I function. Expression here is we're assigning the function to a variable. We have the parentheses. These are the parameters so that we're able to pass in arguments. We don't include the function keyword that is replaced by the arrow, which is created using the equal sign and the greater than sign. Not only does the arrow replace the function keyword, but it also indicates what should be returned. And so once these two values are added together, it automatically returns those two values. So minimal syntax, As you can see, we don't have to type is much. And there are certain situations where that's kind of nice. Let's look at a few additional examples because aero functions are a lot more flexible about what you need to include. Here's another arrow function and notice that this one does not include the parentheses, and that's because we have a single value being passed into the function, so the parentheses are not required. It's still returns the value of this number that is passed in multiplied by itself. Another example. This one simply returns the number 100 that's all it does now. In this case, we need the parentheses because we have no parameter. Nothing is being passed in, so we need to include the parentheses, so some different ways to define aero functions. Now you can have the curly brace scenario functions. For example, if we had more than a single line, we would need to use curly braces for that. Now, with that quick introduction to Errol Functions, let's continue with the second part of function composition. If Errol functions are brand new and you feel you need to practice creating a few era functions before viewing the next topic, I would encourage you to do that, create some simple functions and then convert them to arrow functions. All right, let's move on. 21. Exercise 5 Start: Now, before we move on to the second part of function composition, I want to give you an opportunity to practice Errol functions, especially if you have not used them much in the past. So let's take a look what I'd like you to do. So this is where we left off in Exercise three as you were looking at practicing map, filter and reduce. Now, these particular methods map filter and reduce our many times very good for using Errol functions, especially these examples that we have here because there's a single line, usually a single statement involved. And that is when I usually choose to use a row functions. If there's multiple statements and I'm gonna have to put the curly braces anyway, many times I'll just use a regular function because I think it reads better. But with simple functions like this, I think Carol functions are very nice. So what I'd like you to do is convert thes Tuero functions. These functions that are passed in to the different methods convert them to arrow functions . You should be able to reduce everything every statement to a single line. So take a moment to do that and then start the next movie when you're ready to review 22. Exercise 5 Finish: All right, let's take a look at the solution now for me. When I was transitioning to Errol functions, learning to use a row functions more. A good practice was converting existing functions is that's why I had you do this particular exercise. And also another reason to force you into arrow functions or to make you use them or, if you haven't used them in the past, is they're used extensively and functional program. So if you need to look at code that someone who is following a functional programming paradigm is using, you're gonna see a lot of Arab functions, and as you get more comfortable with it, you're going to want to use them more, especially in this type of situation like we have here. So let's go ahead and convert all these tarot functions. So first off, we remove the function keyword because there is only one parameter in this particular function being passed in. I don't need parentheses around it. I'll add the fat arrow that indicates that it is an arrow function that I'm gonna return or remove the return key word that's no longer necessary. And since we removed the curly Brace and remove the one down here and there we go. We have our first era function. Here's the value. The fat arrow that indicates it is a narrow function. Then this is what's returned right here. All right, let's move onto the next one. So once again, I'm going to remove the function keyword, and we only have one variable, so I don't need the parentheses. Gonna add the fat Darrell and then I'm gonna remove this part of the end. And there we have value that's returned. Is vowel less than or equal to 100. So this is predicated function returning either to our faults. Now removing the zero scores. Let's do that one really quick, Remove the function, keyword. Once again, we only have one parameter again police with fat arrow and then remove this last part here knows how we're getting all these down to a single line. They're wrapping because of the size of my editing window, but they're all on a single line now. This next one is a bit different. We have to variables. So we want to keep the parentheses, so I'm just going to remove the function keyword Then add the fat arrow. Then remove the curly brace semi colon there. And we have the second parameter being passed in for the reduced method. And for a move, zero score is gonna be similar because we have to variables there as well. So I don't want to remove that open friend their own curly brace semicolon. And there we go. We've got those change. Let's just see if they're working else. I'm going to save that and come out. Not sure. Refresh the page. Open up the console and we're going to take a look at those Constance. So Booth single scores. We have boosted the single scores there. Removed the over scores. The 1 10 is gone. Remove zero scores. All the zeros are now gone. Scores some 6 35 and scores count using the reduced method to get the length of the array. And that comes back 10. So there we go. Same code. But now we're using arrow functions. All right, let's move on to the next movie. 23. Function Composition Part 2: to finish up our discussion on functional composition. I want to show an example to help illustrate the concept. I'm going to keep this a simple as I can. So let's say I have a function, not the simple type found and functional programming, but the procedural type. Basically, what it does is it prepares a string from a field entry for comparison, and the purpose of the comparison is determined. If the correct phrase was entered, it would be used in a quiz type application. So what it does is it trim spaces off the string, then removes punctuation, then capitalizes the words, then converts the words toe Honore. So it ends up with an array of words and then finally removes articles. So any articles that air found within the array is simply removes those. So here's what it might look like. I'm just going to copy and paste this in so you don't have to watch me typing it. He jumped a sublime. So here's our initial string innovation distinguishes between a leader and a follower, and then here is our function. Simply call it prepare string. So first thing it does is it trims this string here and then using regular expression. It replaces those four punctuation marks with nothing, so basically removes them. Then it converts to upper case and then using the split method, it creates an array of all the words. And then we use this four loop to cycle through that array. And when it finds one of the articles a N or the, it simply removes them using spice. And then the last thing it does is it returns that array. Now we could simplify this function. We don't need tohave every single line like this. As we move through each of those processes. Let me show you how we might simplify that. I'm gonna copy in a new version and here we go. This is simplified using what we call chaining. And the reason I wanted to show this is the concept of chaining is similar to the concept we will be using as we compose functions together. So what we end up with here is we let air are equal the results of the string that we trim and then using dot notation, we immediately change another function. Replace it Does that dot notation to uppercase dot notation split and so it does all of those and then we can cycle through the array and move the articles Now the reason chaining works is because in this case, everything is acting on a string. And so the object it's acting on the object rapper for strings I should say, is all the same. And because it's all the same, we're able to chain these functions like that, and it works. Now. I'm simply introducing that because it's similar to what we will be doing when we compose functions. Now, as mentioned, when we take a functional perspective to this, we want to break these out into single task. So all of these different things that this function does, we want to break out into functions that do a single task. So let me show you how we've done that. I'm gonna copy this part in as well, doing some copying and pasting here in the first to save some time because this is already a pretty long movie. Now here's our string again. No notice how we broke all those different functions out. We have a trim function. We have a no punctuation function, removes the punctuation we have a capitalize function is simply converts to upper case. We have a breakout function which simply splits those on the space so it breaks him out into an array. Then we have no articles function and that no articles function is used by this function here that filters out they are articles. And what we're using inside of this filter articles function is the filter method of the arrays. Now, a little bit later in this moving and going to be talking about reduce and reduce right, which are also methods that belong to a raise filter is one of those as well. We're going to delve into this in more detail in a later movie, so I'm not going to spend a lot of time explain this. But basically what happens is filter cycles through every element of the array, and it uses this function here to determine what elements in the array should be returned or not returned. And those that are returned create a new array. So basically returns everything but a and and, uh and so we end up with this new race. So that's how that works. Now we have six functions now. We've broken these out into very small single task. No, think about this. Think about how reusable this is now. Each one of these functions can be used in a lot of other places, whereas when we had had them combined to gather in a single function, the only way we could you reuse that function is if we had a situation that was very similar. So it's very specific where these are less specific. These could be used in a number of situations. Now, before we continue on and look at composing these together, I want to convert thes Tuero functions. And reason I want to do that is because, and functional programming ero functions are used extensively now. We've introduced Errol Functions earlier, and so you know the advantages of them. So I'm going to convert. Each of these tarot functions now. Also noticed that I define these functions with CONST. That's something that happens a lot in functional programming as well, because we don't want to mutate. Cost is used frequently. So here let's set these up with aero functions. So get ready to function, keyword. And then here is where the Fat arrow belongs indicates it's a narrow function, and it also indicates what is returned. So there, that one's on a single line now, and the rest of these can be reduced to a single line. Also, fat arrow. No, if you don't have a lot of experience with era functions, you may look to see if you know what to do to change these to a narrow function as I'm going through and changing them. So let me talk through that with the breakout function, so we don't need the function key word when we create Errol functions. But we do need a fat arrow and replace of the function key word and the return key word that indicates that it is an arrow function also indicates what should be returned. No articles will turn into a narrow function as well, even though we're using it as a part of another function. And perhaps especially because we're using it as a part of another function, will turn it into it an arrow function and then finally filter articles. All right, we reduced those down to a single lying. Now each of those simple functions no has mentioned. Since we've broken these out, the different functions could be used for a lot of different purposes in a lot of different places. But how do we put the whole thing back together? So if we want to have the same functionality we had before, we got to put these back together somehow Well, here is one way to do that. Let's say we wanted to log the results to the console. Well, here's what that might look like. So over here on the right hand side of this statement, we first trim the string and then that gets passed to the no punctuation function that executes on it, that results of that get passed to capitalize that and invokes and capitalize everything, then gets past the break out that invokes creates an array that array gets passed to filter articles, which is invoked and eliminates all of the articles. And then we log it to the council. Now this is just very difficult to read and even difficult to enter. Think about if we had to enter. This is backwards to think about because you have to think, um, let's see, I need to trim first. But the last thing needs to be showing up here is filter articles. And so you end up doing something like this trim and then you come back in the results of that need to be passed into no punks, and then the results of that I need to be passed in to capitalize and so on. So that's a process you go through. So not only is it difficult to read, it's difficult to enter. And plus, if we want to do this same functionality again what I've entered here, we would have to enter the entire mess again. So we need a better way to put these functions together. We need a better way to compose them, and that's the concept we're talking about. And once they're composed into, ah, another function, we can use that function over and over again. Plus, we can still use each of these individual functions as we need them. Now there are functions in functional programming that can help us with this problem of composing these together, and they are traditionally called pipe and composed. Now, JavaScript functional libraries have these types of functions already built in, but we're going to create them so you can understand what they are doing. I think that is important now. The main difference between pipe and composed is the order. You are able to enter the functions that you want to put together. So here's the functions we put together and we had to enter them from right to left. Trim is on the right side, going left. That's the order. They are executed. So that order indicates how they're invoked. Now, compose is right Toe left exactly like what we've done here. Pipe, however, is left to right now we're going to take a look at Composed first. Now, as we look at this composed function, I will also introduce a couple of JavaScript language features that are used in functional programming that we haven't introduced yet. So I will put that compose function in. But first, before we do that, let's just run this and make sure it's working for us. We have messed up any of these functions, So if I open the console, we get an array and is array of all the words knows the articles are gone, spaces are gone, Punctuation gone. All that Okay, so it's working for us. All right. Great. So let's jump back. And here is the composed function. Comment out. Consul log and pasting are composed functionally. Some returns now down here is where we're creating a new function. We declare it with const. We call it prepare string and then we call, compose and then notice what we pass in. We pass in these functions we've created up here, and it's right to left trim. No punctuation capitalized breakout filter articles. Now one thing that's nice about compose and pipe functions is that you can enter. You're functions like this because we're simply passing in parameters. We could put them on separate lines, notice how much easier that is to read. Even though we still have to read from right to left or in this case, from bottom to top, it is still easier to read. That's an important thing we've achieved with composed. Now let's first see if this is this works, then we'll come back and explain how it works. So we've created a new function, prepare string, and then we're gonna lock to the console, prepare string and we're passing in. Str the same string from up here. I've commented out this console log statement. Let me go ahead and say that jump back out. Refresh. Let's see what we get in the console. We're getting the same words in the array, so six elements in that race. So it's working for us. Now let's explain how composed works and hang on to your seat. This is not simple stuff. Toe understand, unless you're used to thinking functionally with higher order functions. Now let me just say, if at the end of this video you are still struggling with this, then replay it. Also, I've provided a few links to different blogged articles. Sometimes it's helpful to have functional composition in this case. Explain in more than one way it can help you understand it, so replayed as many times you need to. And then you can look at those blogged articles as well. So let's break down what composed is doing. And first I need to talk about a new feature of the job script language that we've introduced her. This is an operator that was introduced in E. S. Six. It's called the spread operator, and that's thes three dots right here. Basically, what it is doing is it's taking all of the arguments and bringing them together into an array, and then the variable that points to that array is FNS. So is taking all of these arguments that are being passed in, and then it combines them into a single array. And now that array is FNS. So that's what that's doing. That's what that spread operator does, just so you can see that really quick, let me enter or let me do this in the console. Me Jump out here and we'll go ahead and enter a simple function. There it is. We have the spread operator, and the variable is going to placings in is Cool. Then we simply have a consul dot log and we log out cool. So now let's call that, and we'll call that with 12 and three. Nomo's what logs to the console. An array with three elements 12 and three so you can see the spread operator working there . It combined those into an array. Now, just so you're aware in other situations that spread operator can do just the opposite. It can expand an array into different parameters for a function so often raise passed in, it can spread them out into different parameters. All right back to our composed function. Now, the second point that we need to mention is that compose is returning a function that return function becomes the new function that we can use in prepare string. So right here, that's this is what gets returned to prepare string. Now something that's important to realize with this return function is that closure is created over this variable. So it has access to that array. And that array, remember, contains all of the functions that were passed in. Okay, so this function that is returned has access to the array, and we use it right here. Okay, so that's what's inside of prepare string. Now, when prepare string is invoked, then this part needs to run. It's going to return something, and the results of what will return is the array and he uses reduce right to act on the array now reduce and reduce right are very common. Array methods that are used in functional programming, reducing reduce, right, do the same thing. But one starts on the left side of the array and reduce right starts on the right side of the ray. So it's going to start here now. These air higher order functions just like Filter. I mentioned earlier that take a function as a parameter. And the purpose is to use that function to reduce all the values in array into a single value. So it iterating over each value in the array until each value has been passed into the function that we provided and that for function determines what is done with those values. So let's look at what we're doing with the values that are passed in. Here's our function that we provided to reduce, right. So what it is doing is it is taking the second value that is passed into the function we provided, and it invokes it with the first value as a parameter. So the second value is invoked, using the first value as a parameter. Now reduce and reduce right are set up sold that it passes the function. This function right here, the function we provided to reduce right, it passes that function certain values. Now, obviously one of those values needs to be the element in the rake is going to cycle through all the elements in the array. One of those values is the element that is currently being processed, so the first time through the rate trim would be processed. Now that is passed as the second parameter. So right here. That's where trim would be. In the case of reducing reduce right, The first parameter passed in this one right here is the accumulated results of the previous iteration. So on the second time, through this value will consist of what was returned here, so trim being invoked with something passed in as an argument. Now we have the option with reducing reduce right that for the first iteration, since there is not an accumulated result, we can pass in an optional argument the axes that value during the first iteration. And that is what X is in the case of the code we're looking at here. So this function gets returned and is what prepare string is the argument that has passed into prepare string becomes the first value that is passed into reduce right, and so trim is invoked on that first value, and that's what's returned for the second generation. So let's step through this so we can see how this is working and I want to do that on a second page here so we can walk through it step by step. So first off, here is the array that gets created with a spread operator. Truth is, on the right hand side filter articles is on the left hand side. No, After the first iteration, the accumulated results is this. Now we mentioned that trim is invoked and it has one argument which is X on the second generation trim with ex gets passed in as the accumulated results. And this is fat into the first parameter B. So the next element from the array is fed into the second parameter. So after the second generation, we would get this. Now we're on no punked as we go through this array. And so this got passed in, has accumulated results. This got passed in is the next element. And so it puts those together. Then all of that gets passed in for the next generation. So after the next generation, we have this capitalized gets added to that, and once again, that gets passed in and break out is the next element. And so we get this. And finally, after the last iteration, the following is returned. So we have filter articles and then we have a return statement. So then when we invoke, prepare string and passed in a stream, str it goes into X and then once reduce, Wright has finished its work. We get this line of code right here that we showed now, since these are functions, the parentheses caused the functions to invoke. So in the end, all these get vote, the results get passed to the next one, and finally it returns results we see in the console, which is what we see right here. So that is composed. And that's an explanation of how it works. Now. Many people prefer pipe instead of composed with composed. We still have to think a little bit about the functions from right to left her from bottom to top. So it's not quite as intuitive as it could be. Pipe just switches the order, So instead of reduce right, we would use reduce. And so here's how we would create pipe. I'm just going to add it. The composed function. We'll leave everything the same except will reach will change, reduce right to reduce and will change the variable to pipe. Now let's look at how much easier it is to enter. So I'm going to create Prepare string again, this time using pipe and I'm going to each line. I know the first thing I need to do is trim Easy, No pumped. So much more intuitive than I need to capitalize. Then I need to break it out into an array. And finally, I need to filter articles. So let me say that and check that one out as well. I refresh. Oh, I misspelled something. No punked. Right there. Save it. Come back, Refresh. And there is our array, same array we've been achieving before. So we composed a new function, and we composed it from all of these functions that we already have. So these are reusable. Our new function is reusable. And if we plan to use it over and over again, we would add it to our Java script file that contains the function we use frequently. So that's something you do in functional programming. You would save these and they would be organized in a way that makes sense to you. And then when you need those functions, you use that Java script file. Now, remember, both composed and pipe are found in library, so you don't need to build in them yourself if you use those libraries. But we also looked at how you can build them, and we went through them. So you can understand what is going on now. These are pretty complex topics going through and trying to understand it. Don't feel you need to understand it all at once. If you did, then fantastic. All right, let's move on to the next topic. 24. Exercise 6 Start: Let's take some time to give you a chance toe practice function, composition. So that's what we're going to do. An exercise six. Now here is the code, which we left off last time. We're working with the map filter and reduce methods. This is what we completed. This is what we're going to work with. An Exercise six. Now. What I'd like you to do first is convert each statement to a function that can accept an array and not just act on the scores. Ray. Right now, this one's acting on the scores, Ray. And then this one's acting on the ray that's created from that and so on. We just want to create a function where you can pass in an array, and it will do the same thing to that Raiders past him. So that's the first step in this exercise. Once you have that done that I'd like you to compose a function that will remove both the zero and lower scores and the scores that are above 100. So that would be taking and composing this function that's created from this and the function that's created from this now with a composed when you're doing the compose. I want to show you that the HTML pages provided as a part of this exercise links to an 80 gs dot jazz file. Want open that really quick? As you can see, this contains a pipe function and a composed function so you don't have to write those. You can use either pipe or compose. I'll let you decide what you want to do. And the answer. I'll probably use pipe because I prefer that, but you can use either one, so that's available to you. So that's the second thing is composed of function that were removed. Both of those, though zero below and those over 100. Then I want you to compose a function that will do all the modifications to Andre. And so that's all of these modifications. Now, in composing that one, you may want to use a part of that. The function that you've composed here or you could use thes two again along. Sorry, these two again, along with this one, that's the third thing. The fourth thing is to create a function that will accept an array and return the average eso create a brand new function receive an array and then use the sum scores function the one you're gonna create from this functionality and the count of the array. Or you could just use the length. Once again, I forced you to do this with reduced so you could see how reduced could be used for that. But if you want to exclude that now, you could just use the lengthy array and return the average. Finally, I want you to compose a function that will do everything. It will prepare the array of scores, and then it will return average now for testing. All of these use our scores array up here. But you're functions should accept any array. All right, go ahead and give that a try. Once you want a review, start the next video and we'll go through it. 25. Exercise 6 Finish: All right, let's go through this exercise. So the first thing we need to do is convert each statement these statements here into a function that can accept and act on any race. So not just working on the scores Ray or one of the previous races were created, but anyway, so let's go through and do that. I'm going to use these statements that are already here, so don't have to recreate much. I'm gonna call this function single scores by 10 just to try to give it an idea with its name of what it does. So single scores by 10. And that's going to be a function. We're going to accept an array. There's our statement. We need to now change this to act on the array that has passed in close the function there . And then there's one more thing we need to dio. Since this is a function we created here, we need to return the results. So we need to add a return statement right there. Now, if you chose to do this as Errol functions, then great. I'm glad you did that. I'm a little different in my choices of functions. I think Sometimes when we mix arrow functions together, it is more difficult to read. And so if I already have a narrow function, all usually use a regular function. Or if it's a function that has multiple lines, I'll just use a regular function definition as well. Now let's go on to the next one. I think I'm gonna leave the name of this function the same. I think that explains what it does. Remove over scores so we'll set that equal to function. We're going to accept and Ray again. There's our statement, but we need it toe act on your A that's passed in, and we need to return that. And then we need to close our function with curly braces. There there's our second function. Zero scores, I think explains what it does as well. So leave that name and then once again, changed this to the ray that's passed in and return it. Finish off that function like that. Now something The scores. I want to change the name of this function. I wanted to be some scores because that's what is going to do. It takes in an array and then returns to some of the scores in that ray. So using reduce, it gets that some. And of course, we need to return that value as well. So we'll do that. Then finish off my function there and I'm gonna change this one as well, even though I'm probably gonna use the count now. But I'll change this to a function and that takes in an array as well and simply returns the count. So we needed to act on that array, and we needed to return that value. All right, so we've got all of our functions created that we're going to be using. Now, before we move on, I'm gonna come down here and create a function that will accept an array and return the average. So let me create that one first before we move on. So I'm gonna call this compute Average Passing and Ray, and this one I could have done is an arrow function. I have the same issues, is what I described above. We want to return the results, and what we're going to return is the results of this function. So some scores send that array to it divided by this array dot or it could be calling count scores over here as well. We could simply replace that with count scores and passed the rape, so that would return the average. So we got that function created. Now we can go ahead and start doing are composed. So first off, composer function that will remove zero or lower scores and scores over 100. So that's basically this one and this one. We want to do both of those. Now, I'm gonna use pipe. As I mentioned in the introduction to this exercise, we have an 80 GS file, has both a pipe and a composed function that we can use to do this with. And so I prefer to use pipe. So here's how I want to do that. I want to give this ah, function and name. I'm gonna call it removed both high, low like that. And we're gonna set that equal to pipe so the functions is going to be created by the pipe function. And what are we passing to pipe? I'm gonna go ahead and press return here because I think it's easier to read if we put these on separate lines. And first I'm going to call removed over scores. That is the one function up here that removes anything greater than 100 then all remove zero scores as well. So I'm gonna put that on a separate line. RMB zero scores put a semicolon at the end here. So there we have our removed both high and low. Now, at this point, it may be a good thing to test dysfunction, just to see if things were working up to this point. So I'm going to just create a new ray here, and we're gonna set that equal to our new function, the and what a rare we're gonna pass in scores so I can check the no high low Ray and see if it's removed the upper and lower scores gonna go ahead and save that. I just want to make sure I have the right file out here for testing this. And if I go to the console and it looks like we got rid of the zero scores and we got rid of the scores over 100 so that seems to be working for us. All right, so we got that. We compose that function using pipe. Now we want to compose the function that will do all the modification to Andre. And I'm going to use this function I just created to compose a new function. I will use this. Plus this one. That's how I'm going to compose it. And once again, I'll use pipe. So let's call this prepare array or prepare scores. Let's say prepare scores. Use pipe for that. Once again, I'm gonna do these on separate lines. So first I'm gonna remove both high and low. And then the other thing I want to do is single scores by 10. That's the one that will multiply that individuals, the single digit scores by 10. So that would give me a prepare scores. All right, let's take a look at that as well and see how that's looking. Have been working for us. So I'm gonna say prepared Array. This is what I'm gonna call this array and prepare scores. That's the function I want to use. I'm gonna pass in the scores array. So let's take a look at prepare toe Ray and see how that there we have our individual or a single digit scores have been multiplied by 10. So that's working for us. all right, We only have one more thing to Dio Now. We have this function already created so we can compose a function that will prepare an array and return the average. So it's going to do everything for us. So this is one would want to call if we want to do all those things. We now have a function we can call if we just want to remove the high and low scores. We also have a function we can call if we want to remove the high and low scores and multiply the single scores by 10. And then we have all of our individual functions as well. So you can see the reusability here. You can see how we are applying more more of these functional programming concepts. All right, so the last one, let's call this prepare and compute a ve for average use pipe for this one as well. And since I have this function already created, I can just call that one. I conclude that as a pipe, as a part of the pipe prepare scores and then a 2nd 1 would be compute average. Now, in order to test this, let's set a variable at A ve average equal to prepare and compute average. And we're gonna pass in the scores, Ray once again and let's see what our average comes out to be good. Say that refresh 63.5. So taking our functions we created, we have then composed additional functions, which we can use for specific scenarios. All right, let's move on to the next topic. 26. Understanding Arity: before we can complete our discussion on composition and how we use it, we need to deal with charity and how it affects composition. Now to introduce everyday, I want to present a problem we run into with composition, and I want to use the code we have been working with in the past. Now this is the code we left off in with Exercise four. We were updating users. We had this array of users and we're updating used a specific user, Henry. We're updating the score and the tries. And so we had several functions to do that. We're making most of those functions pure. And then down here is where we actually do the update, and we create new users each time by cloning the object. We're not overriding existing users Now. How would we go about doing this same thing using composition? So let's take a look at that. Let's say I wanted to start using pipe to do this, and I'm gonna call update users. So what I'm gonna do is composed this portion here. I'll leave the store user at the end if I want to replace that user. That's when I'll call that But I wanna compose all of these together into its own function named update user. So we would use pipe to do that. And then we would start putting in these users. And the 1st 1 is get user, but notice right away. We have an issue notice the get user has to piece of data that are being passed in. So that function has two parameters that is going to cause a problem with composing. Remember, with composing the output of one function is becoming the input of the next function. What if the next function requires two inputs? This one down here is well, update score requires two inputs. So this function is parameter to that has considered the charity of that function. So that has an aridity of too. And so does this one. Has a narrative to composition, works with functions have and charity of one. So how are we going to go about doing this? How are we going to make it so we can compose these functions together? Well, that is where partial application or currying come in. And I'm gonna introduce this slightly as I show how one way we could solve this problem, and then in the next video, we're going to go into this into more detail in order to help understand how it's working. So what if I could create a function that would already have the users array bound to it? If I had a function already had that bound to it, then I wouldn't have to pass it into the function. I would simply have to pass in Henry. And what if I had a function that had the 30 value bound to it so I wouldn't have to pass that in? All that have to do is pass in user that would allow me to then compose these together. Well, it just so happens that in JavaScript we have a way to bind things to a function, and that is actually a method off functions. And it's bind Now. If you've used bind in the past, you've probably used it toe bind. The value of this and that's what it's used for many times is to bind this value. We're not gonna be using it that way in this case, and it's unfortunate as these two applications. It might have been nicer. They would have separated those into two different methods. But another application of bind is it allows us to do a partial application of the parameters that are being expected. So in addition to binding this, we can partially apply. One of the parameters in this case will do the users array, which is up here. So let's look at how we do that now. Buying creates a new function. Whenever you use bind, you end up creating a new function. So let me go ahead and do that. I declare it with constant, and I'm gonna call it part, get user so partially applied, get user partial application of get user. And what am I gonna do with to create that I'm going to use get user The function that we already have dot bind, bind his method of functions and Soto access I use dot bind, and then the first value that we need to pass in to the bind method is the value of this. Since we're not using that part of bind, I'm passing in. No, The second part that we pass into bind is the value that we want toe partially apply to the function. So in this case, let's pass in the users array up here. This one we're gonna pass that in that's going to be bound to this new function. So it already has that parameter. That's what it's going to dio. So now we can use this function instead of the get user function. We can use this one, and it will only expect one parameter because it already has one parameter associated with it. So it will only be expecting the second parameter. This one's tied to the first parameter. Okay, Now, if we wanted to do the same thing with updates score. We have a bit of a problem because we want to buying 30. However, 30 is the second premise is not the first parameter. And remember, what gets passed in with buying is the first parameter. And so we need to turn things around with updates, score, and so the way I'd correct that as I'd come up here to the update score function and I'm gonna turn these parameters around. So I'm gonna put new A M. T at the start and user as a second parameter. That's the only change will make. Now we can create a another function that is partially applied and we'll call that part. Update score. Put it upper case you here. And we're going to create that by doing updates. Score, stop! Bind will pass in. No, for the value of this. And we're going to buying 30 to it Now. Probably to make this more descriptive. May want to call it partially update score 30. Something like that. So we know that it's 30. That's bound to it. All right, now we've got that taking care of. I can comment this out, and we're going to compose an update user function. So the first thing we want to do is part get user. We're gonna call that function first, and that's going to feed into the clone object. We're gonna clone the object before we do anything else with it, and then that will feed into the part update score 30 that we just created up here. This function here just gonna coffee that and then finally, we can update tries. I'm not gonna clone the object again because I'm not storing it in a variable anywhere. I won't be storing the results until I call this function, so I'm just gonna call update tries. All right, so that will be our new function created using pipe. So we compose those functions together, and then we can call this update user function to update Henry. And I'm gonna have the results of that stored in Just call it newest user so we can see this new user that we've updated. And what am I passing into That, Henry, I only have to pass one parameter now because we bound the users are a to this part, get user function when we bound. 32. This part update score. 30 function. So let me say that and see if that works for us. I'm gonna refresh this and open the consul. We have a Syntex there. I have no idea why I put that equal sign right there. Say that again. Refresh. Now, let's take a look at newest user. And there we see the Henry user scores, run out 1 10 and tries for 1/4. So we now have a new function. We composed a new function update user that allows us to pass in any user, and it will update the score by 30 and update the tries so you can see that what we've done here with partially applying this, we've made these functions very specific. This function on Lee works with this users array and this function on Lee works If we're wanting to update the score by 30 the idea here is I want to introduce this concept, the concept of charity and how it affects composition and then present a simple way provided in javascript for us to deal with that, however, partial application is very common and functional programming impartial application is very similar to currying. Incurring is probably what used most and functional programming. So we're gonna talk about these concepts a bit more in the next topic, so let's move on. 27. JavaScript Concepts for Understanding Currying: in this topic, I want to reinforce a few JavaScript concepts that are important to understand in order to grasp partial application and more specifically occurring. And those concepts are charity, which we have introduced, the use of higher order functions in JavaScript and closure. If you haven't reviewed these concepts from earlier in the course, I would encourage you to do so before jumping into this particular movie. So first, let's talk about charity, even though we've introduced it in the last topic, I want to make sure it's clear. Charity refers to the number of parameters of function has. If a function uses one parameter, it has an charity of one. Now, if we look at these three function examples here declared three different ways, the 1st 1 has an parity of to they're two parameters there. The 2nd 1 has an charity of three. The third has a narrative e of to Now, as we've dealt with function composition in the past, functions have an aridity of one with similar type. You're able to compose together and so arid. He is an important concept in functional programming. We continue to deal with it here now, partial application and currying is how we take functions within a ready higher than one and turn them into multiple functions with the narrative. One partial application incurring make use of higher order functions and closure to make it possible to reduce multiple charity functions into several functions within Arat e of one. I'm going to use a very simple example of partial application, basically partially applying one of the parameters of a function toe hopefully show how these concepts are used. All right, let's say we have an application when we do a greeting. A greeting happens all the time, so we're constantly calling a greeting function and we pass in the greeting we want to display and the name of the user. And so this is happening over and over again. Let me just get a few of these up here. There's James, one more Mary in this one. So throughout the application, we're calling the screening function multiple times now. Notice something with these three calls. There is something that is repeated, well, one way for not repeating ourselves. We could just hard code this greeting as a part of the function, so let's look at how we would make this happen if we were doing it from scratch. So I'm gonna create a function, and I'm going to stick to the same example. So I'm not going to create a general curry function. But to show you how it works, I'm just going to stick with the example of a greeting. So here is what's called the outer function. Now the way we can get this to work is to have the outer function receive the parameter that we want to continue to use over and over again in this case, the greeting, and then have it return a function that will then apply the second parameter. So the greeting is received, and then we return this and then the only thing we're gonna have this function do is just log to the consul, agree? Just keep it simple. So now they're we've reduced the charity because look at how we would use this. I'll explain how it works in just a minute, but here's how we would use it. Let's say he wants to make a welcome Greek function. We make it by calling the curry greeting function and passing in greeting. Then when we want to display Welcome. We just call that function and C were no longer repeating ourselves. Now the reason this works is because this inter function that gets returned has access to the outer function scope. It creates closure over the greeting variable and so therefore continues to have access to whatever we passed in when we set up our welcome greed function. And now welcome Greek could be called with a single argument and therefore has a charity of one or is a urinary function. Now let's just see this work so going to save that, refresh him and open the console and you can see we get a welcome Steve. Welcome, Mary. Obviously, I did not include a space which I should have done there again. No, make a look a little better. So that is an example of using closure to return a function that has a reduced charity. That returned function still has closure over any other values that were previously given closure and being able to return a function from another function which is using higher order functions are key concept for understanding, currying Let's go ahead and move on to the next topic 28. Deep Dive into Currying: in this topic, we're going to continue our discussion on currying now. These topics we have been covering can be difficult to understand. If you find you're struggling with the concepts, re wash them as many times as necessary and try the examples yourself until you feel comfortable with them. Now currying impartial application are very similar concepts. But before we jump into possible differences, I need to remind you of why we're doing this. Why we use currying or why we use partial application, and that comes from understanding its advantages. Now one of the advantages of currying is it will take a function that expects multiple arguments and reduce it to functions multiple functions that expect only a single argument . This will allow us to use high charity functions as a part of composition because composition needs functions that expect a single argument, we can call them you. Neri functions, So help us understand currying Let's look at a couple of examples of functions were trying to compose together in this first example. I want to start high level to help you understand what is going on. So we have three functions here, eh? Fungi Fun H Fund one expects three parameters two and three. So let's say we wanted to compose these together. How would we go about doing that? So we're going to create a new function, and we're going to use pipe to compose these together. Now, the difficulty is, these all expect more than one argument. So we can't just put this kind of thing in there What worked for us? Because we have to account for those other arguments. So this is where currying comes in. We want to reduce these functions down to a point where they'll accept one argument at a time. So one approach would be to create three new curried functions. So it looks something like this. We have a curried F a curry G and a curry H, and we create those by calling ah curry function. Now in the A. T. J s, I've added a function that does currying for us. This was borrowed from Kyle Simpson's work. He has a book on functional programming and this is a curry function which he provided as part of that. Now, in the next topic will go into this more detail. But right now I want us to understand how we're putting things together when we use a curry function. So, like I said, one approach is to create three new functions a curried, a function, a curry G function and a curried h function and see how we've done that. We've called Curry and we've passed in those functions just like that. Now that we have those new functions, we can do this sort of thing to compose. We would use the curried F first. That would be the first thing we pipe in. But as a part of piping that in, we want to take care of two of the parameters we want to deal with the 1st 2 parameters. Now what Curry does is sets it up so that we can invoke it with one parameter at a time so I can invoke it with the A parameter first, and it will go ahead and process that value, and it will return a new function, which is ready to accept the next value. So I could then immediately once invoked that function that is returned with the B value. See how that works. So this one gets invoked, it returns a function and it gets invoked with the second value instill those values. Both of those values will be a part of the third function that will be returned. The third function that will be returned will be waiting on this value and that can be set up as a part of pipe because now it's only expecting one value. And then, of course I would do the same thing with Curry G. And I'm going to do the first value there, which is D and I can do the same thing with curried H. And this one has three values. So I want to do the 1st 2 so f and the function Inter's returned from that call I can immediately invoke and pass in G. So then what we have set up here is this first curried a function It has already set up with both A and B and when we call the new fund function will pass in what we want. First see, and then the result of that will be passed in for e here, and the result of that will be passed in for H. So the last parameter of these functions are the ones that feed in from the previous function. We're composing them together. So not only are you Neri functions important for function composition like we've talked about. But you also need to be prepared to accept the same type. So since these are all numbers here and these functions are expecting numbers that works great, the result of this will be passed to this which will be passed to this. Okay, now that is one approach. That's one approach to doing it, and that requires to create new curried functions which we've done up here. Now there's another approach we which we could take. So let me comment out, this one here also, I'm gonna come out these new functions we've created. Then I will set up the new function again and we're going to use pipe to compose those now . This time I can go ahead and curry the function as I'm composing it. So let's look at how we would do that. Well, it's simply a matter of calling curry and passing in f fun. So that's going to return a curried function. Then we can immediately invoke that career function with a and that will return a function which we can immediately invoke with B like that. So that will be the 1st 1 that's passed. And that's really the same thing. Is what we did hear the differences. We first created the curry function and we placed it into a variable. And then we use that variable and invoked it and invoked it here. As soon as the curried function is created, then we invoke it. Invoke it. Okay, so we end up with the same thing. The only difference is we're not assigning that initial curried function to a variable. So now we can do the same thing with G fund and we When that is returned, we invoke it with De and then finally we can curry H fund and that one that is returned, we will invoke with F and then invoke again with G like that. All right, so that's the second approach. Now I've been using letters, So to illustrate which parameters were taking care of as we're passing is in. Let's go ahead and replace some of these now with numbers so we can see how this works. So let me first put that semi colon there, and then I'm gonna comment out this one and we will do this first example with actual numbers. And then we'll do the second example. So I have those curried functions, and then I'm using the curried functions inside a pipe to compose a function together. Now let's just go ahead and pass in some actual numbers. So let's do one to four and then five and six. So you can see from one of these functions do there, simply adding numbers together. So let's go ahead and try that. So I'm going to say that and then let's jump out to occurring example and open the console and new fund and I'm gonna pass in a three. And why does it give us 21? So since I passed in a three, let's jump back to those functions since I passed in a three. Basically what it did here first was it had 12 and three and added those together that comes up with 66 give its past in is a second number two. The curry G function this one up here, those two get added together, okay? And so that is. 10. 10 gets passed in. And so those three get out together 56 and tan. And that comes out 21. Okay, so that work for us. All right? Now, let's do the same thing except will do it with a process of currying them as we're composing the function. So we're gonna go one to four, five and six. But save that and let's do this again. Let's go. New fund. And we're gonna pass into three, and we get 21 again. So the same results. Okay, so no different there. All right, now, let's do another example. I'm gonna do two examples in this because I think it's important to understand how all this is working. So me give us some space is here. We're going to create some new functions. His first function is simply going to double a number that's passed in. So I'm gonna call that double numb, and it receives a number, and then basically what it returns is known. Plus in, um okay, pretty simple. Now we're gonna have another function, and we're gonna call this total it. Basically, what we can do with this function is passed in four separate values and it will add them together. Just trying to keep these simple because we want to understand currying more than we want deal with complex functions. So four different parameters and it's simply reach ferns and one plus two plus in three plus in four. Simple is that and let's create one more function and this one we're gonna call do Array. So what is going to do is take in two numbers and it's going to return and rate with both those numbers in it, that's all. So here's our two parameters and what do we return while simple. We returned an array with someone, and I'm too just like that. All right, So if we wanted to compose ALS together so that we're passing in a number than doubling it and then making that a part of three other numbers that we're gonna total and then putting the final results with one more number in an array, how would we do that? Well, let's go ahead and compose that function we call this new function will spell it out, and we're gonna use pipe to do this. No, I prefer to shorthand way. So I prefer to just curry it while I am composing the function. Unless there is a reason that the curried function could be valuable for something else, and sometimes that's the case. For example, I could take the double numb function. I could curry it with a 10 and then basically it would be a function that will add 10 to any number I pass in. See how currying creates a new function for me, that's what another one of the advantages of occurring. So if I need something like that around, then I would curry the function beforehand. If not, I would curry it as a part of composing functions, because then I'm using currying to make it possible for me to compose ALS functions. So the first function that we want to put in is double number. Now, Double Numb doesn't need any occurring because it only expects one parameter anyway. And then the results of that is going to be passed in as the last number of total it. In order for that to happen, we have to curry total it. So let's do that. Perhaps I'm up here down here. We want to curry for a little it. Now, as you can see, we have three numbers we need to pass in we need to curry a new function using three arguments that are already going to be a part of the final return function. And then that final return function will receive the number that is returned from this double none function. So let's say the three numbers we want to use are simply three to and one. So basically what we're doing here is we're creating a function that is going toe. Add three to end one and any number that is returned by this. That's what we've done here by currying that. Okay, now for the last one, we're going to add the number that is returned by this 200 Ray with another number. Let's say that the number we want in that array is 50. For some reason, we want 50 as the other number. So we do array, we curry that. And then what number do we curry with? What argument do we create with 50 Because 50 will be the first number. The second number will come from the results of this. There we go. We have a new function created. Let's go ahead and look at it, see what we get. So let's let's figure out what we're going to get here. Let's go ahead and pass in a five and that were returned 10. And so that will add all of these together. So that should be 16 and 50 is what we should get there. Okay, so a new function. And there we have 50 and 16 and 16 as you can see, is in the second position. The reason I did one that creates. And Ray, I wanted you to see what numbers received last. So the 50 takes the place of this, and then the number received from the results here takes a second number. And so that's the same with any function were occurring. Recurring. The first arguments is what we're doing. All right, so that gave you some examples of how to use currying. Now in the exercise coming up, you'll get a chance to try that with some of the code we worked on already in this course. But before we move past this topic, I want to go through some definitions just to make sure we're understanding partial application and occurring. Okay? I think partial application was important to help understand the concept of occurring and it can be used. Partial application is still used. Occurring is probably used the most, though. So here we go first. The definition of partial application a partial application is a function which has been applied to some, but not yet all of its arguments. So, in other words, is a function which has some arguments fixed inside its closure scope. So with partial application is, the function expects four arguments we may due to arguments and lead to that still need to be entered, and they would have to be entered together. That's how part partial application is set up, were currying creates urinary functions. And so we always enter one argument, another definition. Partial application. It is when we call a function with your arguments than it expects, and that function returns a function that will take the remaining arguments. Okay, it has those arguments we provided as a part of that new function that's returned, and it will accept the remaining arguments. All right, now, let's do a couple of definitions of currying a curry function is a function that takes multiple arguments one at a time. Now you saw that here that I think this illustrates it very well. This is a curry function. The result of that is a curried function. Okay, and it takes arguments. One at a time. Here is here. It's invoked. It's invoked again and evoked again each time. Just one argument. You can also see it with the curried version where we curried the function here. And then here's the first argument, a second argument. So the first arguments passed in returns, a new function. The next argument is passed in when it's e vote that new functions invoked and every turns the value. If that is the last argument that's being expected. So it keeps track of how many arguments it still needs before it returns the value. And so if more arguments air needed, it returns a function waiting for the next argument. Then finally, it returns the results right here. This one returned a function waiting for the next argument. So that function is what gets composed. Same thing down here. Okay, so another definition of currying currying is where a function that expects multiple arguments is broken down into successive functions that each take a single argument and return another function to accept the next argument So basically what we were saying for what I was saying before returns, another function to accept the next argument. Once all the arguments are there, it returns results. It knows it keeps track of how many arguments the initial function needed, and there are curry functions that allow you to specify the number arguments. So instead of having the function figure out how many arguments is needed, you can tell it how many arguments. And that's what you would do if if you had a function that accepts any number of arguments and is usually not the same number of arguments. But in most cases you have functions that accept a certain number of arguments. The curry function. Figure out how many that is, and then it will keep returning a function until it gets the final argument that it will return the results. Okay, so what's the difference? Partial application can take his many or as few arguments at time is desired. Curry functions, on the other hand, always return a urinary function, a function it takes one argument, a lot of the concepts behind the tour. The same. This is basically the difference now. Finally, before we're done here, let's address the advantage of occurring again. Really quick. First currying can be used to specialized functions. I mentioned that at one point in this movie, where we could take a some function that accepts two arguments and those arguments could be any number. But we could then create a specialized function by currying that some function with a number 10 for example. Then it would become a function that adds 10 to some other number that's passed in, so it becomes a more specialized functions. That's one advantage of currying. The second advantage is, of course, it simplifies function composition, which is the main reason we were diving into this. All right, let's move on to the next topic. 29. Dissecting the Curry Function: in this topic, we're going to dissect the curry function now. I need to say first that this is an optional topic. You don't need to understand how the curry function works in order to use the curry function. However, I find that if I understand what's going on, if I understand the behind of everything that's going on, then I know I really get those concepts. And then I'm able to remember them. I'm able to use them better. And, plus, you learn some great things about JavaScript simply by understanding how this curry function works. So with that, let's start dissecting it. So here's some of the code we used from the last topic that we composed together, and they were functions that had multiple parameters. And so we curried them. Well, let's take a look at that curry function and start talking about how it works. Let me press a few returns just so you can see this little bit better. No notice. There are two parameters which exists in the Cree function, but really what we've been doing for all of our examples here, as we've been passing in one, which is a function we've been passing in a function that goes into this parameter. But there's also a variable for a ready so we could pass in how many parameters that function expects. So, for example, with total it we could pass in Tollett comma for, But the way this curry function is set up, we don't need to. It will figure it out for us. And how does it do that? Well, it sets charity, too. The function dot length. If nothing is passed in for aren t it sets it to the function dot lane. So whatever this is and the length of it, the length of a function is the number of arguments it can accept. So that's where that first part does. Now this curry function, the very first thing it does is it returns a function right here, so it returns a next curried function. That's what's returning now, something you need to notice about this function that's return is it is immediately invoked right here. Here's the parentheses surrounding the function, and then there's another set of parentheses, which cause it to be invoked immediately, so this is immediately invoked function, and the argument that has passed in is just an empty array. So prev ard's. This variable right here contains an empty A rate. All right, so this function that is immediately invoked, what does it do? It returns a function right here. So that's what most curried functions contained. Is this piece of code right here? All right, now let me illustrate. Before we discuss the rest of this, let me illustrate that. So remember, one way we could deal with currying is we could create a curried function, so I'm going to create a curried total it function. I'm gonna call it Kerr Curry Total. It will set it equal to what gets returned when we call the curry function, but and pass in this function here. And I could do the same thing with the do array. So curried do array, we're gonna call the curry function and pass into a rake, OK, so that we have to curried functions. As you know, we can then use that down here like this. Great. Now what I want to do is I'm gonna take a look at this function here. What gets returned? I want you to see what's inside this variable. So let's go ahead and jump out and go to the console and I'm gonna do curried total it got to stream So I want to convert that to a string so we can take a look at it. So notice what's in here. There's a function curried is name that function. Next arg is the variable that pulls in whatever arguments passed in. Okay, So if we jump back to our code and look at the creed function right here, function curried next. Argh! Basically, that part that gets returned is what's inside of this variable. And that would be inside of the other curried function to do array. Let's do a radar to string Gotta do to string so I can look at it and you can see that's the same thing that's inside of there. All right, so this is the part that gets placed in the variable. So why do this otter function? Why do this immediately invoked function? What's the reason for that? Well, remember, closure is an important aspect of understanding how this works. And so this function down here, it has closure over this function. Notice that we call it right here. So the code that's inside the variable is this, but were still able to call this function out here because it's available through closure and we also still have access to FN. And we have access to charity through closure, all of those air available through closure. So now that you see that, let's talk about the rest of this. So this is the function that's contained in a curried function. So when that gets invoked, we pass in an argument that gets placed into the next are variable. And then we set up an array of arguments. Here we declare this arts variable and we set up array of arguments and what does that contain? Black contains everything that was in prev ard's and it contains what was just passed in now Prev are eggs. Initially remember we just passed in an empty array and so that's what's currently in provides the first time through the first time we call this curried function and we pass in a single number one argument So nothing here. One number there, So basically what that ends up creating is on our eggs variable on our eggs array with one number. Now, if you are not familiar with the spread operator. The spread operate raider basically takes this and spreads it out, takes an array like object and spreads it out into its individual elements. And so if there had been something inside of product, it would spread it out into those numbers. All right, Right now there's nothing. So all we get in the arts variable is a single number, the one that was passed in the first time and called the curry function. Okay, so that's what our exists. So then we check to see the length of our eggs. And if it's greater than or equal to charity, remember, aren t we have access to through closure and already contains the length of the function, which is the number of arguments it can't accept. And so if the ARDS dot length is equal to or greater than charity, then we simply return that original function that was passed in with all of the arguments spread out. So basically we're calling the function with all of the arguments it needs because it's kept track of his arguments. Now, how did you keep track of those? Well, let's go down to this else statement here, so if the length is still less than aren t so we don't have all the arguments we need. Then what does it do? It calls next creed and returns the results. So next create is up here. So we pass in whatever we put inside of our eggs passed into next curried. And what is next Curry Dio? Well, place those arguments in the Prem barks and then it returns dysfunction. So once again this function gets returned as the next function that is going to be called. It's the same function But the part that has changed is that prev are eggs now has more arguments in it. So the next time through our arts variable consists of the new number those past in and whatever was there previously. And then we check to see if the length is greater than or equal to charity. If it is, we return the function, invoking it with all of its arguments. Otherwise we call next create again because we need to get another argument. If next period is called again, it returns Another function the same process. See how that works? See how close your works with this. See the value of closure. That's why I think it's so important to understand how the curry function is working, cause there are some pretty cool things that you're able to do with Javascript that this function is doing all right. So that is how that curry function works. Now, let's just walk through that a bit, So over here and our app dot Jess, we have a creed told it and a curry do array. So here's what I want to do. I want to just play with this curry. Total it a bit. Remember, it takes a toll of four. So what I'm gonna do is I'm going to declare variable fn one, and I'm going to call Curry, total it and set the results into the variable fn one. So remember, is gonna pass in the first argument. Then it's gonna return a function. So let's go ahead and do that. So if I look at FN one dot to string clips, what do we see? Notice It's the same thing. It's that same curried function that we saw before that we saw it with the initial curry, told it, Let me just type that one, and so you can see to string. They look exactly the same. Now the thing that's gonna be different is what is contained in prev arcs. OK, so in order to make this a little more understandable and see how it's processing things, I'm going to change my curry function just a bit. I'm going to put some consul Ogg statements, So I want to see crab arcs. What that contains and also concert about log next art. See what that contains. Okay, so is go ahead and save that, and we'll do this again. So we're getting a lot coming out here because I need to comment out this. I don't want it to do the piping it because I don't want any of those invoked. I want to invoke them myself so you can see what's going on. Okay, so that no won't get anything logged out. Now let's do the same thing again. So let fn one equal Curry Tollett and we're passing in the number five. So when I press return, notice that the two consul log statements remember the first consul log statement showed us what pray Barnes's and then the next one shows what next target is so proud. of Arg is a nem t ray. Next are is five. OK, now let's invoke FN one with a new number. So let's do let fn two equal FM one. And this time we're going to do six. Okay, so let's see what we get. Look at prov. Argh! That now equals the five that was passed in before and next RG equals the six. So if we look at FN two dot to stream, the function is the same. We have the two consul log statements. Now the function is the same. But the difference is, is what those variables contain. What we've created closure over. All right, so now we can do it again. We have FN two. So let's set let fn three equal fn two and will invoke that with seven. We just keep going up numbers here. So now prev RG equals the five of the six and the new r equals is seven. Now, if we do, let's fn four Now, If you with me on this, you realize the FM for is not gonna contain a function. It's going to contain the results because now this is the fourth argument that we're sending in, and so that will then check to see that the number of arguments equals aren t the variable charity and that's going to cause it to return to function with those arguments as a part of it and invoke that function. And so it will return the results So we really should get five plus six plus seven plus eight. So let's go ahead and press return and let's go ahead and look at FN for notice first that we have the prev Rx 567 Newark equals eight and FN four equals 26 five and six is 11 plus seven is 18 plus eight is 26. So that is how that curry function works now. Not all curry functions are the same, but they use this same basic principles. Okay, so the closure that you're able to create over values allows you to return a function that has access to previous values that have been entered. That is the key to making to making curry work. And I think by understanding that you have a better grasp of the JavaScript language, but you have a better grasp of what you're doing when you're occurring. A function as well. All right, let's move on 30. Exercise 7 Start: welcome to exercise seven for this exercise. I want you to apply occurring and composition, but to a task that you may not use in your own code. But I'm pushing you with this one because I want you to think about currying composition more than you have in the past. So let's take a look at what the assignment is. So for this exercise, you're going to be working with some code we've used in the past exercise for. We updated this code to use some of the methods that are part of a race like map and reduce . We're working with the users array, and we have functions to clone the object to get the user to update the score and update the tries and then finally to store the user, which now creates a new array. It doesn't modify the existing users array, so that's the code you're gonna be working with. Now, here's what I like. You too, dio using currying and composition, you're going to create a specialized function that always acts on the usual array. So it's going to be acting on this. You're going to curry a function using this as input and Basically what that function supposed to do is that it allows you to enter a user name and then it will return a clone of that user object from that array. So basically, you're going to be using the get user function to create this. So that's the first part of the exercise. Now, with the second part, you may not find you need a specialized code is what I'm gonna have you create here. But I'd like you to do it for the exercise, for the purpose of learning what is possible. Now, here's the specialized function you're going to create. Using this curried function up here composed a new specialized function that will be used. Update Henry. So on, Lee Henry, you would only invoke this function if you wanted to update Henry as the user, it should accept a new score and then return a new array at the end that contains the updated score and tries. Now, something to be aware of. And this could be a hint. To compose this function, you may need to create another function or some other code. There's different ways to approach this, so I just want you to be aware that you may need to do something else besides the currying and composition which you'll do to create this function. All right, go ahead and give that a try. Once you're done, go ahead and start the next movie and we'll review. 31. Exercise 7 Finish: All right, let's go ahead and go through this exercise. I hope you had success in trying to get that those two functions created and getting this to work. Now, the first thing I'm going to do is I'm gonna comment out this code here because we're not going to be using it. Gonna be replacing it with these other functions that I'm creating now. The 1st 1 we want to do is occurring composition to create specialized function acts on the user's array but allows you to enter user name, have a return, a clone of that user. So basically, we're going to be doing get, user. But we want to curry, get user and include that parameter, which is the users array. Then we'll want to clone the object once it returns a user object. And so that's going to require us to compose two functions together. So let's go ahead and set that up. Now, I'm gonna call this get users user. So just to indicate that were acting on the user's array so very specialized and we're returning a user now, I'm gonna use pipe to compose this. All right, so the first thing we want to do is to get the user, but we're going to curry that function so that we can tie that users array to that. So I'm going to use curry, get user. So there's our curried function. Now we're going to invoke that with the first parameter, which is the users array. And so the next time it is invoked, it will expect the name to be passed him. Hey, and then that will return. He used her object and what we want to do with that, we want to clone it. We'll call clone LBJ as the second function in that composition. So there we have our first function created. Now I'm gonna come down here and work on the second task, and basically we want to do here is all of these things which all these functions air doing . But we want to do them specifically for Henry. So the only time this functions ever called is if we want to update Henry and it will allow us to pass in a score. Okay? So in order to pass in a score, we need to be working with updates. Score. And since it will always work with Henry we're gonna curry update score and then invoke it with Henry one parameter and so the next Preferably waiting for is the score amount. Okay, so that's gonna be the first function That's a part of our composition. But let's go ahead and set up our composition to begin with. Now, this one, I'm going to call update Henry, since that's really what it does. And once again, I'm gonna use pipe to compose this and update score is the first thing I want to do. But we're going to curry update score because right now it expects to parameters. So we need to divide that out into urinary functions. Now, the first time we invoke that curried function notice I'm doing occurring inside the function composition, I could have done it outside and then include that function here. But I've chosen to do it that way. So the first time we invoke that curried function, we want to pass in the Henry object. So how are we going to do that? What are we going to include here? What? We're going to pass in for that first time. We invoke this while it could be a call to this function with a parameter of Henry that would get it for us. So we could put that right here inside of these parentheses that would get the value. And then it would invoke this curried function with the right object that would work. I'm gonna take this a bit further, though. I'm going to create a second function up here. I'm gonna call it get Henry. And all this function is going to do is return the Henry object. That's all it will do. So we can accomplish that by simply saying return, get users user can then pass in. Henry. So I did that up here because it makes it cleaner down here. I think all I have to put now for the parameter let's get Henry like that on the funk. We just call that function. It will return the right object. Okay, so there we've create updates, score, and we've invoked at once with the Henry object. The next time it's invoked, will pass in the score now, once updates scores finished, it is going to return an object again, and we want to clone that object. So I'm gonna add that next to our composition and then from that clone object, we want to pass that into update tries. That's the next thing to do. Once we updated score, we want to update tries. So there we go. And then finally, the last thing we're going to do is store user. Now, remember, store user is going to return a new array and another thing to be aware of with store user notice. It takes two parameters. So we need to curry this to get to work with our composition. So I call Curry first and store user. There. We have our curried function. Now we want to invoke it once with the users of Ray. That will be the first parameter pass in the second. Prouder is is the object that which will come from update tries. So users like that. There we go. There is our update, Henry. Function now we need to do is make sure these air working. So I want to check, get users user, make sure it works with any name. So I'll do that. And then we'll go ahead and check update Henry as well. And we'll just check both these at the console. Think that's probably gonna be good enough for us. So here at the console get users user, and I'm gonna get James is the 1st 1st 1 And there we go. We got a James object, which is what we want now. Well, let's try update Henry. So up, Henry. And let's do 100 as the score And what does that return should return a new array, which has a score updated by 100 and the tries updated by one. And we can check the existing users array we want and see that that is still as it is. So this is now the ray that that contains the latest state. So both of those work for us now. Those were pretty specialized functions, but I wanted to push you into using currying and composition in ways that perhaps you haven't thought of. Specialized functions are an important part of functional programming. And here you have been able to see the advantage of currying both in creating a specialized function and also making a possible to do function composition. All right, let's move on the next topic 32. Imperative versus Declarative Programming: The last piece of our definition that we need to deal with is that functional programming is declare a tive rather than imperative. To understand this statement, we need to understand the difference between the Clarity, EV and Imperative programming. So let's look at a couple of definitions. First. Imperative Imperative Programming is a programming style that tells the computer how to accomplish some task. Imperative programming is what you've been doing. Most likely, you are very specific about what should be done. You use a lot of control structures like if condition, ALS and loops and a lot of statements to make sure the program can process the data without missing anything. You tell it exactly how to process that data. That's imperative. Programming now declared of programming expresses the logic of a program without identifying the control flow. Control flow is abstracted away. So declared of code on, Lee needs to specify what to do, not necessarily how to do it. As your code becomes more declarative control structures like if conditions and loop start to disappear, those things air abstracted away. You spend more time indicating what should be done and last time indicating exactly how it should be done. So if you're not telling how it is done, how does it get done? Well, the important part is those things are abstracted away, so you don't have to deal with them every time you write the code. No, let let me use a metaphor toe illustrate this. It might help. Let's say we needed to tell a self driving car where to go. The imperative model would be something like this. Go straight for two miles, then turn left and then make an immediate right turn, drive another 500 feet, turn left and arrive at the destination. So that would be imperative. Now declarative would be something like this. Go to 15 90 Parkway drive, and that's all. The exact way to get there is abstracted away. It is somewhere in the controls of the car. We don't care how it works. It just does. We simply need to tell it what to do. Now let's look at a coding example. In a previous topic, we saw some code similar to this using reduce. Let me get this entered in, and then we will discuss it, and then here at the end. There's also another variable X. So we saw this code This uses reduce reduce has abstracted away a lot of the logic. We tell what to do. We're telling it what to do with this function. But we don't have to tell it to cycle through each element in the ray. We don't have to worry about that now. If we were to write something similar using imperative code, it would look something like this. We're going to declare a variable cause we need to keep track of the end results. And then we've got to set up a loop and we'll run that loop while I is less than the length of the array. And of course, we'll in commit high. And then we do something different the first time through the array for the first value of the ray. It uses this X variable instead of the accumulated value. So we need account for that inside of this loop, so we'll use and if conditional, to do that. So if I equals zero, that would be the first time through then Results is going to equal the first element in the array and we invoke that element and we pass in X and then the rest of time it goes through the array. We cycle through that array result will be equal to the next value in the array, and that is invoked and results is passed in as the parameter. And then finally, at the end, we returned results so you can see the difference between the declare a tive approach and the imperative approach in the imperative approach. We had to account for everything we had to make sure we were telling it how it was going to accomplish what we're after with the imperative approach. A lot of that is abstracted away with reduce. So as you move closer and closer to declared of coat, you will see fewer loops and condition ALS in your coat you're coding will be saying what to do instead of how to do it, because the how has been abstracted away, either in constructs like reduce or perhaps reusable functions you have created, and you reuse that you keep in your own library. Or it could be constructs from public libraries that are created to help make javascript more functional. Declared of code is much easier to reason about. You don't have to work through the code and try to figure out what is actually happening. Now, if we use this example that we just did the first time you encounter reduce, that may not be true. In fact, it may be a bit complex to figure out what reduce is doing. But once you get used to reduce once you know it reduced does. You don't have to worry about how it works. You concentrate on what needs to be done now. Another example that might help illustrate declared a programming HTML is declared tive. Think about it. You are simply saying what to do. For example, this will be an image, So I m g tag. And here's where the image is found and then it knows what to do with that. This will be an H two, and here is the text, and then it knows how to format that text to make it look like in age, too. So that's declarative now. One more huge benefit to mention with declared of coat is that it's more reusable. We've been saying that a lot with functional programming concepts, they are more reusable. It is not dependent on context. We can apply it to a number of situations, and that helps make it more reusable. So in concluding this video, which ends the discussion of our definition of functional programming, let's return to that definition one last time. Functional programming is the process of building software by composing pure functions. Now you know what this means. You know what functional composition is, and those functions are pure composing pure functions, avoiding shared state. So in the process of this, you're avoiding share state, avoiding mutable data and avoiding side effects. Functional programming is declared tive rather than imperative, and application state flows through pure functions. So the state of the application is passed from one function to the next function, and those functions are pure, so that is functional programming. Now that you understand the concept a little better, this definition can make a bit more sense. Now. You're not going to go from point A to point Z in one fell swoop, as I mentioned in some previous videos. Just as you learn functional programming concepts apply, those that make sense. If you like the approach, continue to learn it and apply more things, and eventually you'll be using as much of a functional programming style as you can within JavaScript. All right, let's move on to the next topic. 33. Exercise on Declarative Programming Start: now is you've gone through these exercises that have built upon each other. Your code should have become more to clarity. And I hope you're able to see how it was more to clarity of less imperative, more declarative. That's what I'm now going to show with the exercises. The last couple of exercises that I did. So let me jump to sublime to do that. Okay, this is the code at the end of exercise seven. That's when I currently have open. Now there's a lot of code here up here. We're seeing modifications we made to the original functions. Map is more declarative. No. Once again, it becomes more declared of when you use it a lot. When you understand Oi mapping and ray to another Ray. Therefore, it becomes more declared if you see that with reduce and so on. But where really becomes more declared of See what we've done down here at the bottom. When we get down to the end of this, this is where we really see things as declared it so I can read through this very easy creating function that will update Henry. Well, what are we doing that we update score and we're going update the score by getting Henry, we're getting going to clone the object than update the tries, and then we're going to store the user. See how that's declarative as opposed to imperative. There is more imperative code in these functions that are called up here, but as we could create and reuse these functions, our code gets more, declared it, and that's what I'm seeing here. That's also what I'm seeing here. I can see quickly what's going on with this particular function. So that's what I mean by more declare. Let's also look at exercise. Six. Gonna open that one. We've had done a lot with this exercise to make it more declarative. Once again, map, filter reduce. You get familiar with those they become declare a tive because instead of worrying about specifying how to loop through things or how to go through the array, your specifying what we do with the array so those become or the clarity and then as the code down here also is much more declared. If we have prepare, prepare and compute average and how do we do that? We prepare scores and then we compute average were simply telling it what to do. Prepare scores up here. We removed both high and low and then single scores by 10. So it's were saying what we do. So it's much more declarative. Remove both high and low scores. We remove over scores and remove zero scores. See how that works. So funds and composition allows us to be more declared A and occurring that we've learned to do allows us to do that function composition for functions that may not be set up perfectly for it. So our code has become more declared, if simply by doing the things we've talked about with functional programming. Functional programming by nature is just more declarative. So's we apply those concepts. Our own code will become more declare. Do we get away from Imperative Coal altogether? No, because you're going to create functions that will abstract that away. So when you're creating those functions, you are more imperative. But then you reuse that function, and where it is used, becomes more, declared him. All right, let's move on to the next topic 34. Exercise on Declarative Programming Finish: welcome to the exercise undeclared of programming. Now, this exercise is gonna be a bit different than the exercise we've done in the past. We're not riding any code now. That may seem a bit weird, but I want to do this is an exercise. I thought of just presenting it, but I think it's important for you to think about this instead of me just presenting it. So what I'd like you to do for Exercise eight is I'd like you to go back to the past couple of exercises and take a look at the final code. What? You've finished what you did, not necessarily what I did in my version. We'll talk about my version in the follow up text size eight. But take a look at your code and identify why it is now more declarative. Show that it is more declared. If give that some thought. I don't expect you to take a long time on this, but take a few minutes doing that. Then when you're done, go ahead and go to the end movie for this exercise and we'll talk about my version of the coat. All identify why I feel it is more clarity. All right, let's give that a try 35. Functional Programming Example: Comparing OOP to Functional: as we have worked through the definition of functional programming undone several exercises you have been learning out apply functional programming concepts in Java script. Now what I would like to do in this topic is show a small bit of code that uses a JavaScript 00 P paradigm and then the same solution using a functional programming paradigm . The reason I want to do that is I found when I was learning functional programming help me to be able to compare code that used a paradigm I was familiar with to code that now used that functional paradigm. So I'm hoping this same approach might help you apply these concepts even more now. Just to be aware, the Opie approach uses prototype will inheritance. So if that is a concept that is new to you, you may want to review using some links I provided in this topic. So first, let me explain what we'll be looking at. The cold we'll look at, is simply a way to track questions for a user. So a user answers different questions and then we will track. The results of those questions will track the question. The response. The result in what the question is worth. We will then have some code that displays the score for the user, will retrieve the score and the total possible score and will display that on an HTML page . So it'll be this page here, So that's basically what we want to do. Now let's take a look at the JavaScript Opie approach first. Now here is the code for the Opie approach. So let me go through and describe this. The first thing we have up here at the top is a constructor function, and this is for creating a new user record. Basically, what we do is we pass in an I D. And then we set up ah, user object. We attach the I D. And then we attach a an empty array for the questions that we will be tracking. We also have it set up so that if new is not used with the constructor function, it will still work. We won't have problems now. A constructor function is not the only way to do an O P approach, but that's the way I chose here to do that. Now, here, below the constructive function, we're setting up the prototype object user. Proto is what we've called that. You can see that we have the object. It goes down to here. So it has several methods set up inside it. One is toe added questions. Whenever we add a question, basically what we do is add to the questions array. So this one we set up here, we simply add additional questions to it. The i d. The response, the result and the wait, what the question is worth. And then that will automatically call an update score method, which is down here. The update. Score meth. It's simply updates this HTML page with the user and the score. You can see we do that. We grab this SPAN tag and we also grab this paragraph tag. When we do that with get element by i d. And then we simply update the inter html toe display. The user i d and the score the total score in the possible score. So we have to get her functions that retrieve the score and the possible score. And as you can see in these, they loop through the questions in the questions array and for the score, it checks to see the result before it adds the weight to the score, so the weight isn't added. If they got it wrong, it's only added if they got it right. So that's how we determine the score. And then for possible score. It just adds the weight no matter what, because that's the total possible that's available. And then we, of course, we returned those values down here we assign the prototype, and then we also reset the constructor, using a pattern that is commonly used when constructor functions are part of an O P. Approach. All right, let's go ahead and test this out. Now the way we're going to do this is simply interact with Consul. So I didn't take the time to set up questions and all of that. We're just going to use the consul as the interface for creating a new user record and adding questions to that instead of taking the time to set those questions up in all of that stuff inside of HTML. So I'm gonna open the consul here, and the first thing we're going to do is create a new use record, so this would occur when a user logs on to the system and we're using the keyword new and we're passing in an idea of one and I just realized something. Let me jump back here too sublime. I still have it set up for the functional approach, so I need to comment out those script tags and uncommon this script tag. So for the old P approach, I've added the code Teoh app dot Js for the functional pope approach. I have AP functional dot jess and then I also have a T GS that GS, which has some of the helper functions. So let's now go back and testes again. So say that refresh to pull that in and let's pull up that line more more time. So we create ourselves a new user record, and now we're going to add a question to it. We're going to do that is just user one and then add question as the method we're going to call and we're passing in an i d. For that question of Q one, this is the answer. This is whether it was true or not, whether it's correct or not. And then this is the weight. That's what's the question is worth So if we go ahead and press return, notice what happens to our HTML page? It updates current score. Four user one is one out of one. Now let's go ahead and add another question. We'll do the 2nd 1 here, and this one's incorrect. They didn't get this one. Correct. Put not answer there for the response. The wait for this one is two rather than one, so it's worth more than the first question. So let's see how that updates. So we got a total of one out of three now so we can see that working. We can see the old peak approach working. You can see how I approach that. Now let's see how we would accomplish the same thing with functional approach. Now the first thing you're going to notice with the functional approach right here is the number of functions we have. And this particular approach results in more functions. And that's that's the reason for the name. Now let's look at how we did this. So first up here we've set up a couple variables. This just identifies the elements on a similar page that we will be updating later now because we will be updating the HTML page. The Dom I've divided my functions into pure and impure, so impure those that are going to modify the dom. Remember when usually output is going to be impure because it's modifying something outside of the function. Okay, so we'll look at those in just a minute. Let's look at how we first set this stuff up. So we have a function to create a user. We pass in an I D, and it's going to return a user object. So we do. We attach the i D here, and then we attach an array, an empty array to keep track of the questions, and so will store this user in a variable similar to what we did before. Now the ad question function is obviously quite a bit different because we don't want to mutate. Data were still passing in the same information. Four. The question, but notice that we also pass in a user, and that's because we're using the user object to keep track of those. And so we do a clone of that array right here, the clone of the ray on the user object, and then we set up a new set of a new question based upon what's been passed in. Knows how we do that. We create a new object for that question and look what we do down here. We return a new user object that has the same user I d. We pull that from the user, and it has the new question added with all of the questions that were already there previously, we use the spread operator to spread that out. So we get that noone ray. That way we don't mutate the existing Ray. See how we've done that down here. Okay, so we're just being extra careful. They're not to mutating. And that's what would return as the user records. So this creates use record returns, years record. When we had a question, it returns. Use a record with more information on it. All right, we have account, score and account possible. We'd use reduce for both of those. Basically, what they're doing is we pass in the user object. It then goes through the questions array of the user object and totals all those values for Cal score. It totals them. If the result is true, it will add the weight. Otherwise it will add zero right here for the possible. It just adds the wait for all of those. Then we have a format results. Basically, what this function does is take and formats the score. So we pass in the user record than it calls Cal score and passes in that same user record format set out of count possible passes in the used record. Now here is a helper function and this one I could have placed in a. T. J s problem because it helper function basically what it does, it just gets a property from an object. So we pass in the property we want and the object, and it retrieves it for us. So it's a simple helper function. We use it down here to display the results on the HTML page. So down here we have another helper function which is impure because modifying the dump. But basically it's just setting a dom elements we pass in the element and the data. It just sets inter html of that to the data. The interface for updating questions and therefore updating the HTML page is update score. So this is what we will interface with and basically passing a user. And then we pass in the information about the question, and then it adds the question, sets it into a variable the user into new variable, then uses that user to display the results and display the user. And we've set up a display results in displayed user functions up here, and we use pipe. To do that. Wells had to use curry in a few places because the set dom element or they get prop requires more than one parameter. So these were the ones that actually display the results of the question. So how many out of how many? And this is the user information. So I guess the user i d. We used to get prop function to do that, to get the user I d. And then it displays it and the user filled. So we're trying to be more declared of notice, where adding a question, were displaying results were displaying user trying to be more declarative, and we've used a lot of the things we've talked about. We've composed some functions using pipe. We've had to use curry. We've, ah dealt with pure functions up here. We eliminated side effects, and we made sure we were not mutating data. Some of these things we've been able to do is with the helper functions that are found in a . T. J s. We have a curry Ah, clone pipe and a composed functions we've been working with in the past. All right, let's go ahead and change what code were using. Look at how this works. Using the functional approach. Say that and we will refresh. So with the functional probe, we're going, Teoh, create a user and assign it to a variable that we don't want to change. We'll give it the same ideas we did before. Now, as I mentioned the function that was set up to interface with all the elements to pass in a new question what not was update score. So I'm going to create a second variable because remember this update score returns a new user record. Not only will it update the results here, but it will return in news record, which I can then use for another question. So I'm passing in the initial user record, and then that's the question i d. The answer that was given whether it was correct or not, And then the wake. So when we press return, I entered the wrong piece of data. So let me correct that. Press the apparel, bring it back, and then I'll remove that E because it's us our want here. I'm going to remove the E. Here is well, so that were consistent. Now let's press return. And there we get our update one out of one. Now, let's add the second question now. So I'm gonna create a new usr variable and this time in update score, we're gonna pass in us are too, because that is keeping track of what we now have. We've added one question. Now we're gonna add a second question. Here's theano, sir, which is not correctly put false here. And this one is worth two instead of one. Go ahead and press return. There it looks like we still have a problem. So what I'm getting from this is that it's indicating that the questions array is not They're for something that's undefined. So what that tells me is I'm probably not returning the user record back into this variable . So let's look at that really quick. So let me jump down to update score. Sure enough, I don't have I returned there, so I want to return that user record. No, only update the results, but return the user record. All right, so let's refresh this will do this all over again. But since I already have entered the data, I can just choose them. There's one out of one. Now let's do the second question. There's one out of three so that workforce is well with the exception, that one mistake where I forgot to return the user, but and that's a good habit to get into with functional approach. Usually you're bringing in something, and you're always returning something. In many cases, it's not always the case, but in many cases that is true. All right, so hopefully being able to see a JavaScript Opie approach converted to a functional approach can help you see out. Apply these better in your own coat. Now that's may not be something you're going to be all accomplished right away. For me, it wasn't I. I still use different approaches in Java script, but I understand those function approaches so that I can use them when I need them and to be truthful. Sometimes I mix because it seems to be the most practical way to solve a problem. All right, let's move on to the next topic. 36. Example Follow Up: I want to take just a couple of minutes and talk about the approach that I took to making this code functional. This example that we've just gone through. How did I end up with what I have here? Well, someone else may have ended up with something different, but I think the approach is what's important to understand. So the idea is you take bigger task and you break them up into several smaller functions to take care of smaller tests. And then we re combine those functions to solve the initial problem. So that's a general approach when we're doing trying to solve something using a functional paradigm. Now, the consequence of riding cold this way is a lot of smaller functions that have intention revealing names. That's a term that is thrown around in functional programming. Intention. Revealing names know what's an intention revealing name? Well, for example, updates score that says, What is going to do display user that says what it's going to do? That's an intention revealing name. And so, by breaking these larger task in the smaller task, it's easier to give that intention revealing name because the function is now doing something specific. It's not doing multiple things is doing a single small task. Now the process of doing this cause you to end up with two kinds of functions. For example, you have functions doing one task format results. Get the property from an object, a cow, the possible score calculated possible score. Calculate the score and these functions are pure, so we're using those functional concepts as we create the small functions. But then the second type of function we get is a function that combines the smaller ones together. That's what we have down here and these air, hopefully easier to read, easier to reason about and understand what they're doing because they should be more the clarity of now. Also, you're going to have some functions that are imperative this necessary, this one up here, this ad question function is more is much more imperative than some of the other ones, and this is imperative as well to create user function. So that's another thing you'll see as you go through this. So basically, in summary, functional program is really not about all the fancy terms that we've been using. Those concepts are important, and those concepts are what we need to apply when we're doing a functional approach. But more importantly, it's about having many small, well defined compose herbal functions without mutations that bring in an argument or arguments and then return something. All right, let's move on to the next topic. 37. Using the Lodash JavaScript Library: as you dive deeper into functional programming using JavaScript, you may want to employ one of the functional libraries that is available for Java. Script in this first topic on libraries were going to take a look at Lodi. Now the goal of this topic is to get you started with low dash. I'm not going to go through every utility it provides that you can use the documentation for that. But let's first look at the website and see how to download and use the load. Ash Library. Here's a website for low dash At the very top of the page, you can see where you can access the coat. You can get a core. Build some of the core functionality. You can get a full build, download both of those and then you can attach them or use them. Or you could do a cdn copy. So basically, Cdn will create a link to a load ash library that's on a repository now installation. It also describes that at the top here in a browser. So if you're using a browser, you simply want to link the file using a script tag. If you're using note, then you want to install as indicated here, and then you would require the load ash module toe work inside a note. Now for this topic, I'm going to be using a browser, and I'm going to use the cdn copies. So let's just take a look at that really quick. How you do that Not something that's kind of nice about Cdn takes you to just deliver. And you can use the entire library, which is what you would select hair to get the entire library. Or you can use specific parts of it if you just want pieces of the library and basically all of it. If I click, show all it basically list everything. There's Valin Library, and I can pick and choose what I would like and then generate a cdn linked to that. Now, before we go ahead and attach the library to the browser page so I can begin show you a little bit about Lodish. I need to talk about the FP module and Lodish because that's really what we're going. Teoh use Load Ash comes with a functional programming module that promotes a more functional, program friendly style. Now it does this by the listen close. This is what it says on its website, exporting an instance of low dash with its methods wrapped to produce immutable auto carried literati Free first data, last methods. Now that's a mouthful. And what exactly does that mean? Well, before we go to the FBI, let me just explain that really quick. So immutable means the functions do not mutate any of their parameters. So they modify the function so that no parameters are mutated. All auto pureed means if you pass in, you know what curry means now. So if you pass, unless arguments in the functioning expects it will return another function and that function will expect the rest of the argument. So basically, Hume break functions up their auto curried. We'll show that just a minute. Intra t first. Now a lot of function. You pass in a function to tell it what to do with the data. For example, if you remember with reduce and filter and map, we had to pass in a function to them. Well, Lodish has the same types of utilities map, reduce, filter and others, and it expects a function in order to process the data Well, it or a T first means that the function is passed in first and the data last. So that's a switch with the regular way load. Ash works toe help with functional programming. And then, finally, data last simply means that the data that would go into a function like that comes at the end instead of at the start. So with Low Dash, I would recommend using the F P module. So let's jump there really quick. I click on that button. It takes us to get hub and provides a little bit of an FP guide. Now, the one thing that is really important here is the script tag, which is used for loading a Cdn version of the library. It also shows you how you would do it in note. There is also some additional information about the F P module, but the documentation is not great. So in exploring this, I recommend you use the documentation that you have available from the first page, and it goes through every single utility that's available, every single method that is in this library. Now, the only thing you need to remember as you're looking at the documents here in the main. The only thing you need to remember for the FP module. So the functional programming module is this. The first argument that it shows when you're looking at different things is usually the last in the low dash F P module and any optional arguments that it may indicate in these methods are omitted. So optional arguments are not there because we keep an charity that is certain with the F P module, so it works better for functional programming tasks. All right, let's go ahead and take a look at using low dash, so I'm going to jump to Sublime. Now here is the HTML file I'm going to be using, So I want to add a script tag that will bring in the low dash library Now. First, I'm going to do the load ash library that is not optimized for functional programming because I want to show you just a difference between the functions when their auto curried and when they're not. So here is the regular Lo Dash library, the cdn for it just going to say that, and then we're gonna jump back to app dot Jazz, since where we'll enter a coat Now there is an ad method that's a part of the load ash library. Basically, what it does allows you to pass into numbers and just as them together. That's what it does so very simple. So let's take a look at that. If we did some equals now, the way we access Low Dash is we use another score and underscore is what has been designated as pointing to the load ash library. So we do an underscore and then a dot toe access the different methods that are a part of low dash, and we're going to access an added method and I'm gonna pass into numbers. And that's basically add those two numbers and it's going to place the results in some social. We should get seven. So let's look at that really quick. I'm gonna jump back out here to that html page, and then I'm gonna open the consul and just take a look at some and it is equal to seven. Now, let me show you what's possible with the auto curried methods. So we're gonna do that same thing, but I'm gonna break up the parameters. OK, so before we do that, let's go ahead and put the script Dag, for the FP module. I'm going to replace the one here with one for FP annual noted. That's correct. One for the FP. Because you'll see the Lord Ashe, not men dot jazz plus load Ashdod FP Duckman. So it has a little both of those. Then I'm going to say that and come back. And now I'm gonna leave this line here because you'll see, we can still use the math of the way we did before. That's still possible. But now I'm also going to use the auto curried ability of that method. So I'm gonna do some, too, and set that equal to underscored ad. And now I'm going to just pass in five. You know what this creates for us is a some to function, so this will become a function because it's curried. This is going to return a function because it doesn't have all the parameters. So return a function with closure around the first parameter of five, and then suddenly this becomes a function that will add five to anything. So really, I should have named this. Let me just change that. Add five okay and that's what our function will be. And so let me say that really quick will jump out the consulate seal that works. Okay, so if I do some, we can see I still get seven. No, let's do add five. Now notice that is a function. If we were to press return now, we would see the function that's returned. So now we can do add five, Then add the second parameter to now that will return. And seven. So that is auto curried is what we call that. All right now, to really introduce you to load ash and FP module that's available with it, we're going to do several of the utility. Several of the methods air part of that library, and I want to focus on methods that represent things we've already learned in this course, so you can see how to use them in low dash. All right, so here's what we're going to dio. We're going to create a function that's going to act on an array of numbers, and what this function will do is first out of one to each number. In that array, there will multiply each number in the array by three and there will remove any numbers in the array there, over 100. Then at that point, we'll log the results to the console, and then we will some, all the numbers into a single total. And then we'll log those reasons that results in the console. So we're gonna have one function, do all of that. We're gonna compose it. We're gonna compose that function from simpler functions, will create a function. It does each part of what I described. Add one to a number, multiply that number by three, removing number over 100 log the results to the console and then some the numbers. So we will create those functions, and then we'll compose them and will do all of this using methods that are part of the load . Ash library. Okay, so first off, we're going to create a function is going to add one to a number. So since this is an array will be acting on, we want to use the map method is available in the low dash library. And so I do an underscore dot map. Now with the F P module, it accepts the function first. So this is the function is going to act on each element of the rate. So this works just like map that we learned earlier. That's a part of Java script. However, The difference is if you remember the version for Java script, we had an array and then we would do dot map. It was a method of a raise, and that's how we'd act. Access the map method here in low dash. It's a method of the Lodish library, so we select it and then we pass in. The function is going to act on each element of their rape, so we'll give it a parameter. I'm going to do barrel functions here because one line is simple. I'm passing it into a method, so that's usually when I use a row functions. So here's our parameter for the function that's going to take each element from the ray, which will be a numb. And then here's our fat arrow, and what do we want to do with that? We want to do num plus one, and that's what will be returned. OK, so that's our first method that simply goes through an array and adds one to each number in that array I was creating second method that multiplies numbers by three. So I'm gonna call this molt by three open, I just knows appear left off my equal sign. You guys probably noticed that now set that equal to underscore dot map will use map again because we can go through all the elements of the rate, multiplied them by three and return a new rape similar to what we did above where we're adding one. And the printer for that is going to be numb again. And then we'll have our fat arrow. And what's that going to do with it? Nam multiplied by three. Simple as that. Okay, now let's remove numb numbers that are over 100. So this is the next function. Remove numbs over 100. So I'm calling. This one will set this equal to now Gas. What method? A blow dash we're gonna use here. Since we're removing numbers, we want to do a filter and load. Ash has a filter. Utility uses the same term. So I'm gonna do an underscore dot filter. Then we need to pass in the function that's going Teoh act on that and parameter numb for each element in the ray will do our fat arrow. Now, what are we going to return here? We only want to return numbers that are less than or equal to 100. So that's what we should put here because of its less than or equal to 100. It will return true. And that will cause that number to be placed in the new array. No notices. We're creating these functions here. There is no array that's been passed to them. Well, that is the parameter is going to be passed to each one of these functions is an array. Okay, so the array hasn't been identified yet, like we do in Java script. Where we where. It's a method of the rays, so it already knows what to act on. That's not the case here. That array needs to be passed in. So we're still waiting on that. All right, now, the next function I'm gonna create is simply going toe logging results to the console and then return the data again. So I want to be able to use this inside of a composed function. And so that's why I'm creating a second function to do this so I'm going to call it log and return. So logged the results and it will return the data so that I can then do more with it. Okay? And we'll set that equal. Teoh, I'm gonna create regular function this time function expression. Basically, it has it can receive data. And what does it do with that data? While the first thing it does is it doesn't Consul log data. And then the second thing is it returns the data. So we did that so that we can include this inside of a composed function and what we could put consul dot log inside a composed function. But then nothing's returning, so we can't continue to work on the data. And so that's why I did that here and then. Finally, the last thing we want to do is want to some all of the numbers in the array. So let's set that one up. We'll call that some all numbers. Now guess what method of low dash we're going to use here. Underscored. Got reduce. So it has a method exactly the same name as one we've learned in javascript. And what are we passing into this? Well with reduced we need to pass in more than one parameter to the function that supplied one is the accumulator, remember? So we'll call that some as keeping track of everything that's added together. And then, um is the element from the array that will be the number from the array. All right, then we'll do our fat arrow and we simply returned some plus numb. Now, since this is auto curried, all these functions are auto curry. Reduce is expecting another parameter, and that is the initial value for the accumulator. And so what I'm going to do here is simply put zero and princes falling. It's a little invoke. The function that reads returned here because it's auto curried. It will invoke it with a zero, and that will be the initial value for some. And then the next thing it will be expecting is the rave that will act on. All right, we've got all our functions set up now. We can now compose them together so we can using the composer or pipe. They're both available in Lodish. However, they're not called that they're called flow and flow. Right? Okay. So composed A similar to flow right flow is similar to pipe. However, something load ashes done to make things easier to use is they've created an equivalent for those functions for flow and flow. Right? They created an equivalent pipe is equivalent for flow and composes equivalent for flow. Right, So we can still use the terms pipe and composed. And I like that. I like being able to use the same term. So I'm going to set up this function that we're gonna call process numbers. I'm gonna set that equal to underscore dot pipes or accessing pipe, which is really the flow method inside of low dash. And now we set that up similar to what we've already learned. I'm going to add one to each number in the array, and then I'm going to multiply by three sale declared of this is and then I'm going to remove numbers over 100 and then I'm going toe, log the results and return the data so that I can then act on it again and some some all the numbers. And then finally, will consul dot log the results at the end. So that is the process numbers function that we just created So let's go ahead and say that Refresh here and let's go ahead and call process numbers and I want to pass in an array and I'm gonna put Let's put about five, 8 20 we need one number that's gonna be over 100. So we know that it doesn't include that. That one will be over 100 after adding one and then multiplying by three. So let's do that array and see what we get. So here's the first log and return function we have in 18 to 27 a 63. Okay, so it added one that multiplied by three and the forties not there because it was removed. And then the final Consul log statement adds those together, and we get 108 for that. All right, so that work for us now, the load ash library has ah lot of methods that you wait may want to use. So I would recommend is you get familiar with it that you look at some of those methods in the documentation and see how you may use them. You can simply click on them and see what they dio and then you can determine whether it's something you'll want to use. And as you can see, there are a number of here. All right, so this should get you started using low dash. Let's move on to the next topic. 38. Exercise 8 Start: welcome to exercise eight. In this exercise, you're going to be using some of the code we've already used in the past and some past exercises. But I'm gonna have you used Low dash. This will give you a chance to use low dash to accomplish some of the things we've already worked on and help you get more familiar with Low dash. So let's take a look at what I'd like you to do. Now, this code comes from the start of exercise six. So we have some statements here. First, we've declared an array with scores and then we've been working on that array. You can see that we're mapping the array to a new array by boosting the single scores. Anything below 10 were multiplying by 10 were then using that array down here and filtering out all scores that are over 100. And then we're using that array and filtering out all scores that are zero. So that's what these statements are doing Now your assignment is to convert each statement to a function that can accept an act on any array and to create those functions, use low dash. You want to use low dash for all of this. That's what I'd like you to dio. Then you'll compose a function that were will remove both zero or lower scores and scores over 100. And then you'll compose a function that will do all of these modifications. He's to appear to the array, and then you'll create a function that will accept an array and return the average. Know something about this assignment, hair and exercise. Six. We did this with reduce. If you'd like to, you can do it with reduce. But there's also some other methods in low dash, which could make this easier. So just a hint, something to look at their then finally compose a function that will do all the modifications. So these up here, in fact, what this function does and then return an average. So composing this one and this one. All right, go ahead and give that a try and see how you do on that assignment 39. Exercise 8 Finish: all right. I hope you were successful on that exercise. Let's go ahead and take a look at how we're going to do this now. First thing I want to do is I need to make sure that I have the load. Ash library is a part of my HTML page. So I'm gonna come into here to begin with, and I'm gonna add a script tag which loads load hashtag men that jazz and load ashton f p dot Mindich Js Oh, go ahead and save that file. All right, Now we can begin working on the so first thing I want to do is convert these statements here toe functions. So the 1st 1 is taking single digit scores and multiplying them by 10. So the six and the eight would qualify for that. So let's go ahead and create a function that will do that instead of just the statement. So I'm gonna call this function mult single scores by 10. I'm being intentionally descriptive in my function names here. I'm gonna set that equal to underscore dot map. I'm going to use the map method of low dash to take care of this. And what am I going to pass into that? Well, I'm going to pass in a function that will process those and they'll do a narrow function. So here's the variable that will store the number that comes from the raise it it rates through that array. Fat Darrell. Then what are we going to do? Well, if that number is less than 10 so we check that first, I'm going to use the Turn ERI operator to set this up. If it's less than 10 then we multiply it by 10 and that's what we return. However, if it's greater than 10 we simply return the value. So we've got that 1st 1 done in a comment out that statement, So I know that it's done come down to the next statement removed over scores, and so this will require filter just like we have done here. So let's create a function that will do that and let's call this one removed scores over 100 said that equal to underscore dot map, and we'll do a narrow function again. Fat arrow here, what is going to do? Well, if the value is less than or equal to 100 then that is true, and it will return that value. Otherwise the value will not get returned. So it will not be made available in the new array that is created from this. All right, so we've got that one complete. Go ahead and comment out that statement. Now we need to do one more, and this is removed zero scores, and I'm gonna call this the same thing. We're gonna set that equal to underscore again, and we'll use the filter method. And I just noticed. Look what I did appear a put map. And then instead of filter, we need to fill through that, that that's how that will work. So Onley. If it results to true, will the value be returned? In this case, a value less than or equal to 100 will be true, and that value will be returned. So that's how we remove those over 100. Okay, so now back down here using filter once again. And this time we're going to use about greater than zero. So if the number is greater than zero, it results in true and therefore the value is returned. Otherwise it will not be returned. So that way we eliminate the zero values. Okay, so I finished that one. I'm gonna comment out that line right there. So we've completed this first thing, a converting statement to a function now composing function that will remove both zero or lower scores. So let's go ahead and set that one up and we'll call this. Remove Bulls zero and over 100. We're gonna call that we'll set that equal to underscored out pipes and our composing a function using pipe and will compose up by removed scores over 100 and remove zero scores. And there we have a new function that does both of those. Now look, compose a function. It will do all the modifications to an array. So we want to not only remove those scores, but we also want to multiply the single scores by 10. So that will require pipe again. And I'm gonna call this process scores underscored up pipe open, prin. And so the first thing I want to do is multiply single scores by 10 and then we want to remove both zero and over 100. So that takes care of all of those modifications that one function that we have a new function that will process the scores now create a function that will accept an array and return the average. So how are we going to do that? Well, I mentioned that there might be an easy way to do that using utilities and low dash. So I'm going to jump to the low dash website, and I want to show you one of the utility methods is available mean So, basically computes the mean of values in a race we can pass in array, and it will return the mean or the average. So that's great. That's the kind of thing we want. However, let's take a look at something really quick If I go to the main page and then jump to the FP guide and I look at the functional programming if I looked through, all of the methods that are listed here mean is not included, so they didn't include that as part of the functional programming module. So does that mean I can't use it? Well, no, I can still use it, but I will need to curry it in order to make it work for this and of course, load. Ash has a curry method. Actually, two different Karim methods, regular curry method and career, right? So I'm going to use Curry to set this up. So let me jump back and I'm going to call this compute average and years I will create this . We'll do underscore dot curry. We're going to curry the mean method, and we have to access the mean method by doing underscore dot mean all right, So what that's going to do is create a curried method of mean for compute average. Now, we could have done this at the time we were composing functions, but I decided to do it as a separate function for one reason because it was part of the assignment. But for another reason. I think it looks cleaner. Now we will compose a function that will do all the modification the Honore and return the average. Let's go ahead and set that up. We're gonna call this process and compute average. Don't set that equal to underscore dot pipe open print. No, what's the first thing we're going to do while we're going to process the scores? We already have a function set up to do that so we'll use it. And then the second thing will do is compute average. All right, let me save that. And let's go ahead and see if everything is working for us. All right, let's jump out here and try that. Let me open the console. And let's first test remove both zero and over 100 scores. Let's see what that returns as you remove all the zeros and anything over 100. So there we have no zero showing up. We have nothing over 100. So it looks like that's working. Let's look a process. The scores. Now, what this will do is also multiply the single digits by tan. Okay, And then it will remove the zero and 100 scores. Process scores are gonna pass in the scores array. So it did take care of that. Multiplied six by 10 and eight by 10. So we're good there. Now, let's just do compute average. So I'm gonna do compute average by itself. First on the scores, Ray, this should be a much lower average 47 not 61 whatever. And the reason it should be lower is because we have zero still in it, and we have these lower scores still in it. So now if we process and compute outreach, we get a 63.5, all right, so it looks like all those are working for us, and that gave us a chance to use some of the methods that's available in low dash. All right, let's move on to the next topic. 40. Using the Ramda JavaScript Library: in this topic, we're going to take a look at Ramda Jess, another library for improving functional programming. Java script. Now the use of Ramda will look similar to our examples that we did for Low Dash. So what is the dear friends and which should you choose to use? Well, the choice is up to you. You may find you like one better than the other, but let's look at what the creators of RAM to say about their library first. So here is the Ramda Web page. Basically, in this first paragraph, one thing they talk about is that Randa was developed specifically for a functional approach in Java script, where other libraries we're utility libraries that were converted or made to support a functional approach. Ramda was developed from the very beginning to do so. So I guess one of the differences would be the load ashes. A general purpose library turned into a functional library, whereas Ramda was built from the start for functional programming. Now you'll notice reading the What's Different section here that has a lot of the features that we talked about with low dash with the functional programming module of load ash it has immutable and side effect. Free functions. Their functions air, auto, curried and the parameters for functions are arranged to make it convenient for occurring. So the data to be operated on is supplied last where the function, if you need to pass on the function, would be supplied first. So some similarities to Low Dash and you will see that the function names or the method names are very similar as well. Now, also on this home page, you'll see there some articles linked to to help you get to know rammed it faster. Let's take a look at the documentation. I think the documentation is fairly robust. I wouldn't say it's any better than Low Dash, but the difference is here in Ramda. We're talking about the functional version of the methods because that's all they've created, where in low dash the documentation is talking about the pre functional programming. So there may be something you have to do to adapt when you're looking at the load ash documentation. In both cases, they describe the functions, and they also have categories. So, for example, if I wanted to see everything that was tied to the math category, I just click on that category and issues all of the methods for that. Now back to the home page. It gives you instructions about installation. Here's how you'd use it in node and then if you wanted to use a directly in a browser once you download Ramda dot Js, then you would use a path to it in a script tag. Or you can use the Cdn like we see here, and that's what we'll be doing. So I'm gonna copy that now so we can use a bit later. Now, one thing I like with the Web page for Renda is the try Ramda tab. Basically, this just allows us to try some of the coat. So we talked about how Ramda functions are also auto curried. Let's look at that for Ramdas. Well, we'll use the same ad function that we did for low Dash. So let's say I wanted to add two numbers. Notice how I refer to a method inside the Ramda Library is using capital are dot and then the method where low dash we used the underscore here use capital are I'm going to add five and two. Now I press return we get the output over here, which is seven. All right, now let's see how it's auto curried. I'm going to remove that. Let's just clear the output. And here's what I'm going to create. Let's do add five, which is going to be a curried function. We're gonna set that equal to our dot ad, and then all we're going to supply is number five. Now, when we do add five and we pass in a to we get seven over here in the output so we can see that it's auto curried, just like Low Dash. And Ramda was built that way from the very beginning. All right, so a nice little feature. Now let's look at some code using Ramda. We're going to create pretty much the same thing we did with low Dash, so we will first create functions to act on. An array of numbers will first add one to each number. Then we'll multiply that number by three, then remove numbers there over 100. Then log the results to the console, then some of the numbers, and then finally log that result to the council. Know what compose all of those functions together into a single function. So let me jump to sublime. Now, first thing we're gonna do is inside the HTML page here. We're going to add a script tag, but and I'm gonna put the source gonna paste in when I copied earlier. Well, that was the entire script Taggart copied, so I did not need Teoh begin creating the script tag before I pay Pasted Things in. So here's our script tag a Cdn link to rammed it out men dot Js Let's just say that and we'll go to our app Jazz and First will create a function is going toe. Add one to every number that's in an array and will use the map method. To do that, we'll call that add one are uppercase ours how we access the methods of Ramda map. And from here it's just like low dash we're gonna pass in a function will be an arrow function. There's the fat arrow and numb plus one So this variable is every number in that array. We simply add one to each of those and return it and that will create a second array with the number one added to each of the numbers, which were in the array, provided no. Once again, just like with low dash map is not acting on an array. It's not a method of a raise, so we will pass in an array. So in order to use this function we just created, we would pass in an array of numbers to it. Okay, All right, let's go ahead and create the multiply by three function, so we'll call it multi by three. Set that equal to our dot map. We're going to use map again, so this will look very similar to the function above it. Here's our fat arrow and what are we going to return? Numb times three like that. Now let's create a functional removed numbers over 100. So remove Mom's clips over 100 and we'll set that equal to you. Filter this time notice. So far, all the methods have been exactly the same, whether we are in low dash Ramda or plain JavaScript. And here's what we're going to filter. We're going to pass in each number in the array, and then we will return that number if it is less than or equal to 100. So last center equal to 100 will evaluate to true if it is, and then it will return that number. All right now we're going to create the long the log and return function. So we want this toe log to the console and then return the value because we then want to act on the value once it's returned. So we'll set it up exactly like we did in the low dash topic. We have our gate of past in, and then we logged that data to the console. And then the next thing is we simply returned that data so that then the next function can act on that data. If we compose a function with all these together, we want to make sure we return that data, and that's why we're doing that. Finally, let's create a function that will some all the numbers. Now, of course, this time we're going to use reduce once again. It's exact same name for that function are not reduced. We have two parameters there. One is for the accumulator value and the other is for the value from the array. Let's go ahead and create our fat arrow. What are we returning accumulator, plus the new number that's passed in and that will be added to the next accumulator. No, Once again, since this is curried, we're going to go ahead and pass in the first parameter. We're going to invoke it with the first parameter, which is the initial value for the accumulator. So there we go. Now we can compose all these together. So we're going to compose a function that does all of this. All of these things together we've created and so we'll call that process. Numbers set the equal to our dot pipe. And first we're going to add one to each number in the array that's passed in, and we're gonna multiply each number by three. We're going to remove numbers at over 100. We're going toe, logged the value and then return the value so we can do one more thing with it, which is some all numbers and then finally will log that last bit of information to the consulate. We can just use Consul Log for that. We don't need to create a new function. So there we have process numbers. We go ahead and say that and let's take a look at this. An HTML page meant open the console and it looks like we're not loading the resource files . Let me look at what I did here. Oh, so I copied in their script tag. I need to add h T T P s colon on the front of this u R l. It's a little work for us. All right, Let me say that again. Let's jump out now, see if it finds the Ramda dot Js file, and it did that time. So now we can run process numbers, and I'm gonna use the same array. 58 2040 and suit we get in return. So log out the array. Just like load Ash did it Got rid of the one that was over 100. And then it added those all together, and we got 100 8 so we were able to accomplish the same thing with Ramda. So, like I said, I'm not going to recommend which one of these you may want to use. I think they're both great. So you just need to decide which one fits your personality. It may be that you want to use low dash because it has some other functions, some other utility functions that you may want toe take advantage of. Or perhaps you want to use Ramda because it was built with functional JavaScript as the focus. All right, let's move on to the next topic. 41. Exercise 9 Start: all right, It's time for exercise. Nine. We're going to apply the Ramda library to some cold we've already been working on. So let me show you that code. Now here's a bit of cold. We've worked on this through several exercises, basically just a quick reminder. We have an array of users, and what we're doing is updating data about the user's score and tries that kind of thing. And so we have some functions to do that. And then in the later exercise, we actually made some very constrained functions that were specifically updating the Henry User. Net was all and so we created those using curry and pipe. So the assignment is to re factor this code using the Ramda Library. Now, there are multiple places that you could make changes to this. Some of the obvious ones are in these functions down here, but technically you could make changes in all of them, and I plan to do that. So what I'd like you to do is do as much as you are able, and then when you're ready to continue, can see what I have done. No. One thing I'd like to like to mention is we talked about in a previous exercise, several exercises back that these two functions weren't technically pure because they're changing the input. They're changing that user input. We're updating the tries on it. Now we clone the object so it doesn't cause us problems in the end. But the functions themselves aren't pure. And I mentioned that exercise that we're going to resolve that once we got to the library's , we're going to resolve that with Ramda. So if you want to give that a try as well to see if you can reader these functions using rammed it utilities, and by redoing them, it should make them pure. But at least redo these functions. Re factor these and make sure they're using Ramda. And then once you ready to continue, come back and we'll go through this together. 42. Exercise 9 Finish: All right, let's re factor this code using Ramda. Now, the first thing we need to do is make sure that we are linking to the library. So let's take care of that. First, I'm gonna open up the HTML page and I'll just add a script tag right here. I'm using the cdn for this. You could download the file if you chose to and just linked to it locally. So let me go ahead and say that we've got that taking care of. No. Now I'm gonna deal with the code at the bottom first. This is the easiest to change the get users user and the update Henry function. The reason I say it's pretty easy is because we just have to link to the Ramda. Leiber is all we need to dio. We no longer have the a t. J s dot Js file down here so we can't use pipe from that and we can't use curry from that. And so we're going to go are dot hype to link to that and are dot curry to link to the curry function that's in the Ramda library. Now, Ramda also has a clone function, so I'm going to change the clone object to our dock phone. Simple as that are not pipe. There are not curry. Let's change this to the clone function again. And then our dot curry. Now those functions air currently using Ramda so we could technically run Update. Henry, let me go ahead and save that. And if I open the console, we can then invoke up Henry, I'll do a score of 100 and we can then take a look at Henry. It is now 1 80 tries are four. Then we can also look at the users array. And here Henry has not been changed. So we can see that we're able to update the score for Henry. And we're not mutating that original Ray. So that's simple change allowed us to continue to work with the code we already had. But since we re factoring, I want to make it better. I want to improve on what we have here, and one of things I mentioned that we needed improve on is this update, score and update tries functions because they're currently not pure. They're modifying this user data. It's working for us because we're not mutating data in a way that has an adverse effect. But we really want these to be pure, and we can do that with random. As I mentioned in previous get exercise, there's a way to do without it as well. But I like the way we can make this happen with Rambis. So let's go ahead and take a look at that now. First thing I'm going to do is replaced this middle part. So what we want to do is update the score. Now, when you're learning to use Ramda, you'll need to come out to the documentation and take a look it and try to find a function that's going to help you do what you need to do. And the one I'm going to use is this S S O C function, and basically what is telling me it is It makes a shallow clone of an object and then it allows me to change a property. So the problem we were having with these functions is they were not cloning the object. So if I can do that at the same time, I'm making a change to the property that would work great for me So here's Here's how we would do that. I want to call that function first and then this function has three parameters. The first parameter is the property that we want to update in the object. And so, in this case, we're going to be updating score. Now it's the property One update or it could be a property we're assigning as well. So it could be a brand new property or attributes, and then we want to put in what the value will be. And so in this case, we're going to take user dot score, and the value is going to be that amount, plus the new amount that is passed in and then the third parameter is theon object that will be acting on. And so the object we want to act on is the user object was passed in. Now, remember, this is going to return a clone of that, so it's not gonna modify the one that was passed in, so that helps make the function pure. Now we've narrowed this down to a single line, so this is now the type of thing I would usually use a narrow function for. And so I'm gonna modify and do that as well. Since we have two parameters, we need to keep the parentheses here. But then we can do the fat arrow. Then we get rid of this last part here. So now the update score function is on a single line and it's improved. It's now pure. Now we can do the same thing with update tries. So let's go ahead. Since we know we're going Teoh, do this as an arrow function. Let's go ahead and start that way. Since there is a single parameter I don't need, the prince sees I can just have the variable there, do the fat arrow and then we're gonna replace all this part here using our dot assoc from Ramda. And what attributes are we updating tries in? The second thing you want to pass in is the value, so user dot tries now you might initially think, Well, let's do this. However, the problem with using the increment operator is that it will update the original object and so we need to do this instead. We need to do plus one like that and then the object we're going to act on his user so there. We have update, tries and update scores and their improved. They're better than they were there now. Pure. All right, so let's continue on. I want to do some more because I want to show you some additional things we can do with Ramda. And so let's modify the get user. And by the way, while I'm up here, we can get rid of this function. Could we Don't need it anymore. We're using the clone function from Ramda. Let's go ahead and modify. Get User. So what I'd like to do first is change this if statement in here and I'm gonna use rammed it to do that, I want to show you how you can use this library to eliminate if statements you conduce. Oh, it all with functions. That's one of the things that Ramda allows us to dio. So what we're going to be doing is checking the value as we move through each element in the array, we're gonna check check the value, which is an object, the name property of that converted to lower case and see if it's equal to the name that's passed in. Converted to lower case. All right, and If that's the case, then we want to use the value this past in otherwise will use the accumulator value. And basically this allows us to use reduce to get down to a single object. And and that's the user that were trying to grab from this. So the only time we return value is passed in as if they're equal to one another. And then every other time will return the accumulator value, which we've labeled as O. B. J. Because we don't want to lose that. If we go to another, value is not equal to we could lose it. And so that's why in the else clause were returning LBJ. So we're going to use a function from Ramda to check this to do the condition. And Dan will use a turn eri operator to determine which we're going to return. All right, let me go ahead and remove that I'm gonna enter return because the end result is we want to return whatever we get. And then the function we're going to use from Ramda is e Q by so equal by and basically what this allows us to do is passing a function and then pass into values, and it will use that function on the values and to find out if they're equal to one another . So the function we want to pass in is the Ramda to lower function and that converts things to lower case and then the values. We want to check our val dot name and name that has passed in. So it will pass each of those through this and then see if they're equal to each other. If it is, it will return troops. So if that value is true now we're going to use the turn Eri operator. If that value is true, then we want to use the value that is passed in. Otherwise we'll use accumulator value. So there we've got that middle part taking care of. No, obviously you're where we can replace reduces well with the rammed equivalent. So let's go ahead and do that, and that is r dot reduce, and then we need to pass in a function that is going to be used by reduce. Now I'm going to make this an arrow function and we have to values. We have the O. B. J. And we have the A l So this is the accumulator value, and this is each element in the array as it cycles through them. Okay, Errol, function. So we want to use a fat arrow. And now here is what we want the function to Dio. And we've already modified that here, this is what we want the function to dio. So since the scenario function we don't need the return. The arrow function will automatically return that value. But with reduce in Ramda, we have some additional parameters we need to include So first off, we need to include an initial value for the accumulator. And as we did previously, we set it to know, Let's do that again. So I'm gonna put a comma and then knoll, and then we need to supply the array that we will be using reduce on. And so that's passed into the function. And so we'll put that there, and now we can close parentheses. All right, now, there's one more thing I would like to do here. I want to make sure that when we return the object that we found that it is already cloned , so I'm gonna include that as part of this So when we get a match, I want to clone that object. So this variable represents the object we find in the array that is equal to the name we passed in, where the name value is equal to the name we passed in. And so when we find that I want to clone it and that will place it in the accumulator value and so next time we need to pass that back, it will already be cloned. And so I'm going to use the ram that clone function to clone that just like that. Right? So we've taken care of cloning inside of these functions. As I've updated them, we've made them pure. So one thing that allows us to do is to remove the clone from this. And since we're removing clone from this now, we no longer need pipe because we only have the one function to deal with. So we can just create that get users user function by currying they get user function and basically we Corey it and a sign or attach the users array to it, and that gives us the get users user function. So remember, this was our very specific function that we wanted it to act on Lee on the user's array, the one that's a part of this, okay, and so that's why we curried it to assign that. So instead of passing in the uses array, it's already a part of this new function. So all this new function requires is a name to then retrieve the correct user. So we've made that function bit simpler as well, because we included the cloning up here. While we're simplifying things, let's go ahead and simplify the get Henry function as well. With one line, it could simply be an arrow function. Now we have no parameters here, so we need to put the princes there. And then we can't remove return because it does that automatically and remove the rest of this. And there we have a much simpler Get Henry function. All right, one more fix I want to make. This is obviously going long, but I think it's important to see all of things we can do. Let's modify the store user now doing the same sort of thing that we did with get user, so I'm just going to do that from the start. We did it in pieces down here so you could see the process. We did the middle first, and then we modified the reduce. And then we updated this clone. And as you could see here, we could make this an arrow function pretty simply because it's down to a single line within the function. Now I keep saying that, but I don't want that to be the prerequisite for a narrow functions. That's just my own personal application of aero functions when they're simpler functions. I loved to use zero functions. If they're more complex, I think they're easier to read as regular functions. But for store user, let's go ahead and make that an arrow function as we do this so we can get rid of the function keyword. And then we create our fat arrow. I'm gonna press a couple returns, so I have the code down here so I could refer to it as I'm creating this as I'm re factoring it now. First thing I want to do is map. So are dot map one. Use the map function of the Ramda library, and then what are we doing inside of math? We need to pass it a function that will act on each these elements. So basically, map is going to create a new array that will have the updated information in it for whatever user is passed in. Or, I should say, for whatever array and user is passed in. That's what maps going to do. So let's pass at a function and will make it an arrow function again. So that is the parameter as it cycles through the array. Vowel will store that parameter than the fat arrow. And we're going to use the same function down here that we used because it's the same process we're looking to see if the user matches so are not equal by and then in parentheses r dot lower to lower. That's the function were passing in, and we wanted to act on val dot name and user got name. Okay, so I want to see if those are equal. Once they're converted to lower case, and then if they are, then we will return the user, and that will get placed in the new array. Otherwise, well, simple return the value that was passed in. So the new array will consist of either the existing objects or will be a new object that's been updated. Okay, Now, with map in Ramda, we need to pass in is the second parameter the array will act on. So the first parameter is the function. Second parameter is the array, and then we can end it Now I can get rid of all of this down here. So see what we've done. We have really simplified things. Oh, and one more thing we can take care of down here. Update Henry, We can remove that clone because we took care of that when we updated these other functions and so even simplifies that a bit more. All right, so there we have our functions set up. So one more thing, I probably would have done as I was doing this in a functional style, as I would have used const for these as we've moved through this code, sometimes I haven't always updated things. We started with some code that wasn't based on functional approach at all and then moved to more and more and made it better and better. And this last exercise, we re factored even more with Ramda to make it simpler and cleaner. All right, let's just see if it still works for us. That's the trick, right? When we open up the console. Good sign. There's no heirs there. Let's go ahead and do update Henry, and I'll do 120 this time for kicks. Let's see what we get. But update center 120 tries four. And then if we look at the original users array and that is still as it should be, So it didn't modify the original uses race. So we returned an array, which we could then use going forward right here with the new data in it. All right, now you may be looking at this and saying, I don't know if I could do that. I don't know if I could have re factored everything this way. Well, what I would recommend is just watch through this a few times, get used to it, go to the documentation, rammed and read about those functions. That's the process to go through to get more used to this. An important thing to remember as it you're applying more and more functional principles. You just got to be patient with yourself. You're not going to go from point A to point Z in one fell swoop. It's going to take time and you'll do it little by little. That's how I did it. I think that's how most people do it. All right, let's move on. 43. Understanding Recursion: a simple definition for Rikers, Asian is it is a function that calls itself and functional programming. The tendency is to avoid loops. We saw how weaken iterated through a raise without using loops. Rikers, Incan be used to solve other problems that may require looping. The basic idea of Rikers in is that you write a function that will solve a small part of the problem, and then you call it over and over again until the larger problem is solved. Let's use an example to illustrate this. The most common example used when teaching incursion is factorial now. First, a quick review of Factorial, the factorial of some integer, is the product of that indenture and all the integers below it. So the factorial of three is three times two times one or six. Now, factorial can be used to figure out the number of ways a specific number of items can be arranged in the sequence. So if you have five dishes as an example, the number of different ways those dishes can be arranged is five factorial or five times four times three times two times one. So determining the factorial of a number is a perfect example for using Rikers in. So let's break this down. First, to find the factorial of five, we would need to do this five times, four times, three times, two times one. And that would equal 100 and 20. Now we could do the reverse is well, it could be one times, two times three times 45. The end result is the same. So it doesn't matter the order. It just matters that we multiply all of those numbers together. So now how would we express this as a function? Well, if we passed a number into a function, let me set that up. And so passing a number into the function. And then we want to find the factorial that number. Well, it would be a matter of returning, okay, Numb multiplied by numb minus one. And then we would have to repeat that, right? Because this would work beautifully if the number of past and was too two times one that would give the factorial of two, which is simply to now. This is the small part of the factorial problem. And we can use this to solve the larger part by running this over and over and over again. So how would we do that? While the way we do that is we simply for this last part call the function again? So numb times the factorial of no minus one and then that brings that new number into this function. Now, this is called the recursive case. It's called the recursive case because we are calling the same function again. Now, don't let this confuse you just because we're calling a function that happens to be the function we are in. This is no different to the javascript engine. Then if we were to call a second function, say something like this, the JavaScript engine would process the results of this function, call return the results and then it would process the rest of this function here. If this factorial numb function happened to call another function, the javascript engine would process that first returned the value to factorial numb, finished processing that and then return the value to factorial. This is called the stack. As each function is called, it is placed on the stack. The function at the top of the stack is processed first. Then once that function has done it goes to the next function on this stack. If a new function is called, it is added to the stack. So we're gonna come back to this idea of the stack to help you understand Rikers in But lets first finish this problem and then I will go ahead and illustrate that. So we have the recursive case right here. This is a recursive case because it is calling the same function we're in. But right now, this will just keep executing. Say we did factorial five. It would keep executing. It would go into negative numbers. It would not stop. We always need tohave. In addition to the recursive case, we need tohave a terminating condition. And it's also referred to as the base case when we're doing Rikers in. So let's look at what that would be. Basically, we want to end this once, numbers equal one. So if num is equal to one at that point, we can simply return one because we know that the factorial of one is one. We could also return numb. Either way, we return one, and that's what we want to accomplish their this causes because we have a return statement here. This causes this function call to end. So let me finish this so we can see the results and then we'll run it and then will illustrate how it's working. So there's our number five and unless just log to the console results. So I'm going to save that refresh and let's display the consul. So we have 120 that is the factorial of five. So that is working for us. Now let's talk about how this is working. So five is the number that has passed in it checks to see if numb is equal to one. It is not so it goes down here and it returns numb. But before that value could be returned, it calls another function, which happens to be itself, and this time it calls it with a four so four gets passed in. That's not equal toe one. It returns four times, but before it can return that it calls it again with a 33 gets passed in, it returns three times before it can return that number. It calls it again with a two and then a one. When it's one, it returns a one and so, at that point is no longer calling new functions. And so then it begins to unwind the stack. So it then multiplies one by two and gets the results, which is two. And then to buy three gets results than which is six than six by four and so on, and that is unwinding the stack. Now I think this is better illustrated if we look at a page with it written out. So first off, we're computing five times the factorial of four. So this is what's getting put on the stack. And then we get five times, four times the factorial of three. Five times 35 times, four times, three times a factorial of to five times, four times three times of times, two times a factorial of one. And now, since one is the value, it returns one. And so this is what we end up with. And then it unwinds that we get one times two, which equals two. Then we get three times to which equals six than four times six, which equals 24. And then finally five times 24 which equals 120. And that is the end result. So that is how this is working. It is placing these things on this stuff, and then when it's able to when that want, when it gets to a one, it then unwinds this stack. Now I want to introduce the same thing using the the bugger, because I think it helps clarify what's going on. It helps you to see that stack as it's happening. So let's take a look at that. I'm going to refresh. Let me open up the consul here. I'm going to go to sources. Let's open up the Java script file and then right here, I'm going to set a break when this code executes. I wanted to break here so we can see what's going on inside of the the bugger. All right, so now I'll come back and I'll refresh this page. And here the execution stops on this line. Now let's take a look at a few things. First off, you can see what numb is equal to. Numb is equal to five. You can also see it down here in the scope window. And over here is the call stack notice. There is an anonymous call to function That's when the function is first called. Let me jump to JavaScript file right here. That's lying. 10 shows you the line number, so that's when its first called. And then we get a call to Factorial that's happening right here. Line seven. Now let's go ahead and continue executing. Now Numb is equal to four and notice we've added another call to the stack right here. Go again, numbers equal to three. We have 1/3 call, and again, Numb is equal to two. Now when I do it one more time and now we start unwinding the stack. We now have a return value showing up here two times. One equals two. Let's go again and watch this online return values now equal to six. Now we only have three left on the stack again. It's equal to 24 again. We have the final value, so it only has to finish out this final call to Factorial, and to finish that out, it's simply returns the value which we've arrived at. So I go on more time and now finally equals 120. We can just finished the execution than if we jump the console. We can see that the 1 20 is showing up. So that is how Rikers Asian works. It can be more difficult to understand than loops. For some reason, the fact that we're calling the same function we're in just seems to confuse us. But think of it as it's no different than if you're calling another function that would be doing the same thing as the current function you're in. Now, before we conclude this topic, I want to take a look at this same function as you might see it, written by someone who does functional programming. And so they would use aero functions and they would simplify it. And so let's look at how that might be done. So first off, if we were to change this to an arrow function, we would remove the function keyword, add the fat arrow, and then we can get rid of the if statement, because what I'm going to do is use the Turn Eri operator and we're going to check to see if numb is equal to one. If it is equal toe one, then one is what gets returned. Otherwise, we returned this none times factorial of numb minus one So now we've got this entire function on a single line, and this is how you would probably see it written by someone who's doing functional programming and just to verify. Let's make sure that's working and go ahead and refresh Open the console. And, yes, we have 120. So, using the Turn, Eri operator allows us to eliminate the if statement as well. We basically check here because of those parentheses. Check to see number is equal to one. If it is, we return one. Otherwise, we returned none times the factorial of no minus one. So that is Rickerson. Let's move on to the next topic. 44. Congratulations!: Congratulations. You have completed this course on functional programming. Now, for most of you, these concepts are new and may take some time to grasp. Don't get discouraged. That was my experience as well. But the goal and when I hope I was able to accomplish is to give you the ability to understand the concepts associated with functional programming. That is an important first step. Then you can begin incorporating these techniques into your own code. Review these topics more than once, and I promise that you will begin to understand more and more and be able to incorporate more and more. It could be a lot to take in all at once. Now something else to remember. Most people begin using pieces of functional programming. They don't switch. The functional programming all at once is that seems difficult to do, and not many are able to do that all at once, but they do it over time. They include more, more in their cold. They find things that they like that work for them, and they use that in their code. And then as they learn more, they use additional things, and I would recommend approaching it that way. Use what makes sense. Keep studying it and it will improve your coat. I wish you the best of luck in your JavaScript endeavors. And once again, congratulations.

Lập trình chức năng trong ví dụ JavaScript là gì?

Lập trình chức năng là một mô hình xây dựng các chương trình máy tính bằng cách sử dụng các biểu thức và chức năng mà không có trạng thái đột biến và dữ liệu. Bằng cách tôn trọng các hạn chế này, lập trình chức năng nhằm mục đích viết mã rõ ràng hơn để hiểu và chống lỗi hơn.a paradigm of building computer programs using expressions and functions without mutating state and data. By respecting these restrictions, functional programming aims to write code that is clearer to understand and more bug resistant.

JavaScript là chức năng hay thủ tục?

JavaScript có thể hoạt động như một ngôn ngữ theo quy trình và đối tượng.Các đối tượng được tạo theo chương trình trong JavaScript, bằng cách gắn các phương thức và thuộc tính vào các đối tượng trống trong thời gian chạy, trái ngược với các định nghĩa lớp cú pháp phổ biến trong các ngôn ngữ được biên dịch như C ++ và Java.. Objects are created programmatically in JavaScript, by attaching methods and properties to otherwise empty objects at run time, as opposed to the syntactic class definitions common in compiled languages like C++ and Java.

Lập trình chức năng được sử dụng để làm gì?

Lập trình chức năng được sử dụng trong các tình huống mà chúng ta phải thực hiện nhiều hoạt động khác nhau trên cùng một bộ dữ liệu.Lisp được sử dụng cho các ứng dụng trí tuệ nhân tạo như học máy, xử lý ngôn ngữ, mô hình hóa lời nói và tầm nhìn, v.v.in situations where we have to perform lots of different operations on the same set of data. Lisp is used for artificial intelligence applications like Machine learning, language processing, Modeling of speech and vision, etc.

Thành phần chức năng trong JavaScript là gì?

Thành phần chức năng là một cách tiếp cận trong đó kết quả của một hàm được chuyển sang hàm tiếp theo, được truyền sang một hàm khác cho đến khi hàm cuối cùng được thực hiện cho kết quả cuối cùng.Thành phần chức năng có thể bao gồm bất kỳ số lượng chức năng.an approach where the result of one function is passed on to the next function, which is passed to another until the final function is executed for the final result. Function compositions can be composed of any number of functions.