Video summary
This JavaScript tutorial provides a comprehensive overview of fundamental programming concepts essential for developers, beginning with variables, loops, and data types while highlighting unique language behaviors like optional semicolons and dynamic typing. The course distinguishes between `var`, which creates global scope variables that persist after loop execution, and `let` or `const`, which define local scopes to prevent such leakage; it also clarifies the critical differences between loose equality (`==`) with type coercion and strict equality (`===`). Beyond basic syntax, the video explores functions as first-class objects capable of being assigned to variables, introduces concise arrow function notation for single-line expressions, and explains how nested structures utilize ternary operators. The discussion extends to object manipulation through dot or bracket notation, noting that properties can be added dynamically but accessing non-existent ones returns `undefined`, whereas attempting to access a property on an undefined value triggers an error.
As the tutorial progresses into asynchronous programming, it addresses the challenges of network requests using callbacks with libraries like `request`, illustrating how code following an async operation executes immediately unless managed by handlers that can lead to "callback hell." To solve this complexity, Promises are introduced as objects that transition from a pending state to either fulfilled or rejected, allowing developers to chain operations cleanly. The `.then()` method is explained for handling successful resolutions and errors via optional catch blocks, with the important caveat that once a promise resolves or rejects in a chain, subsequent handlers are skipped unless new promises are created sequentially. Advanced utility methods like `Promise.all` are also covered, demonstrating how they aggregate multiple asynchronous operations into a single result array while rejecting immediately upon the first failure to ensure robust error handling across parallel tasks.
The final segment of the instruction focuses on essential Array methods that streamline data processing through concise arrow functions and functional programming patterns. The `map()` method is shown transforming every element in an array simultaneously, such as extracting or scaling grades into a new dataset without mutating the original collection. Complementing this, `filter()` allows developers to isolate specific elements by applying conditions where only those meeting criteria are retained, effectively creating subsets based on logic like identifying students with high scores. The tutorial concludes with the powerful `reduce()` method, which iterates through an array while accumulating a single final value from two parameters—the current result and the next item—enabling complex calculations like summing numbers or finding maximum values to collapse entire collections into meaningful summaries for averages or statistical analysis.
Read the full video transcript
let's begin by looking at how to declare
variables in JavaScript
to declare a variable in JavaScript we
specified its name
and assign it a value in this case the
string Daniel
we can print a variable using
console.lock so we'll type console DOT
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 our 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 for 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
will 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 of
our 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 use 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 well 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 or 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 a string as or 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 typo check 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 these 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 a type object
now let's talk about some syntax that
you haven't 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 5 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
Tech version 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 this 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 conversion for
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 our 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 as 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 Supply 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
1 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
also has two parameters last an increase
increased
and also uses the return keyword to
specify what's returned from the
function
foreign
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 percent
so our result should be 0.77 so let's go
ahead
clear the console and run to our program
great we get 0.77 as expected
yeah
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 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 could
remove that
here
and when we do that we've created an
anonymous function in Java Script
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 special function syntax called
error functions that JavaScript supports
has brackets
and with any brackets and I'll close all
of the parameters within it and then
there's special errors to the expression
to an expression this is the body of the
function and then because it's a first
class object again we can assign this
error function to in this case the
variable funk
here has the function keyword
then some parameters
foreign
statement here here notice there's no
return it's only comprised of one line
the r function will just return the
results
whatever expression here is on that line
now let's switch over to live coding
environment and look at some examples
let's create an error function that
multiplies two numbers so we'll start
with our brackets and then our two
parameters we'll call them A and B and
then we'll do our R function which is
just the equal followed by the greater
than sign okay times and do a times B
and then great there we have our error
function so we can assign it to some
variable
so we'll do our equal operator and then
we could call this variable multiply but
before we do that let's specify the let
keyword
so now we have a full error function
it's optional and remember that the let
keyword is optional and so if you remove
it all variables are just assigned the
let keywords defaults to the left
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 then we'll assign
it to
function the same it's an anonymous
function and we'll take in two
parameters A and B and then we'll return
a times B times B so the r 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 something so
now let's look at an example of calling
the r function so we'll do console log
and then multiply and let's name the
second function multiply two so we'll
call multiply and we'll Supply two
parameters in this case two and four two
and four so let's go ahead and run this
should be so we'll do node and the name
of our file intro.js
and we get eight as expected expected
okay let's write another arrow function
let's create so this error function that
we'll write
will take a parameter and compute its
Square
and to be more efficient we'll just use
the multiply function that we wrote so
let's go ahead and make some space and
ideally we'd like to land or multiple
output or opening brackets followed by a
parameter in this case we'll call that
parameter a great things if we create an
error function we need a parameter and
one of the great things with error
functions is if you only have a single
parameter you don't need the brackets so
then we can have our error function and
then we can call multiply
a comma a our parameter 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
foreign
so now let's call our Square function so
we'll call square and then we'll pass in
our single parameter by saying square a
and we'll select the value here for a so
we'll say four four and now let's go
ahead and run this program
this should print out so we'll clear the
console
and then run our file node
intro.js
and so here we get 16. great as expected
16.
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 error function that uses
multiple lines our function has multiple
lines so this error function that we'll
write we'll take in two numbers and then
Show an example of this return so the
number that's bigger so let's go ahead
and use our our function syntax we'll
take into parameters and here we'll use
curly braces to denote that our error
function is going to be more than one
line so we need to include these
brackets here 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
notice that because our error 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 here bigger
great so now let's go ahead and run this
code to see if we have any errors so to
your node intro.js
great uh no errors so now let's go ahead
and call the bigger function so we'll do
console log
ger bigger and we'll pass into
parameters here we'll pick two numbers
say two and six we expect to get six out
here so now let's run this and if our
function is working is expected it
should return six
function right we get six returned so as
expected see if we could write
sure 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 use the ternary
operator as a hint you could do this if
you use the ternary operator so go ahead
and pause the video great
let's get a cleaner let's start looking
at some solutions so here we'll have two
parameters A and B followed by our Arrow
function just like before
and then we could return 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 turning operator
this is true and if a is greater than or
equal to B then we'll return a otherwise
we'll return B then we can see and then
we can assign this to or bigger variable
function
so if we go ahead and run this
we'll get six like we did before but we
can still make this shorter right here
we have a single return and so we can
compress this
down to a single line yes we can so
pause the video and see if you can do
this since this is powerful so here will
remove our curly braces
I'll remove our return statement because
we're just doing a single line so we
don't need it and now we have or one
line version of or bigger function we
can simply do this so let's go ahead and
run this to make sure that we don't have
any errors so we'll go down and we'll
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 the closed
curly brace represents the end of the
object notice this object doesn't
contain any name or a 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 Graham
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 Graham
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 Jon 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 but
not in 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 access 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
closed heart 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 node.objects 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 dot student that
gets us to the student property dot name
that gets us to the nested property
inside of the student object
let's go ahead and run this
and we get Jon 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 seashore 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 dot salary dot
raise here we're going to get an error
because raise is not a property of the
type undefined
so we can't read the property raise 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 signing Daniel G
Graham as the new value to the name
property
we can also use double quotes or single
quotes interchangeably 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 G Graham PhD as the
new value
and there we have it Daniel G Graham 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 it will 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 Eva
and then we'll look at the
teacher.proposed 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 this great
autocomplete 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
accessing 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 dot Rank and now we can
assign it a value of one
let's go ahead now 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 one
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 uh welcome back to another lecture
in this lecture we're going to talk
about web apis
and web requests and we'll give a 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 let's start digging
it
so API stands for application
programming interface and it's the way a
client like a mobile app web app or a
terminal application like curl will
compute communicate with a web server
and that web server will be running a
web API
and so these web apis are typically
implemented using Frameworks model view
controller Frameworks like Django or
asp.net but they're also serverless
implementations like the one that Amazon
uses at Amazon AWS uses
we'll look at Google's serverless
implementation in the form of cloud
functions and 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 post requests but I want to measure
mention what a guest 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 in 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
foreign
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 the 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 CAF facts so cats
must have fat in their diet because they
don't produce it on on their own and
that's 76 and if we
refresh this we'll get another cat fact
say the relative relative to its body
size the clouded leopard has the biggest
canines of all animals
uh it's dagger-like teeth
can be as long as 1.8 inches so great
that's another cat fact
so 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
yeah
so let's do a little deeper dive into
this cat fact API and in particular
let's look at the response and request
so curl is a command
um 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 cat facts the
cat fact AI endpoint we would 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's 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 cat fact will
be included here so this is where the
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 is normally a get
request this is just kind of an example
an example a 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 uh let's
um 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 uh with this
remember to install the
request
MPI module that allows you to do
requests
okay uh so we're going to switch over to
our live coding session now
okay
um let's go ahead and install
requests
2.x.x this will get us the most recent
version
great we got a successful installation
with zero vulnerabilities which is good
um 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 and exporting uh later but
this require keyword let's just use the
request npm Library
we're going to store 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 cat fact
and our app we'll have some URL
Dot
India forward flash forward slash fact
um and then we'll maybe we'll also store
the cat factors across the part of this
object as well so cat fact and we'll
start it off as black
okay
so let's go ahead and make a request so
the way we make a request is by saying
requests
and then we pass in a 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 that our
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 two parameters
error if 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's an error
right we will want to just console log
that error
if not
there's no error
then we're going to go ahead and set
app.cadfact
to the response dot body
so remember responses had headers and
body right and the body was where the
data was stored and so we want to go
ahead and take the body part of the
response
foreign
so here now if we go to the bottom here
and we console log
print
cat fact
plus and Dot cat fact
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'll pass in the response and
then that responds if there's no error
we'll then get updated to the object
app.cat fact and then we would progress
here and then print out cat fact 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 cat fact is empty it
will print for print cat fact we will
get nothing
let's go ahead and clear this and clean
clean this up a bit
so save it and we'll run this so
promises.js
and it said print cat fact but we got
nothing
so the question is well how do we fix
this right
um
what do we do
well uh we could go ahead and print the
cat fact out in here
right so
we could go ahead and
um
print
or cat fact so we're just gonna go
console
console.log
or app
.confact
so now we'll print
something out here that says
um in Handler
print
um
traffic
so I have to go ahead and run this
no it promises
well first we're not the print cat fact
and then we'll print a pin Handler and
then our Json for the cat fact
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 we're just
going to extract the fact from that
first body
and then we'll go ahead and we'll print
out that new object so now we should
just get the Json object without the
link so
I'll clear this and then we'll do node
bonuses
.js
and there we go in Handler print cat
fact but notice it printed this cat fact
first and then once the request was
ready then it printed the second Cafe
so
you know that's that's okay so we just
have to include our prints and updates
in or Handler functions
but uh this might not always be the case
so let's switch back over to the slides
and consider a more involved example
okay uh 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
um or 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 also buy their credentials
which is just a fancy way of saying
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 via a
post request to some authorization
server
and then that authorization server will
return an access token or
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 I returned but sometimes a new
access token will be returned so the
idea is that you can create a really
secure
off server with a bunch of things on
logging and checking for credentials and
then your research servers will just
need to have these access tokens
but both of the services have access to
the same back-end 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
um 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 login example with curl
and here I'm passing in the Json with
the credentials and so in this case the
credentials are Peter
and their password uh City Slicker and
I'm using this API endpoint here called
request
and uh this is kind of a an open API
that lets you kind of test
Authentication
um so if you're interested in
um 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 uh let's get 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 a
collection of things
um one of the endpoints that it provides
is this post login successful endpoint
so if you click on this it will show you
what JavaScript the API is expecting or
which Json object I'm sorry the API is
expecting and what it will return and so
here this will return uh this is
expecting uh email and password and if
the email and password match this then
it will return the token
and produce a 420
um
code
so this is just 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 uh switch back over and
write some JavaScript to access this API
and read the Json values that we get
back
okay
so one way of
um
getting a external library in JavaScript
that you could use this require syntax
so I can say require request
foreign
and we're going to go ahead and stir
that in our
request variable
so you can princess that class
I'm going to make this a constant
and then we'll create our app namespace
and we'll have something for the URL
GPS
to rest in API login
and then a token
and this token will set it after
something that's empty
and then one of the things that we could
do is along with this request is we can
pass it some options so
say Okay request
and we're going to pass through some
options we'll fill this out and then
we're going to need a function to handle
a request so handle
candle requests
so what are these options that you can
pass well options as an object that's
what the request Library requires and
this object for contain things like the
URL or URI
so I have that URL we'll use that
and the type of request
um that we're gonna get so post uh posts
there are two types of requests post and
get
um post requests post the content inside
of
the packet and 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
um
content from before and I'll clear the
screen here
um
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 and
write or Handler so
I'm gonna 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 uh 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 gonna press the risk to get
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 gonna
go ahead and console.log
in Handler
the token
plus the API app token
right
and so now this request will go ahead
and fire and I will make this smaller so
we can see all the options here
and so uh towards the end
right 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 uh 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 uh other services or
get some resources so we have a choice
we can't put a handle request object
here
right because we won't have the token at
that time
instead we could kind of Nest the
Handler requested here so I
if we wanted to do this we could do
another handle requests right
and I just want to preface this by
saying this is kind of bad practice
right 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 a request too
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
um
and then we would go ahead and inside of
this we would then fire or request
and then with
you know or 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 you know
another request in here and so 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 uh 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 we promise being
declared
and it takes its parameter is a function
and this function
um
needs to have two
uh 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 promise as kind
of a wrapper for these functions
great
in particular when the resolver reject
methods are called they set some
internal State Properties associated
with
the promise
so uh 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
contains a value that was actually
passed as a parameter if 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 from 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 states of the
promise to fulfilled
and the value
of that was passed to this resolve
function would then get updated into the
results property of that promise
and if a promise if the executor the
asynchronous executive 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 results
to be an error
and that error value would be would
correspond to the error value that was
called called by the reject function
so let's switch back over to the live
coding environment and uh start looking
at some examples of these promises
great uh 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 uh
using network requests to mimic long
operations that take a long time we'll
just use a timer so I'll just have to
set timeout value here
and
I'll pass in I'll just do a console log
so it's an error function which is a
console log and I'll just say done and
set timeout as far as after a 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 rerun this
no promises it'll take five seconds
before it prints out done
so hopefully soon
there we go
so uh since we're using this as our
asynchronous operation our operation is
going to take a long time over the
network
let's go ahead and wrap it in a promise
so we'll see this is some new promise
here's our operation it's going to take
a long time
so I have some function
uh it takes in two parameters resolve
and reject and these two parameters are
based on
are defined by the JavaScript engine so
the asynchronous function must take
these two parameters in as uh 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
to 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
should be done
and here in a reject case we normally
want to make this an error so the result
would be
so uh now that we've had this kind of
wrapper for a promise
um
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 we'll just 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
I'll just say function here result
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 can 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 we could say
resolve here
and resolve let's see great
we got something
and then
once that promise is complete once this
resolve is fired after the timeout then
we can go ahead here and we could
console.log
in consumer
and then the result
so I can go ahead here and I will run
this for you
and after five seconds we should
print out great
so in consumer
uh great that was misspelled we got
something
so what happened here was the result was
fired that changed the internal state
after the internal state was updated
the promise then method is executed
and the results
here is the value of
the results of internal property which
was set to great we got something
so pause the video
um and think about this
and so we could make this a lot simpler
by using Arrow functions
okay we have a one line Arrow function
this is
so this is
still valid
and then I'll just rerun this and I'll
make this a little shorter so we get the
answer more quickly
foreign
and another way that you uh
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's 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 resolve
here we called a reject
and I passed in something like
here is an error
the then on the on the promise would
fire
and
um
we would get in consumer here is an
error
clear this and then we can we run this
to c
foreign great
so a couple of things to mention is that
if we have two things and accept and a
reject
and the resolve fires before the reject
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
great
um and so we expect here because this
resolve function is going to fire first
that will get in consumer no error
everything is great
so in consumer no error everything is
great
excellent
but if this did not fire first
and instead the rejectified we would get
in consumer here is an error
we can have multiple results and rejects
so for example if we had just resolved
stop now
we would get in-consumer stop now
so
and consumers stop now notice none of
these other things fired
so uh next time we're gonna
take a look at
um 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 a race where
we'll talk about some functions that
will help you write clean air JavaScript
code
namely map reduce and filter
okay so let's stick it so what is this
problem Sol syntax
so the promise.all method returns a
single promise that resolves when all
the promises passes an interval so this
could be an array have resolved or when
the interval contains no promises
this uh promise will also reject if any
of the promises
um
in that array reject for some reason and
in particular I will take the first uh
promise that rejects so just to say that
simply air 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
okay so let's switch over to some live
coding
okay so let's look at a live coding
example of using this new chromosol
syntax so let's create three promises
and we'll make them globally available
so promised our resolve and we'll just
make this first one resolve a three
then we'll make something that just has
a value that returns immediately so just
one three three seven
and then we'll make a third promise that
will actually resolve
Let's do let's do this
so we'll make a third promise that
resolves
uh after some time so we'll pass in an
error function with resolve and reject
and then we'll have our set timeout
tapping
foreign
and we'll have that fire after
100 milliseconds
but then we can say promise dot 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 let's start 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 our values and then we'll make this
an error function
and then I'll just go ahead and
console.log
values so this should print out three
one three three seven and one hundred
so let's go ahead and run this
very fun
oh
made a mistake here with my spelling
sort of been values not value clearance
and I'll save it and then we'll run this
one
it's great three
one three seven and two
okay
so I'll save this and
we'll uh switch over now to slides and
talk a little bit about arrays in
JavaScript
so a raise in JavaScript are a little
special
um
and in particular the root object for
array supports a couple cool things
what's these methods map reduce and
filter
and they're particularly useful when
filtering through data or trying to
um
structure data in a way that makes it
easy to present and they're particularly
interesting when used with arrow
functions
so let's switch back over to a live
coding section and we'll look through
some examples of where these mapreduce
and filter functions actually help us to
write cleaner more readable code
okay so let's go ahead and create a new
array
I'll close this Explorer to give us some
more screen space so let's create an
array called students in this array we
create it with this bracket syntax
can contain anything because JavaScript
is dynamically Tagged so we'll make this
array contain a collection of objects so
the first student object has a grade uh
the student had 93 name
J
oops
and then another object
um maybe we'll do this on multiple lanes
for readability
and then the student had a grade of 96.
and a name Devin
and then a final student with grade
of 19.
and name of
Alicia
and so that's our acid array and so say
we wanted to go ahead and get all of the
grades
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
um the screen is array will go through
and we'll say
um
start off with some I started zero it's
a little for Loop uh less than the
students
dot length
I plus plus
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 and index I get
the grade value
so
this might be one way and I'll just
console log the grades here so we can
see this
we'll run this so this is one way of
kind of getting
all of the grades
um
from or array and so here is our grades
but there is a different approach
um friction 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 math concept to get the grades
from our new student
okay so let's talk a little bit about
this new concept of math
so what JavaScript allows
is for you to apply an individual
function
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
arrow function it 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 1
times 1 is just one two times two will
be four three times three will be 9 and
then 4 times 4 will be 16.
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 it's going to be a
function that takes in a student object
and simply returns
to grade
student.grade
and now we can create a new grades array
by saying student
dot 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
if we go ahead and clear this
and then we do node create fun
yes
um we get a reference error because it
should be students with a capital S so
fix that
um
great we get nine three nine six nine
zero which is what we expected
so we can also make this more compressed
right 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 clear this and run this again
and we get the results as expected and
sometimes you'll see an arrow function
used
so it's common to use Arrow functions
with this map syntax and because it's
only returning one line we just need a
one line Arrow 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
it's clear and then 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 students.grade parameters
and if we wanted to scale those grades
say multiplied it by 1.1 so give
everybody a one percent bump
we could do it that way and so
there we go here's our grades with the
one percent
okay so let's look at another function
that's available to us called filter so
let's switch back to the slides and look
at this filter function
okay so let's talk a little bit about
the filter function
so here's 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
this two value it's also not included
and that's because our filter function
here is X greater than 2. so 1 isn't
greater than two two isn't greater than
2 but 3 is so its result is included in
the 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
uh
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 Deshay and Devin
and not include Felicia
so how might we use the uh 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 into students
and then it's going to look at their
grade so students
dot 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
dot filter
and pass in our filter above function
and so now this will create an array of
all of our top students and that
duration contained the shade and Devin
so if we go ahead and log this top
students array it's going to contain
these top two objects
so
great uh we get uh that result as
expected
so now let's uh switch over to the
slides and we'll talk about the reduce
function
um 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
straightforward is this reduction
function
and the reduce function
um is unique in that it actually outputs
a single value
and so the kind of key idea here with
with reduces that it's going to take in
two parameters and apply that function
and it's going to pass the results again
to that same function with the next
value in the array and then I 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 key things here
takes two parameters
and the relative result is stored in the
print in the first parameter so here
that's where the results is going to
restart
so let's look at a kind of practical
example of this so say this function was
some function called sum so I would take
two parameters D and one it would
compute D plus one and then the result
would update sum to be D plus one so the
next time it would be 2 plus sum which
happened to be D plus one
then it would produce D plus one plus
two that would be the sum variable that
pops out here
and then we would do D plus one plus two
which was the sum from previous one plus
three to get our final result which is
the single value which is the sum of all
of these
and the default values of value that
must be passed into the reduced function
so here it would start off with zero 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 uh let's uh look at
A reduced example and in particular
let's 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 our our function we're going to take
student
and we're going to do our function of
student.grade
um
and so this gets us all our grades and
then we could do a reduction on our
grades so the sum is going to be
well first let's write our reducer
function so a reducer function is going
to be
function we're going to call it reducer
from your function I'm just going to
take in two values it's going to take in
our sum sorry 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
plus equals the grade
right
and so that's our reducer
and then we can call on our grades to
get the sum we could create
and Dot reduce
and we can pass in our reducer and our
default value of zero
and then we can go ahead and console log
press sum
so if we go and run this
we get our correct sum and then we can
just go ahead and divide that sum by the
number of things in the array so the
students.length
foreign
node and now our new sum is actually our
average
yes
the average is a 93.
so uh let's go ahead now and make this a
single line error function
so we're going to have our first
parameter
um
and then grades grades and then we're
just going to do
sum plus equal grade
dude every time
oops and
we have a small error here so I added
bracket fix that so there and we'll run
it again
and nope we get our averages expected
foreign
write a mapping function that would give
you the student with the highest grade
so let's go ahead and write for a
reducer
so we want to reduce her it'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 scorer
and our score and our current student
and then we're going to see if the high
score
dot grade is larger than this or if yes
if the high score is created is larger
than the current student's grade
then we're going to return
the high score
otherwise
student
otherwise we're going to return the
student's grade
otherwise we're going to return the
current student sorry
so that's going to be our new high score
so we're going to return
um
so there's our reducer
so now we can go and pass our default of
zero and we'll run our reducer
there we go for this and so we expect
that our score here is going to be mark
so instead of average we're not going to
divide by the student length right 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 the
student array that we want to reduce and
then our result is going to be our high
score
okay
here and then we can go ahead and run
this node erase one
and we get an error that says student is
not defined so because we need to do it
on the students array
so I'll clear this
movie node very fun
so here we're getting the lowest score
so there's a small error so if the high
score is grade
was greater than the student's grade
then we would return the high score
otherwise we'd return the student
so pause the video and see if you can
think about what's the error here
so uh here we're processing the students
uh array and it's an object so dot grade
is not a property of that object so 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
if we make the suggestion and we rerun
it
we get our high scoring student