 Let's begin by looking at how to declare variables in JavaScript. To declare a variable in JavaScript, we specify its name and assign it a value, in this case, the string Daniel. We can print a variable using console log. So we'll type console.log, followed by the variable name. Notice that we didn't include any semicolons here at the end of our two statements. Semicolons are optional in JavaScript. Now let's go ahead and run this program. We can run it by typing node followed by the program name intro.js. Here we see that Daniel is printed to the terminal. Here we'll use the const keyword to specify that the variable name is a constant and isn't expected to change throughout the program. So if we run this by typing node.intro.js we'll get or print out for Daniel. There are two other keywords that you'll see. The first keyword is the var keyword. And this specifies a variable that's global in scope. The second keyword is the let keyword. And this specifies a variable that's local in scope. Also remember that semicolons are optional in JavaScript. So if we run this, we don't get any errors. Great. Now that we've talked about variables in JavaScript let's move on and talk about loops in JavaScript. Great. Now let's talk about four loops in JavaScript. So let's write a simple example loop. So here we have the four keyword. Then our initial condition i equals zero. As long as i is less than five. We'll increment i. So this is very similar to other languages. And let's play with this idea of the var and let keyword here. So we'll have a var keyword count and then we'll set it to i. And then we'll console log that var keyword outside of the loop. And so remember the var keyword is global in scope. So it's going to be preserved. The variable is going to be preserved even after the loop is complete. So that count variable will be available outside of the loop. And that's just because we're using the var keyword. So let's pop down to the terminal now and run this. So here you see that that count is four because we were able to preserve it outside of the loop because we used the var keyword. So if we change that keyword to let it's only going to be available within the scope of the loop. So if we go ahead and try and print count here we'll get not defined. And that's because the count variable is not available outside of scope. And that's because we use the let keyword here. So now that we're kind of comfortable with loops in JavaScript let's go ahead and look at an example of types. So JavaScript is a dynamically typed language. And we have several types. And one of the easiest ways to check the type of a variable is to use the type of keyword. So let's look at an example of using the type of keyword here. So there are several types. One of them is the number type. And so if we do type of and then a number like five and we'll console log the result of this type of call function call, we should get number. So let's go ahead and clear the terminal and then run our program. And so we get a number. So a number is one of the types in JavaScript. We also have a string type. And so if we replace this with a string test and we run this we'll get string as our type. So we also have the Boolean type. And so we could type in true here. And these are default lowercase in JavaScript. So it's important to be careful there. And so here true is a Boolean type. And we also have the null type in JavaScript. So null is a type. And for historic reasons, the null type when you do a type object on it will return object. So let's go ahead and run this and see. And so the object return type here is for historic reasons with JavaScript. And so the final two types are the undefined type. And this is for variables that have not been initialized. And then the object type. So every other variable that we haven't discussed before is type object. Now let's talk about some syntax that you might not have seen before. Triple equals. And this is different from double equals. So triple equals is going to do a slightly different type of comparison to double equals in JavaScript. So let's go ahead and console log five double equals the string five. And so what do you expect to happen here? So JavaScript if we run this is going to print out true. So let's go ahead and run this. So why does it print out true? JavaScript does something called type coercion. Type coercion is very similar to casting. So it's going to coerce one of the types so that the types match. More specifically JavaScript will try to transform the type on the left side of the operator so that it matches the type on the right side of the operator. So in this case the number five gets transformed into the string five. This is different from the triple equals operator which does not do type coercion. So variables are compared directly. So if we go ahead and run this program we'll get false. It's important to be very careful when working with type coercion in JavaScript. For example some strings get converted to zero or get coerced to zero. For example the new line new line character string forward slash n forward slash n actually gets coerced to zero. So if we run this we'll get true. Let's look at a slightly more involved example. So let's create a couple variables and this example will illustrate two types of coercion. Implicit coercion and explicit coercion. With implicit coercion the JavaScript engine is going to do the coercing for us. With explicit coercion we're going to do the coercion explicitly. So here we'll create two variables x equals three the number and y equals three the string. Now if we do x plus y here the x which is on the left hand side of the operator is going to get coerced to a string three and so our result is going to be 33. However if you're a programmer and looking at this really quickly you might not see that. And so let's go ahead and run this. So here we get 33 as a result. Instead we want to implicitly tell the reader that this is being changed. So we could wrap this in a string function. So we'll say string x. This explicitly says that x is being converted to a string and then add it to y. And here y will be treated as a string because that's its original type. So 33 is our result. Now in the next module we'll talk about functions. So let's clean up here and switch over to the next video. Great. Welcome to another lecture. In this lecture we'll talk about functions in JavaScript. One of my favorite quotes is by Douglas Crawford where he says the best thing about JavaScript is its implementation of functions. So let's switch over to the live coding environment where we'll start implementing functions in JavaScript and you can get a better feel for how you can write your own functions in JavaScript. Let's get started. Here we'll create a function called grow. And our function will take two parameters, the number and then the percentage that we want to increase by. So let's start off by typing the function keyword. So the function keyword tells JavaScript that we're creating a function. Then let's apply the parameters. So we'll start last. That's the number and then increase the percentage that we want to increase the number by. Then we'll use curly braces to indicate the beginning and end of the function. And here we'll just return last multiplied by one plus our increase, which is a percentage expressed as a decimal. JavaScript supports named and anonymous functions. Here this is an example of a name function. Notice it has a name following the function keyword. It also has two parameters last and increased and also uses the return keyword to specify what's returned from the function. Let's go ahead and call this function. So let's call grow and then two parameters. So here we're calling the function grow on 0.7 and increasing it by 10%. So our result should be 0.77. So let's go ahead, clear the console and run our program. Great, we get 0.77 as expected. Okay, let's look at another function example. So in JavaScript functions are first class objects. So we can use them like we would use objects or other variables. So let's go ahead and assign this function to a variable called career. Now we can call the grow function by referencing the career variable. So we can replace grow with career. And if we go ahead and run this by typing node.intro.js we get 0.77 as before. So here we've indirectly called the grow function through the career variable. And this is because functions are first class objects. So this means that we don't actually have to use the grow name. We can remove that here. And when we do that we've created an anonymous function in JavaScript. So here this function is an anonymous function because it doesn't have a name and we've assigned that anonymous function to a variable called career. So let's go ahead and run this function. So like before we'll type node.intro.js to run our program. And we get 77. So semicolons are optional in JavaScript. So sometimes you'll see a semicolon included at the end of a function. And since this is an assignment statement this is how programmers kind of emphasize that this is a complete statement. Great. So next time we'll look at arrow functions which is a unique thing to JavaScript. Welcome back to another lecture. In this lecture we'll talk about special functions in text called arrow functions that JavaScript supports. Arrow functions begin with a bracket and close all of the parameters within it. Then there's a special arrow that's assigned to an expression. This is the body of the function. And then because it's a first class object we can assign this arrow function to a variable, in this case the variable funk. So below we'll see the function expression that we looked at in the last lecture. Here it has the function keyword then some parameters and then a return for an expression. This is a good one to the arrow function. Notice there's no return statement here. Here notice there's no return statement. The arrow function will just return the result whatever the expression is. Whatever expression is on that line. Now let's switch over to live coding and look at some examples. Let's create an arrow function that multiplies two numbers. So we'll start with our brackets and then our two parameters call them A and B. And then we'll do our arrow function which is just equal followed by the greater than sign. A times B. And then great. There we have our arrow function. So we can assign it to some variable. So we'll do our equal operator and then we can call this variable multiply but before we do that let's specify the let keyword. So now we have a full arrow function. And remember that the let keyword is optional and so to remove it all variables are just assigned the let keyword by default with JavaScript. So now let's go ahead and look at an example of writing the multiply function with our previous syntax. So we'll have our multiply variable and then we'll assign it to function. It's an anonymous function and we'll take into parameters A and B and we'll return A times B. So the arrow function above is equivalent to this function here. And remember semicolons are optional. So notice that we don't have a return statement and that's because if we have a single line arrow function the result of the expression is what is returned. So let's go ahead and write some So now let's look at an example of calling the arrow function. So we'll do console log and then multiply and let's name the second function of this one. So we'll call multiply and we'll supply two parameters in this case two and four. So let's go ahead and run this. So we'll do node and the name of our file intro.js and we get A as expected. Okay let's write another arrow function. So this arrow function that we'll write will take a parameter and compute it square and to be more efficient we'll just use the multiply function that we wrote earlier. So let's go ahead and make some space and then we'll put our opening brackets followed by a parameter in this case we'll call that parameter A and one of the great things with our functions is if you only have a single parameter you don't need the brackets so then we can have our arrow function and then we can call multiply on A, A. So this would be our function that computes the square and then we can go ahead and we can assign it to some variable square. So now let's call our square function so we'll call square and then we'll pass in our single parameter A and we'll select a value here for A so we'll say 4 and now let's go ahead and run this program so we'll clear the console and then run our file node intro.js and so here we get 16 as expected so far we've looked at our functions that use a single line so let's go ahead and clear the screen and look at another example of an arrow function that uses multiple lines so this arrow function that we'll write will take in two numbers and then return the number that's bigger so let's go ahead and use our arrow function syntax, we'll take in two parameters and here we'll use curly braces to denote that our arrow function is going to be more than one line so then we'll check and we'll see if A is greater than or equal to B then we'll return A otherwise we will return B notice that because our arrow function is multiple lines we've included a return statement and curly braces and then let's go ahead and assign this to a variable bigger so now let's go ahead and run this code to see if we have any errors so we'll do node intro.js great no errors so now let's go ahead and call the bigger function so we'll do console log bigger and we'll pass in two parameters here we'll pick two numbers and six so now let's run this and if our functions working is expected it should return six great we get six returned as expected great now is a challenge pause the video and see if you can write a shorter version of the bigger function ideally we want to get down all the way to a single line as a hint let's do this if you use the ternary operator so go ahead and pause the video great let's start looking at some solutions so here we'll have two parameters a and b followed by our arrow function like before and then we'll have our return line where we'll check is a greater than or equal to b and then we'll use our term operator and if a is greater than or equal to b then we'll return a otherwise we'll return b then we can assign this to our bigger variable so if you go ahead and run this we'll get six like we did before but we can still make this shorter here we have a single return and so we can compress this down to a single line so pause the video and see if you can do this so here we'll remove our curly braces we'll remove our return statement because we're just doing a single line so we don't need it and now we have our one line version of our bigger function so let's go ahead and run this to make sure that we don't have any errors so we'll go down and type node intro.js and we get six as expected so I hope you enjoyed this section on javascript functions in the next section we'll start discussing javascript objects and javascript's inheritance model welcome to our second lecture in this lecture we'll talk about javascript objects javascript objects are containers for properties and these properties are name value pairs so each property will have both a name and an associated value values can be any javascript type except undefined this means that values can even be other javascript objects now that we have a general idea of what javascript objects are let's switch over to the live coding session and write some code that demonstrates these ideas so we'll begin by creating an empty javascript object we'll use curly braces to signify the beginning and end of the object an opening curly brace represents the beginning of the object and a closed curly brace represents the end of the object notice this object doesn't contain any name or value pairs we can also create a student object and we'll include a couple of properties in this student object first name so the name is first name and the value is daniel notice that the property name is a string we can also add a property that doesn't use a string in particular here the property name title is not a string but the value phd is a string properties in an object are separated by a comma let's add a third property last name here the name is last name and it's a string and the value is gram and it's separated by a comma it's important to note that the last comma is optional for objects so the last property doesn't need a comma at the end objects can also contain other objects so let's create an object that will contain the student object let's call it teacher and let's add some properties we'll have a name property daniel, gram comma separated then we'll have a student property this student property will be another object so we have our opening and closing curly braces it contains a property age comma separated another property name in this case john stewart the famous comedian and finally a grade in this case a number 86.2 remember that trailing comma is optional we included it in the first object and the second congratulations you've written your first object in javascript take a second to look at it does it look familiar? do you think you've seen it somewhere before? if you said json you're right json stands for javascript object notation and it's the way that javascript represents objects now let's add some of the properties of the objects we've just created and in particular we'll log these properties to the console so they'll show up in our terminal below so we'll start by typing console.log and then we'll look at the student object and here we'll access the first name property because the name is a string we'll need to use the hard bracket syntax to access the property so we'll type opening hard bracket followed by the string representing the name close hard bracket then we'll run our code using the node command node object.js and notice it's printed out the first name Daniel which is the property of the student object we can also access properties using the dot syntax so here we'll access the title property using the dot syntax so we'll do student.title and then we'll run our program again and here we'll copy the object and here we get phd as the value now let's access some of the properties associated with the teacher object so we'll copy our console.log code down to the bottom here and in particular we're going to do a nested property so we'll access that object that's associated with the student property so we'll do teacher.student that gets us to the student property on the side of the student object let's go ahead and run this and we get john stewart which is the name of the student nested in the teacher object take a second to look at this example now let's go ahead and access a property that's not associated with the object in this case salary here we're going to get undefined because this property is not associated with that object so the salary property is not contained in the teacher object and so we get undefined let's look at another example in this example we'll access a property within the salary property so teacher.salary would be undefined and so if we access teacher.salary.raise here we're going to get an error because raise is not a property of the type undefined the property raised from the type undefined now that you have some practice reading properties let's look at an example of setting a property here we'll set the name property here we use the bracket syntax and access the name property and then the equal sign to assign a value to that property and here we're assigning daniel ggram as the new value to the name property we can also use double quotes or single quotes in javascript so let's just illustrate that here notice that we've used the bracket syntax to access the name property now let's go ahead and console log the teacher.name property I've used both the bracket and dot syntax here to show that they can be used interchangeably now let's run our program and if our program is working correctly we should see daniel ggram phd as the new property value and there we have it, daniel ggram is our new property value so now let's go ahead and set a property that wasn't already defined in the object in this case we'll set a new property whose name is propose and so we'll assign it some value and here the value that we'll choose to assign it is thinking and creating so what this will do is create a new property associated with the object so let's go ahead and use the dot syntax to do the same so teacher.affiliation and uva and then we'll look at the teacher.propose property using the dot syntax and we'll also do another console log for the teacher.affiliation property and we'll use the dot syntax here as well notice that we get a great auto-complete with visual studio so if this is working correctly we should see thinking and creating and uva printed out great we get those values printed out as expected once more I'd just like to highlight that the bracket notation and the dot notation can be used interchangeably because they're equivalent okay now let's look at an example of creating properties in a nested object and also setting those properties so we could always create a property by simply adding it to the initial declaration of the object so here we've added a property rank for the student and a value of 4 so now let's go ahead and set that property so teacher.student.rank and now we can assign it a value of 1 and console log this property and here we should see the value of 4 be updated to the value of 1 so let's go ahead and run this great or rank is set to 1 so let's clean up our IDE here and get ready for the next lecture so in the next lecture we're going to talk about inheritance in JavaScript okay welcome back to another lecture in this lecture we're going to talk about web APIs and web requests and we'll give an overview of these and we'll look at how we can get data to and from or apps and so let's switch over to slides and start digging it so api stands for application programming interface and it's the way a client like a mobile app or a terminal application like curl will communicate with a web server and that web server will be running web api and so these web apis are typically implemented using frameworks model view controller frameworks like Django or ASP.NET but there are also serverless implementations like the one that Amazon uses and Amazon AWS uses we'll look at Google's serverless implantation in the form of cloud functions we'll cover these topics in more detail later on in the lecture but this lecture is intended to give you kind of an overview for how this communication mechanism happens so here's the client server breakdown from before and what the client will do is it will connect to the server and it will issue a request and there are two forms of these requests there's a get request and a post request in this class we'll be mostly focusing on pokes requests but I want to mention what a get request is so in a get request information is placed in the URL that's all you have to kind of know about it for now and then the server will generate some response and this response could contain your data in the form of JSON so let's make this clear by looking at some examples of web APIs so this is the javadoc for this web API that gives you cat facts so if we click on this we'll see the web API here so the API is going to generate a response and this response is going to be a JSON object and that JSON object is going to have two properties one is called fact and that will have whatever the cat fact is and then the other property is the length of the fact and it also has a status code we'll talk a little bit more about what these status codes mean but just know that 200 means that everything went well with the web request we can also access the endpoint and get a fact so if we do catfact.ninja forward slash fact we'll get a fact and so here's one of these cat facts cats must have fat in their diet because they don't produce it on their own and that's 76 and if we press this we'll get another cat fact say the relative to its body size the clouded leopard has the biggest canines of all animals it's dagger like teeth can be as long as 1.8 inches so great that's another cat fact let's switch back to the slides I just wanted to point out this list here so this list is a list of open source public apis some of which you might find useful for your projects so let's do let's deeper dive into this catfact api and in particular let's look at the response and request so curl is a command that you can perform on the linux machine or a mac and it does a web request out to the url that you give it so here if we did curl on catfact api endpoint we'd get the following response so just a couple things to kind of highlight here that you would want to pay attention to in your responses so this code here this 200 code means that everything is okay that the request was processed correctly and you also want to see the time and date for the machine this might also be important for some of the requests the actual data the actual catfact will be included here so this is the word that data will be in the request but a lot of libraries will go ahead and parse this for you and the data will be easily available to you so you don't have to worry about the syntax here just know about these condition response codes and time those are two kind of key elements and the request it's normally a get request this is just kind of an example an example request you don't have to worry about this but the request also has headers and I just wanted to point this out just in case you get into a situation where you're going to be debugging and you need to look at the headers to make sure that your request is formed correctly and to stress this this is just an example request this is not the actual request that went out from this so now let's switch over to some live coding and talk a little bit about asynchronous functions so just a reminder if you're going to follow along with this remember to install the request mpi module that allows you to do requests okay so we're going to switch over to our live coding session now okay let's go ahead and install requests u.x.x this will get us the most recent version great we got a successful installation with zero vulnerabilities which is good so let's go ahead and include that request library and the way that we do that is we use this required keyword so we'll talk a little bit more about importing later but this require where let's just use the request npm library we're going to just throw that in a constant called request okay now we're going to have some var app and remember the point what we're writing here is an application that will go out to the catfax api and get us a catfax and for our app we'll have some url url forward slash fact um and then we'll maybe also start the catfax part of this office is also catfax and we'll set it up as blank so let's go ahead and make a request so the way we make a request is by saying request and then we pass in url so we'll do app.url and then we pass a callback so a callback is a function that is called when the request is ready and this request function will pass that function information to then process so let's call our function or callback handle request so once our request is ready this handle request function will be called so let's implement that handle request so request is going to pass this handle request function to parameters error there is an error and then the response if it's able to successfully get the response and we'll make this an arrow function just for readability so if there is an error right we will want to just console log that error if not there is no error then we're going to go ahead and set app.catfact to the response.body so remember responses had headers and body and the body was where the data was stored and so we want to go ahead and take the body part of the response so here now if we go to the bottom here and we console log print catfact app.catfact we're actually going to not get anything printed out so you think what would happen is that this request would fire then it would go up to this handle function handle request and then when it has the response it will pass in the response and then that response if there is no error will then get updated to the object app.catfact and then we would progress here to the app.catfact but that's not what happens what happens is that this request is processed asynchronously so it will execute line 16 and that will execute in the background and then it will go to line 17 and since catfact is empty it will print catfact we will get nothing let's go ahead and clear this and clean this up a bit so I'll save it and we'll run this and it said print catfact but we got nothing so the question is well how do we fix this right what do we do well we could go ahead and print the catfact out in here right so we could go ahead and print or catfact so we're just going to go console console.log for app.catfact so now we'll print something out here that says in handler print so if we go ahead and run this now it promises we'll first print out the print catfact and then we'll print out in handler and then our JSON for the catfact so let's go ahead and clean up this JSON a bit so let's do json.parse so we'll just create a nice clean object instead of a string that body and we'll just extract the fact and not the length so we're going to ignore this length field from that and then we'll go ahead and print out that new object so now we should just get the JSON object without the length so I'll clear this and then we'll do node promises.js and there we go in handler and catfact but notice it printed this catfact first and then once the request was ready then it printed the second catfact you know that's okay so we just have to include our prints and updates in our handler functions but this might not always be the case so let's search back over to the slides and consider a more involved example let's take a look at a more complicated example so we looked at a kind of simple API request where it's possible to kind of nest what we're interested in inside of the handler but that's not always good practice so here's an example of a login workflow so here's there's some user and they'll supply their credentials which is just a fancy way of seeing their username and password to some client and then that client either a mobile application, a web application a tablet application we'll go ahead and pass those credentials normally by a post request to some authorization server and then that authorization server will return an access token and a refresh token we'll talk a little bit about what a refresh token is when we look at OAuth but the client will then pass that access token to some research folder say it wants to get email or something else and then that research folder will return the resource and a new access token and it's not a new access token isn't always a return but sometimes a new access token will return it so the idea is that you can create a really secure OAuth server with a bunch of things on logging and checking for credentials and then your resource servers will just need to have these access tokens both of the services have access to the same backend database we'll talk a little bit more about this architecture a little later but what we want to be able to do is could we think about how to implement these request structures here as we've seen previously so we had a simple example where we could kind of get the token but how do we then use the token so here's our logging example with curl and here I'm passing in the JSON with the credentials and so in this case the credentials are peter and they're password city slicker and I'm using this API endpoint here called request and this is kind of an open API that lets you kind of test authentication so you're interested in testing your mobile apps with any kind of auth service this is a really good site to look at so let's switch over to our live coding session and look at an example of using this request API but before we do that actually I'll show you what this request API looks like it has collection of things one of the endpoints that it provides is this most login successful endpoint so if you click on this it will show you what JavaScript the API is expecting or which JSON object the API is expecting and what it will return and so here this will return this is expecting email and password and if the email and password match this then it will return and produce a 420 code it's an example of the request API there are other APIs like login unsuccessful which will if you're missing a password it will return missing password and a 400 error code okay so let's switch back over and write some JavaScript to access this API and read the JSON values that we get back so one way of getting an external library in JavaScript is you can use this request in text so I can say require request then we're going to go ahead and start that in or just request variable so we can princess that class and make this a constant and then we'll create our app namespace and once I make the URL gps gps.in.bi.login and then a token and this token will start it off with something that's empty and then one of the things that we can do is along with this request is we can pass it some options so say request and we're going to pass you some options we'll build this up and then we're going to need a function to handle our request handle handle request so what are these options that we can pass? well options is an object that's what the request library requires and this object will contain things like URL or URI so that app.url what is that? and the type of request that we're going to get so post there are two types of requests post and get the request, post the content inside of the packet so that's what we're going to use here and then the JSON value that we want so we'll use the same post content from before and I'll clear the screen here so here we're going to post email and password and this is what the endpoint expects and then we're going to go ahead or our handler we're going to go and have something that's going to handle the request so handle request and this is going to have some error and some response and it will be an error function and I will say if error if we get an error we're going to return console log, we're just going to return from the function and we're going to console log the error otherwise we're going to go ahead and get the app token and we're going to parse the response body which is going to just be a JSON here and we're going to get the body of it and just the token and then we're going to go ahead and console log in handler the token plus the API app token okay and so now this request we'll go ahead and fire and I will make this smaller so we can see all the options here and so towards the end it doesn't make any sense to do a print token because we're not going to get anything here so I'll run this so first I'll save it and I'll do node I'll do node promises.js and there we go in handler and we got our token I should have included a space so now we have a choice so we need to take this token to then authenticate with other services or get some resources so we have a choice we can't put a handle request object here because we won't have the token at that time instead we could kind of nest the handler request in here so if we wanted to do this we could do another handle request and I just want to preface this by saying this is kind of bad practice we don't want to end up nesting all of these requests we want to have a better strategy so we could have another handle request here and we create another handler maybe handle request2 and then it would take in some error and some response as the error function here and if it had an error we would return and console log that error now we would go ahead and inside of this we would then fire our request and then with our additional options if we decided to write them and then our second handler so and then if we needed to do another request using information from that request we'd have to create another request in here this is not very good coding practice this is kind of a bad idea so let's switch over to this notion of something called promises great so let's now talk about a way of solving this problem of nesting handlers inside of all their handlers so JavaScript solves this problem by introducing promises so promises are special objects and these objects have some properties about them that make them really useful for doing asynchronous programming so for every new promise that we have a function pointer is passed into that promise and so if we look at this example here we have a promise the new promise being declared and it takes its parameter is a function and this function needs to have two parameters associated with it the first parameter needs to be called when the function, the asynchronous function successfully completes and the second parameter needs to be called when this asynchronous function fails so you can think of the promises kind of a wrapper for these functions in particular when the resolve or reject methods are called they set some internal state properties associated with the promise so promises state initially starts off as pending and when either the reject and then changes to fulfilled or rejected depending on the results of the resolve or reject call and the result means a value that was actually passed as a parameter these resolve or reject functions so this might seem a little strange but let's go ahead and look at an example so here's my new promise and then this executor function here is the function that's going to execute asynchronously so when that function completes it would call the resolve function and that would change the state of the promise to fulfilled and the value of that was passed to this resolve function would then get updated into the result property of that promise and if a promise if the executor, the asynchronous executor failed in its asynchronous task then it would fire the reject function and that would set the state, the internal property of the promise to be rejected and the result to be an error and that error value would correspond to the error value that was called by the rejected function so let's switch back over to the live coding environment and start looking at some examples of these promises great so let's switch over and do some live coding so before we noticed that these network requests take some time so because these take some time we want to figure out strategies for making sure our program doesn't block and one of these ways is to have these callbacks using handlers so instead of doing network requests using network requests to mimic long operations that take a long time we'll just use a timer so I'll just have this set timeout value here and I'll just do a console log so it's an error function so it's a console log and I'll just say done and set timeout as far as after physical time so in this case a thousand seconds oh a thousand milliseconds which is one second so I'll make this something larger so we can see it so I'll make it five seconds so if I go ahead and run this no promises it'll take five seconds before it prints out done so hopefully soon there we go so since we're using this as our asynchronous operation and our operation is going to take a long time over the network let's go ahead and wrap it in promise so let's say this is some new promise here is our operation it's going to take a long time so it's in function it takes in two parameters resolve and reject and these two parameters are based on defined by the JavaScript engine so the asynchronous function must take these two parameters in as as arguments and then we'll close this up here and so once the program completes it can set call resolve and when it calls resolve this will change the state property that's associated with the promise it's fulfilled and it will change the result property to be done so that's what resolve is going to do and if we said reject in the case of an error this is going to set the fulfilled property to reject it and the results to be done and here in a reject case we normally want to make this an error so the result would be so now that we've had this kind of wrapper for a promise let's go ahead and consume it so promises are consumed by consumers and so let's assign this promise to a variable maybe promise and say that promise to be explicit and then once the promise, once reject or accept is called then the then function will fire inside of the promise and the then function takes two parameters the first parameter so I'll just say function here resolve the first parameter is a function pointer and this function pointer gets fired when there's a successful thing from the promise in other words this first function gets fired when the resolve is called and then we have another function error and the second parameter is the one that's fired when the reject is called so we could go ahead and say resolve here and resolve would say great we got something and then once this resolve is fired after the timeout then we could console.log in consumer and then the result so I can go ahead here and I'll run this for you and after 5 seconds we should get a printout great so in consumer great, that was misspelled we got something the result was fired that changed the internal state after the internal state was updated the promise then method is executed and the result here is the value of the result internal property which was set to create we got something so pause the video and think about this so we could make this a lot simpler by using arrow functions we have a one line arrow function this is still valid and I'll just read from this and I'll make this a little shorter so we get the answer more quickly and another way that you might see this written is the second parameter might be omitted, the reject case and instead of a parameter for the reject case there will be a dot catch on the promise and this dot catch gets fired if there is an error so here we'll do error and then I'll just console log in consumer space plus my error so if instead of calling the result here we called a reject and I passed in something like here there is an error then on the promise with fire and we would get in consumer here is an error so I'll just clear this and then we can read what it is to see so couple things to mention is that if we have two things and accept and reject and the resolve fires before the reject will never fire here so we'll just exit the promise so I'll go ahead and I'll clear this so here we'll change the resolve to read no error everything everything create and so we expect here because this resolve function is going to fire first that we'll get in consumer no error everything is great so in consumer no error everything is great excellent if this did not fire first and instead the reject fired we would get in consumer here is an error we can have multiple results and rejects so for example if we had just resolve stop now we would get in consumer stop now in consumer stop now notice none of these other things fired so next time we're going to take a look at writing the web request example using this producer consumer model or promise consumer model great so in this lecture we're going to talk about the promise all syntax and then we'll start looking at some more queries or we'll talk about some functions that will help you write cleaner job script code namely map reduce and filter so let's stick it so what is this promise all syntax so the promise.all method returns a single promise that resolves when all the promises passes an iterable so this could be an array have resolved or when the iterable contains no promises this promise will also reject if any of the promises in that array reject for some reason and in particular it will take the first promise that rejects so just to say that simply it rejects with the reason of the first promise that rejects so it looks through the array finds the first one that rejects and then fires a reject for that promise so let's switch over to some live coding okay so let's look at a live coding example of using this new promise all syntax so let's create three promises we'll make them globally available so promise.resolve and we'll just make this first one as always three and we'll make something that just has a value that returns immediately just one three three seven third promise that will actually resolve let's do let's do this so we'll make a third promise that resolves after some time so we'll pass in an array function with resolve and reject and then we'll have our set timeout and we'll call resolve with foo and we will do single quotes here and we'll have that fire after 100 milliseconds so then we can save promise.all and we can pass in a collection in this case we'll do an array of all of our promises and notice it's a mixed type because we have a number type in here and then this.then will fire when all the promises have resolved and the values will contain a collection in this case an array with the results so values and I'll make this an error function and then I'll just go ahead and console.log of values so this should print out three one three three seven and 100 so let's go ahead and run this fun oh made a mistake here with my spelling should have been values not value so clear this and I'll save it and then we'll run this one great three one three seven and foo ok so I'll save this and we'll switch over now to slides and talk a little bit about arrays in JavaScript so arrays in JavaScript are a little special and in particular the root object for arrays supports a couple cool things supports these methods map reduce and filter and they're particularly useful when filtering through data or trying to structure data in a way that it makes it easy to present and they're particularly interesting when used with our functions so let's switch back over to a live coding session and we'll look through some examples of where at these map reduce and filter functions actually help us to write cleaner more readable code ok so let's go ahead and create a new array I'll close this explorer to give us some more space so let's create an array called students and this array we create it with this bracket syntax can contain anything because JavaScript is dynamically typed so we'll make this array contain a collection of objects so the first student object has a grade and the student had a 93 name a shade and then another object maybe we'll do some multiple lines for readability and then the student had a grade 96 and a name Devin and then a final student with grade of 19 and name of Elysium and so that's our student array and so say we wanted to go ahead and get all of the grades to create a new array that had all of the grades for each of these students so one approach might be we initialize some array for grades and this greatest array we'll go through and we'll say so I'll put some I 30 or I less than the students length so it's going to go through all of our students and then we would get our grade so we do grades.push and then we do students at index I and get the grade value so this might be one way and I'll just console along the grades here so we can see this so this is one way of kind of getting all of the grades from our array and so here is our grades but there is a different approach approach that allows for a lot of parallelism and also in some ways some more readability so let's switch back over to the slides and we'll talk about this concept called map and then we'll use that map concept to get the grades from our student array. Okay so let's talk a little bit about this new concept of map so what JavaScript allows is for you to apply an individual function shown in this box here to every single element in the array in parallel so I can apply this function to every single element in the array completely in parallel and then I'll get a new array with the result of that function applied to each of those independent elements here so say we had something that would square a particular value so here's my our function takes in some value x and then it returns x times x so if I apply that function if I map that function to this array it will multiply each of these numbers by itself and store that result in a new array so one times one is just one, two times two or three times three will be nine and then four times four will be sixteen and so here will be the result of completing that map so let's look at an example of where we're going to use the map function to extract the grades from that student array so let's switch back over to a live coding session okay so here we have our student array and instead of doing this for loop to generate this grades array we're going to use the map function so first we need to create a function that's going to get us all of our grades so we need something that will take in an individual object and extract the grades so let's call this map function and it's going to be a function that takes in a student object and simply returns a grade senate.grade and now we can create a new grades array by saying student.map the map function is going to take that function and apply it to every single student and we need to make sure we spell student correctly every single student and then return a new array with the result of that function so in this case it's student.grade and so now we go ahead and declare this and then we do node array fun yes we get a reference error because it should be students with a capital S so fix that great we get 939690 which is what we expected so we can also make this more compressed so we could create a function here as it's being passed in and you'll often see this done and so this is still valid so we'll declare this and run this again and we get the result as expected and sometimes you'll see an error function used so it's common to use error functions with this map syntax and because it's only returning one line we just need a one line error function here and so we'll add some space between the arrow and the function body and you'll see something that looks like this so we'll run this one more time and we get the same result so this is just a nice clean way of extracting the grade from every student in the array and you can look at this and you can read that this is going to create a new array with the student.grade parameters and if we wanted to scale those grades say multiply it by 1.1 to give everybody a 1% bump we could do it that way there we go here's our grades with the 1% ok so let's look at another function that's available to us called filter so let's switch back to the sites and look at this filter function ok so let's talk a little bit about the filter function so here is our old array and what the filter function will do is it will take in a function and this function is required to return either true or false and then that filter function is applied in parallel to the array and if the result of that filter function is false that value is not included in the new array so notice here that this one value is not included in this new array and the same thing for those two values it's also not included in the new array and that's because our filter function here is x greater than 2 so 1 isn't greater than 2 2 isn't greater than 2 but 3 is so its result is included in the new array and all of these are kind of applied in parallel and so this is a great way if you want to kind of extract some data from your JSON the filter function is an amazing tool so let's see this filter function in action great so now let's look at some examples of using the filter function so in this example we want to identify students who have a grade of 91 or greater so that would include Deshae and Devin and not include Felicia so how might we use the filter method to do this well first let's create a filter function so filter 91 or above and this filter function is going to take in a student and then it's going to look at their grade so student.grade and if the grade is greater than or equal to 91 then we're going to keep them so we do that by returning true otherwise we're going to return false great so now that we have our filter function we can go ahead and filter the students using it so we can create a new array called top students and we can call students.filter and pass in filter above function and so now this will create an array of all of our top students and that array should contain Deshae and Devin so if we go ahead and log this top students array it's going to contain these top 2 objects we get that result as expected so now let's switch over to the slides and we'll talk about the reduce function and how it's also a very very useful function in JavaScript okay so let's switch back over to the slides so another function that's kind of straight forward is this reduction function and the reduce function is unique in that it actually outputs a single value and so the kind of key idea here with reduce is that it's going to take in 2 parameters and apply that function and it's going to pass the result again to that same function with the next value in the array and then it will take that result to pass it to that function with the next value in that array and it will reduce it all the way down to a single value so a couple of key things here it takes 2 parameters and the result is stored in the first parameter so here the result is going to be stored so let's look at a kind of practical example of this so say this function was some function called sum so it would take 2 parameters d and 1 it would compute d plus 1 and then the result would update sum to be d plus 1 so the next time it would be 2 plus sum which happened to be d plus 1 then it would produce d plus 1 plus 2 that would be the sum variable that pops out here and then we would do d plus 1 plus 2 which was the sum from 3 plus 1 plus 3 to get our final result which is the single value which is the sum of all of these and the default value that must be passed into the reduced function so here it would start off with 0 and then you would get 6 as your sum so let's look at a reduced example and actually let's switch over to the live coding environment okay so let's look at a reduced example and in particular we're going to go ahead and generate that grades array again and then we're going to reduce that grades array and calculate the average so we can generate the grades array by going to our students and then mapping and in our arrow function we're going to take student and we're going to do an arrow function of student grade and so this gets us all our grades and then we could do a reduction so the sum is going to be well first let's write our reducer function so our reducer function is going to be the function we're going to call it reducer the function is going to take in two values it's going to take in our sum it's our first parameter, this is going to be the one we accumulate and then the current grade that we're considering and then it's simply going to return sum plus equals the grade right so that's our reducer and then we can call on our grades to get the sum okay grades and reduce and we can pass in our reducer and our default value is zero and then we can go ahead and console log plus sum so if we go ahead and run this we get our correct sum and we can just go ahead and divide that sum by the number of things in the array so students.lang and node and now our new sum is actually our average average is a 93 so let's go ahead now and make this a single line our function so we're going to have our first parameter and then grades and then we're just going to do sum plus equal grade oops and we have a small error here so I added bracket so there and we'll run it again and we get our average as expected so think about how you might um write a mapping function that would give you the student with the highest grade so let's go ahead and write our reducer so that's going to give us a student with the highest grade so it can be a function and we're going to take in some our current high score and our current student and then we're gonna see if the high score grade is larger and the score yes if the high score is greater than the current student's grade then we're going to return higher score otherwise the student your questions So that's going to be our new high score. So we're going to return student. So there's our reducer. So now we can go in and pass our default of zero. And we'll run our reducer. And we'll do this. And so we expect that our high score here is going to be mark. So instead of average, we're not going to divide by the student link. We're just going to call our reducer. And it's not going to be on grades. We're going to do it on student because that's a student array that we want to reduce. And then our results going to be our high score. And then we can go ahead and run this. And we get an error that said student is not defined. So it's because we need to do it on the students array. So I'll clear this. Very fun. So here we're getting the lowest score. So there's a small error. So if the high scores grade was greater and the students grade, then we would return the high score. Otherwise we'd return the students. So pause the video and see if you can think about what's the error here. So here we're processing the students array. And it's an object. So dot grade is not a property of that object. This is going to come back as undefined. What we need to do is we need to be looking at this student value. And so here we make this adjustment and we rerun it. We get our high scoring student.