Transcripts
1. Introduction: Welcome to my course, JavaScript interview questions
with practical tasks. In this course, we
will solve together 59 most popular
interview questions that they got or was asked
in the last ten years, and they will cover the whole
knowledge of JavaScript. This course is fully focused
on the coordinate tasks. This is why I highly
recommend you to try and implement every
single task by yourself. First, after this, we will
implement it together in different ways for different
level of knowledge. By the end of this course, you will be much
better prepared for your JavaScript
interview to get a job. Who am I? My name is
Alexander cohered hint, and I'm a web developer, was more than ten
years of experience. It as well as a professional
instructor with various courses about
web technologies. I did my best to put
all my knowledge inside this course and I wanted
to share it with you. So welcome on board
and let's get started.
2. Types of interviews: There are three
different types of interviews that you might get. First of all, it is
theoretical parent. You are just been
asked some questions regarding your work and
experience and so on. This is normal type
of interview for more advanced
developers where they already have a lot of years of experience because the
interviewer understands, okay, this guy was working
in web development, for example, with
JavaScript last five years, which actually means he has
enough knowledge and it doesn't make any sense to
check his programming skills. The second popular type of interview is
coordinate interview. And actually I would say this is the most popular
type of interview. People often mixed together theoretical interview
with coding challenges, which actually means
you are getting some theoretical questions and then you must code something. Most often you are just using pen and paper and non-computer. In this course, we
will solve together 59 different JavaScript
challenges that you can get. These challenges are covered in almost all JavaScript that he will meet on the interviews. And the last type of interview is project check-in interview. Typically interviewer
wanted to see your code. So if you have
something to show, it is much easier
for you because you should not answer
just random questions, but you can talk
about your project, about your code and so on. Which actually means I
highly recommend you for the interview to implement some project because
first of all, you will have something to
show to the interviewer. And secondly, you will
have something to talk about that
you at least know.
3. Interview and Work Are Completely Different Things: So typically to get a job, you must pass an interview. And this is how it is working
in almost all companies. But the main problem with that, your interview is not always
related to your work, which actually means some of
the interview you might be asked difficult, not
real-world questions, but you must answer
them to get a job, but you will never
use this knowledge later in your everyday work. Here is the problem. There are some similarities
between introduce and work, but actually they are different. And in the perfect world, your interview must be a mirror of your real work
in the company. But unfortunately, it is
not always like this. This is why you must know both. You must know how to pass the interview and you
must know how to work. In this course, most
of the challenges are completely real
knowledge that you must know and that you need both in your interview and in
the everyday life. But he also included
in this course some questions which are not related to your
everyday programming, but you need to know them
just for your introduce.
4. Mapping Users to Get Usernames: The first task that we want to look at is sounding like this. You need to write
a code to get rid of names from an array of users. And as you can see here,
we have an array of users. And actually, it is just
an array of objects. We see this name and
this active property. And actually, this is a
relatively easy task, but it is really nice
to start the interview. And experienced
interviewers will know that you are under stress, which actually means
you must receive several easy exercises just so you are relaxing
a little bit and you can be more focused
and more productive. And actually even an
easy exercise can tell interview quite a lot what
code style you are using, how do you name your variables and how you are
writing your code so he can understand on
what level you are and what questions
he needs to ask you? So now I highly
recommend you to post this video and try to
implement it by yourself. If you just want
to follow along, then let's code this. And actually there are
several ways to implement it. Normally beginners
will start with for loop because it is the easiest
approach what they know. For example, here
after our user three, we can write here for loop. So we have here for for let index from zero
to user slant. So here we have a smaller than user length and here we
have eight plus plus. Now inside our for loop, we want to access
every single name and push it in some glory. This is why before we
want to create an array, let's name it names and it
will be an empty array. Now inside of a for
loop we can write names to output
and here inside of access in our users with I saw this is our
current user dot name. In this case we are put an online name of this
user in this right. And after our for
loop we can just console.log our in your names
and check it and browse it. I am related in the page
and as you can see, our result is Chegg. John Mike This is exactly what we need to implement and yes, we solved our task. And if you are a beginner, this solution is totally fine. But you can do better
because every single time when you try to
better code an interview, you show that you're a better
developer. This is why. Let's come and told this
code and try again. So what we can use
here instead of for loop is for rich
function for our array. This is where here we can
simply write users dot for rich and inside we must
provide a callback function. What is more importantly, we get an access here
to every single use it and now inside of a
can do whatever we want. And as you can see here, we don't have any indexes and our code is looking much better. So what we want to do here is exactly the same stuff
like we did previously. We created here in the
real names and now inside our for each loop we want to push inside our names, our user dot name. And as you can see in
comparison to our old code, this code is much
easier to read. Let's some common here our console.log and check
if it's working. As you can see, we are getting
exactly the same result. So this is your level
two of write in code, but actually the
best way to solve this task is to use
additional map function. And actually it will make
your code the simplest just because you're using the right tool for
the right task. In this case here, we can write that we want to
get back our names array and here we want to loop through our users with
the map function. And if you don't know what
the map is doing well, looping through
every single element inside our array and
will return some of your data for
every single element in our keys instead
of our object, we want to return a single name. This is where? Here we can
write that we have a user and we want to return
his user dot name. Let's check if it's working. As you can see in browser, we are getting exactly
the same output. But this is the best variant for this task and it
shows that you know, what you are doing for solution is almost
always low level, which means you exactly need to implement
what you are doing. In this case here, we need
to say that we are pushing elements to our new array names. And also what you can see here, we created names array
before using for loop, which actually
means our logic and our additional variable don't
have anything together. In our case here we're
writing the result directly to our new
variable names. So you successfully solved this task and now you're
getting the next one. We need to get back
on active users, which means our first
point here is valid, but this must be
all active users. And actually we could use any method that we want
here to solve this. For example, we
could use here for loop and simpler write
inside than if condition. And we can check
here if our user is active and if this
property is true, then inside we want to push our element to our.
And you are right. And as you can see in browser, we're getting here
only two users because our last
user is inactive. This is totally fine, but we have here two problems. First of all, our
code is low level. And secondly, we mixing
here logic together with filters and elements
and mapping them. And this is bad because when
your code is more complex, then it is more
difficult to split it. And actually the
solution with for each will be exactly the same. But let's look in the
solution of this map. Actually, what we
want to do here. We want, first of all, to filter our array and
get on the active users. And after that we want to apply our map so we can
right here dot filter. And we have exactly the same
logic we have here access to our user and we must return here a predicate
with true or false. In our case it will be
user dot is active, so if our user is active then we will leave
it inside our array. In either case, we
will throw it away and after this work call in
our map to map names. What is important in
this code here when not mixing merkin and
filtering together, which means it is easier
to support such code. Now we have another task. You are getting
certain users by age descending and of course
to first rules also place. Which means we, first of all, must sort out Ray
and then we need to filter our rate
and map our names. And as you can see here now, additionally, we are
getting age property. This is our property by
which we will sort our rate. And actually, in JavaScript, if you want to search something, you must use only a single
JavaScript function and it is not sort. You can't really do
it differently if you don't know how a resort
function is working. You can jump to developers
mozilla orig to this URL and here is a
real prototype site. The main idea is that
are colin search function on our
array and inside we pass a function comparator
with A and B and in our case it will
be first user and second user and then second
user and third user, which means it is comparing
elements one by one. And here we must
return something. As you can see inside we
can return minus one. If A is less than B A, then we will audit. Now we must return of
one if A is greater than B and were returning
zero if they're equal. And this is exactly
what we must do here. So in all the three cases, we must write the same code, but in the first two variants
it will be kind of fugly because actually we must do the sorting before our code here. So let's and comment
our code here and we want to apply
certain and here we want to write user stored sort and we are getting
here our comparator. So we have here
user one and user two and we want to
compare them by age. This is why we can write here. User one dot age is less
than the user to that age. And if it is true
then here we have one two ternary operator we
want to return minus one. In another case we
want to return one. Let's save this and
check if it's working. I'm jumping to browser to load the page and we're
getting John and check. Let's check the salt on the top. John is 18 and Jack is 20, which means with sorted
our data correctly but in descending order as you can see here from must sorted
in descending order, which means we want to
swap here not minus one, but one, and here
will be minus one. Let's check the
result we're getting, first of all, Jack
and then John. And this is correct
sorting also you must remember that sort operation in JavaScript mutates and array. This is way here with the regular code sort and we
didn't assign our result to some property because
it just mutates our users array and then we are doing other
stuff with it. But as you can see
here, this code is really separated from our full loop because we must do it before our operations inside. Now let's comment
this code and try to use it with our
map and filter. And here it is much easier to do because we simply
want here after our users to call dot sort and after this to
call filter and map. As you can see here,
when I am commented, it is looking really pretty. We have here our users
were doing our sorting. After this we do our
filtering and then mapping. And first of all, this code
is much easier to read. You have here chaining
and you are getting your result in this
one single property. Also, it is important
that we are not mixing different operations. First word to insert, then filter and then map. And if we need to
adjust one of them, we don't need to change
the logic of another one. Let's check if it's
working and flooding the page and we are getting
exactly the same result. So as you can see, you can solve even the simple task
in different ways. If you want to show
on the interview that you're an
advanced developer, you must use a specific tool
for your specific task. This is where the
chain of thought, mapping and filter here is much better than using for loop.
5. Difference between null and undefined: You might get a
question like this. What will do logged in the first example and
in the second example? To answer shear correctly, you must understand
the difference between null and undefined it
inside JavaScript. As you can see here,
we have two examples. First example, we didn't assign
anything to our variable, which means this variable
is not defined yet. This is why when here we
console log this variable, it will be equal, undefined it here
after this we're console login the type
of this variable, the name of the title also be undefined it here we
have our second example. We're inside our variable two
were assigned null value. Here we're console login var2. And this you can understand
here we have our value. Now, this is what we
will see on the screen. But type of variable two will be an object because there
is no such type as now, this is why the type of variable is an object. Let's
check this out. I'm reloading the page and we're getting here undefined it. This is our variable one here. So the value of it is undefined. It the type of undefined
it is undefined as string. Now after this work console log and work through
here we're getting now this is our value and type
of variable is an object. You really must distinguish in JavaScript between
null and undefined. It undefined. It means that the
variable is declared, but the value is not assigned
yet inside this variable. This is exactly what we
have here on line three. And now in JavaScript
is an assignment value, which means it's a value that we can assign inside the variable. In our case here we're signing
now inside variable to. And even if you answered
correctly here, interviewer might ask you, but what is really
the difference between now and then define it when we need to use now and when we need to
use undefined it. And actually it is a tricky one because normally in
normal languages, we have only a single property, which means that the
venerable does not exist. For example, New
button JavaScript. We have two different things. We have undefined
it and we have now. And actually it really depends
on your code style and your team because you can use both of them inside project. But for example, I
prefer to always use online and try to have as little undefined
and so as possible. But obviously, if
you are trying to find a value inside the array, you will get the
undefined it and not now because we
didn't find anything. So the answer here that it
is fine to use both of them. There is not really something
better in one or another.
6. Hoisting: You might be asked in the interview the
question like this, what will be console
logged here? And as you can see here,
we have console log full and then foo equals one. And actually this is
a typical question regarding hoisting. Hoisting error
means, it means that the declaration of your variable will bubble to the
top of the file. And this is how it works
in JavaScript when you are using var keyword or
function keyword. So the question is
what we will see here, we have here console log
f2 and f2 is a variable, but as you can see, it is not declared. And on the second line
we have foo equals one. Actually, we will
get here and narrow. Let's check this
out. I'm reloading the page and we're getting foo is not defined it by
this happening because yes, the first line which
is executed is console log and foo is not
defined inside of a file. This is why we have this error. So the correct answer here, we will get an error because
foo is not defined it. The main problem is here that typically you will
get some chances just to answer on the paper without any usage of computer. Because obviously
programmers are not using computers every day. This is why you can't
really test it in browser. And you need to understand how all this stuff is
working beforehand. After a correct transfer, you probably will be asked
something like this. The next question
then we'll be okay, we're console login here for, but after this we have
var foo equals two. And actually here that
the huge difference because then first
question we had here, f2 equals one, but we didn't have a creation of the variable. But here we have var2, which is actually a
creation of the variable. But you might think, okay, we were to happens
after console log, which means we will still
get an error that foo is not defined it because
Y2 happens later. But actually this is a wrong
answer because the main idea is that while declaration is bubbling to the
top of the file, which means it is exactly the same code like right in here, var foo, and here we're
just assigning f2 to tune. This is exactly the same code. This is how JavaScript
interprets this code. This is why if we
will open a browser, you can see that we're
getting undefined it, why it is happening, because actually here we have var foo and in this case we're f2 is undefined it because we didn't assign any
value after this, we have a console log for, we are getting undefined it. And only after this we're
assigning to incite form, which means it
won't be an error, it won't be true, it will be undefined. It. This process is called hoisting. If you answered correctly, you might get one more
question regarding hoisting. As you can see here,
is question three. We have here full equals three, then console log foo, and then var foo. And I think now you'll
know the answer. Yes, we have here Wherefore, and it bubbles to
the top of the file, which means actually this far fu is exactly like
it's written here, which means on the first
line we're defining full property on the next slide where sign-in foot or three. And after this work
console login form, which means it will
be equal three. And it doesn't
really matter that warfare is going at the end. It will be bubbled to the
top. Let's check this out. I'm reloading the page
and we're getting three and this is exactly
what we were waiting. You can get exactly
the same question, but not with words, but with function keyword, if you have somewhere in your code function and then
the name of your function, and then inside you're
right, in some logic, this specific definition
will bubble to the top, which actually means
it doesn't really matter in what line of
your code you are, right? And function foo, it will be the first line that will
be executed in JavaScript, which actually means if here
before I will call foo, it is totally fine. As you can see in browser, we're not getting any errors
because this foo function is bubbled to the top and it works exactly the same like var. And here is one more
important thing that you mastered
to your answer. You must mention that we
can use const and lead, and we don't have any
problems with them because both CONST and lead and
not bubbling at all. Which means if provide
here const a equals one, it won't bubble anywhere. If it is defined it
on the 17th line, then it will be existed
on the 17th flying, which means we don't have any
problems with Constant LED. And the way the JavaScript
interprets our code is exactly the same way code that we're seeing on the screen. So you can just say
that you are using CONST and lead in
every single project and you don't have
any problem with bubbling of the variable
or with hoisting.
7. Closures: This is for sure a
question that they hear on every single
JavaScript interview. This is why you must
understand water closures. As you can see here,
we have a task, create a counter function which has increment and get
valid functionality. And actually you might not
get it from this task, but this is a task regarding clauses because we must create a function where inside restore some value and we have
two public methods. This is how you typically
need to implement it. We want to create our, for example, private
counter function. And this is private because we're starting accounting side, which is not available outside. And actually this
is just a function. But if you hear on
interviews that you must or something
inside function, after you call this function, then you have a question
regarding closure. What we want to do here, we want for us to
create our counter. Let's name it count, and by default it will be 0. Now we must return
our public API, these two methods increment
and get fairly functionality. This is why we're
making here return and inside we want to
return two things. First of all, it is an
increment function. This is just a property where we're passing inside our value. And what we want to
do, we want to change this count that we
have on the top here. We're right in here,
count plus equal, and here is our value
that we want to increase. And actually it might
be that we want to increase it by
default, just by one. This is why it makes sense to pass here one, in this case, we can simply call increment and it will work out of the box. And the next method
will be here, getValue because we want
to get our count back. And actually here this is just a function which
will return our count. And the main idea is that
this is our public API. This is what is available inside this function
after we are calling it, let's check this out. Let's create here our counter
and we're colon here, our private counter function. And actually what
I want to do here, I want to console
log first of all, our counter dot getValue. This is a method to
get our counter. And secondly, we want
to call counter dot, and here is increment to increment R value and then counter once again
to check value. Once again, let's
check if it's working. I'm reloading the page,
we're getting 01. But the most interested
in the idea of what we have inside this
private counter, if we're right here, private counter, you can
see that this is a function and actually we don't have any access to this
property count. This property count in
this case is private. And given if I'm right
in here counter, you can see that we're getting
an object with two values, get value and increment, and we don't have any access to our counter property inside. This code is working, but it is really tricky and complex because
this is a closure. What does closure ever mean? Closure means that we
have accessed inside of a function to the outside scope, which actually means
here, for example, inside the increment
we're using count and we don't have a discount
inside this function. We have it outside here on the top and exactly the
same regarding get value. We have this counter
here on the top, not inside this function, which actually means collage or function has access
to all properties inside itself and all properties which were defined it before. Why it is important because they actually with this single liner, cons counter equals
private counter, we're creating a closure because
we're now counter exist. We have a closure and we have this reference to this counter. This is why every
single time when we're calling getValue and increment, it is working and it is referencing this
count on the top. And you might say, okay, but it is sounding like magic. I don't understand how it is
looking like in JavaScript. And this is where console
Directory can help us if we will write
inside console, not console log but
console directory. And inside I want
to pass a function. In our case it is countered getValue then
hidden here, enter. Here we don't see a body, but instead our
function is an object. And we're interested here in
part which is called scopes. And this is exactly
what we are interested about afterwards
opened here scopes, we have here a property closure, and this is exactly our closure, as you can see here, we have
closure private counter. Here, count equals one, which means exactly are we
have this lead count equals 0, and now it is inside closure. This is why it is available
for us inside JavaScript. And oldest questions regarding clauses I exactly the same. For example, you might
be asked the question, you need to create
a function which will store inside secret string, and we'll just return it when we call this
function again, it will look
something like this. For example, let's create
a function private secret. Here we don't pass
anything inside, but we want to do inside is
create our secret string. So let's just create a
secret and it equals four. So this secret is
exactly our closure. For it to be available outside, we must return here a function. We simply return
here a function, and this function
will return a secret. This means that
when we're creating outside a function
which we can name, for example, get secret, it must call here our
private secret function. The main idea is that private secret function
gives back a function. In this case, r gets
Secret is a function. And now we can console log hour gets secret and we just call it. And actually as you
can see him console, we're getting this
full screen back. This is why our secret string is actually a closure
and it is available outside after restore
this private secret inside the additional property. In this case, we're starting disclosure after our
function was executed. And closure is a super popular
pattern inside JavaScript. This is why you must know
how to use closures.
8. Currying: You might get a
question like this. Write a function which
helps to achieve multiply a and b and returns
product of a and B. And as you can see here, we have this strange notation. Multiply them a and B, not like two arguments, but this is the first
call of the function, and this is a second
color of the function. And actually if you are
getting such question, it means that you are going
in the direction of current. And current is a
special possibility in JavaScript to
carry a function. And then we can
call it like this. And actually here
we can implement this stuff with
super basic current. Let's try this out now. What I want to do, I want to
create multiply function. And here we're getting our a, so it will be number
one, for example. Here we want to return a function because as you
can see here on the top, we're calling on the
result of multiplying a, b, which means that we're multiplying master
return a function. So here we can write that we're getting a function
which will get B. This is number two, for example. And here inside we want to
multiply our num1 and num2. In this case, our second
function will deliver for us multiplication of
number one and number two. And this is how we can use it. We can write here console log. We want to call here, I'll multiply function and we're passing a for example two. And after this we're calling b. This is our second function
and we're passing in S3. Let's look in the browser. I'm reloading the page
and we're getting six, which means this
code is working. And actually you can write this multiply function
in better way. You can simply omit here returns and then it will be a
simple single liner. We have here multiply function and we're getting numb one here. Then we want to return
here a function, and we're getting here num2. And we want to multiply our
number one, multiplying num2. This is exactly the same logic, but it is reasoning
the single line. It, I will now come and
told the previous code. And let's check, as you can see, we're getting exactly
the same result, but this is not really current. If you solve such task, typically you will be asked, okay, but what did
you write here? What this mean? Why we need such
strange notation? And actually you
must tell that we're talking here regarding current, there is a next
question that you might get is create a
kind of function. And this is actually
a difficult question. And if you didn't
have any experience of current functions, then probably you won't unsafe. This is why here we
will look how we can create a kind of
function and why do we need them and actually carry functions work in exactly
like how I multiply here. So we can write in
browser for example, Kyrie, and this is our function. We must always pass inside the function that we
want to cover it. In this case, we
have, for example, a function with a, B, and C. So we have
three arguments and we want to just sum
a plus B plus C. The main point is that
the result of cardi is a function and let's
name it carried some. This is how we're using current, what we can do with
car at some later, we can write here our arguments. We have three arguments, how we want to, for example, we can write here 123, just like three
normal arguments. We can also call it with 123, which means we're
not getting a result until we're getting
three arguments. So for example, we have only
one argument here, one, then it will return the
partially applied function, which means we are
getting back a function. And then if we will call that function and
pass two arguments, then we are getting
enough arguments and we will return a result. And of course, it should be also possible to call the
function like this. First of all, we're
calling it with one and then we're
calling it with 23. This is how normally
carried function is working and we will
create it just now. What we want to do here, we want to create a
curried function. And as I said, this is
more advanced stuff and actually it is a good idea to write this function
was ECMO script file. So this function keywords, just because we're writing something which will
be used as a library. This is where here I want
to write a function, and here we're
getting a function. And actually here on
the top, Let's try it, our usage, so we understand
what we're talking about. We said here that we
want our carried some. We're calling here
our current function. And inside we're passing a
function with a, B, and C. And here we want to
sum a, B, and C. And actually I
can't even write it here on the bottom
after our query. So we can test if it's working, actually, as you can see here, as our current function. And we're getting
inside the function. This is our Fn, this abc and a plus b plus
c is our function here. But we want to do now we want to know how many arguments
we have here. This is where here
I want to create a property which
is called arity. Here we can just write function length and we will get the amount
of arguments here. Let's check this out. Console log arity. And here is our arity. I'm looking in the browser
and we're getting three, because here we have three
arguments, a, B, and C. Now we want to return here
a function because we know that current function
is always a function. This is y here Let's
write function, Let's name it for example, f1. And here I want to spread our arguments and let's check
what we have inside here, console log F1 here
our arguments. And actually when I reload
the page, as you can see, we don't get anything because we didn't call this car at some. What we must do afterwards, we must call discouraged sum as a function and we can
pass inside something. In our case we can pass 123. These are our three parameters. I'm reloading the page and
we are getting here f1, 123. So we're getting all
arguments as an array. This is our idea. And obviously we can also call this function
just with one. Then we will get array
with just one argument. What I want to do inside, I want to check how
many arguments we got or if we got enough
arguments or not. This is where here
inside return we can compare arguments length, this is the length of our array
is bigger or equal arity. This means that we are getting enough arguments to come
out of the function. So here I want to console
log enough arguments. In this case, I just
want to return here our function and call
it with our arguments. I'm spread in our
arguments again, and it will just put here all arguments just like
they were previously. Let's check this
out. I'm reloading the page and we've got a
message enough arguments. And actually here we can console log what we
are getting back. In this case, we
must get our result. I'm reloading the page,
we're getting six. It is working correctly, which actually means our
code already do works when we're passing in
three arguments at once. But it won't work when we're
passing less than that. This is where we must write here L Condition and
inside we can write, for example, console log
in need more arguments. And now after this book
wanted to return a function, as I already said,
if we're past, for example, encourage
just one argument. It must return a function where we can pass
additional arguments. This is why here we must return a function and we can
name it, for example, F2. And inside we will
pass more arguments, which actually means
this is our first coal, this is our second co-op. For example, here when
we pass current sum, this is also a current function. Let's name it partially
carried some. Here we call carried some. Now here I want to construct partially correct sum so
we can check what it does. As you can see here we are
inside need no arguments, and here is our function
was more arguments. And actually here we want
to pass in some arguments. For example, we
can pass here 23, and it will be exactly
this more arguments that we wrote here. What we want to do now, we want to concatenate
our arguments with more arguments to put all our arguments inside
the call of the function. This is why here we
can create a variable, new arguments, and we want to concatenate
here our arguments. And I'm calling here concat and I'm passing insight
more arguments. Now here we don't need to call our fn function just
like we did here, but we must call our F1 function because we want this check for enough arguments
again and again, which means we are
calling it recursively. This is why here
I want to return F1 function and they want to spread all our new arguments. This is where here three
dots and new arguments. Let's check this out. I'm reloading the page here. We're getting to meet my
arguments and enough arguments. What does it have a mean? Here it is our current sum. We passed here one argument, we're getting into cells. This is our console log need more arguments and here is
our additional function. This is where we're
calling this function and we're passing here
are more arguments. This is this variable. Now here we concatenate
it, our one. This is what we
passed here and 23, and we called our F1. We are getting here again, we have enough arguments, and here we're calling our function and
we're getting six. Now let's remove all
our console logs and check how it's working. What I want to try here is our correct some how we can call it, we can call it with 123
and we're getting six. It is working. Now we can call it with one. As you can see,
we're getting back a function and we now can call it with 23 is you can
see we are getting six also, which means it is working. And now we can call it
here with stool and after this with three
and we're getting six, which actually
means it is working correctly with any
amount of arguments. And here we carried some function where we
have ten arguments. Then here we're doing some
operation with Stan arguments. Then here we will
call this function recursively until we get
all needed arguments. As you can see, writing career
function is not the TGA. And if you never did it before, it is difficult to write this
directly in the interview, especially just on
the piece of paper. The last question that
you might get here, okay, But why do we
need curry function? And what your current
function can do? This is why here
we want now to use our career function
on our real project. And what we can do here, we can call it two
functions, get and map. Let's try this out. I want to create a get function
and they want to carried. This is why I am calling
this kind of function. And inside I am passing a
function with two properties. First of all, it
will be property, and secondly it
will be an object. And what we want to return here, we just want to take an object by key and it will be property. Let's check how it works. As you can see here we have our get and here we're
passing two arguments. First of all property
for example AD, and secondly our object, for example a D1. In this case, we are
getting one back. What we can do here, we can now because it's carried, just call it with one
argument, just with AD. This, you can see
we are getting back a current function now we can store it somewhere and reuse. For example, we can create
here an additional function, get ID, and we're calling here
get with just Property ID. Now as you can see
in the browser, we can use getID function
everywhere across her application on any object to get appropriately ID from it. Now we can do exactly
the same with map. For example, here
I want to create map and they want to
carry a map function. Here we are getting a
function which is an argument of the map and values
which is an array. Here I want just to call a plain JavaScript values that map and then pass in
our function inside. But now our map is carried, which means we can use it
everywhere like carrot map, for example, we can pass
inside of a map, get ID. And now here as the
second argument, we can pass an array and just
have here id equals one. As you can see here,
we're directly got an array of IDs with
the help of the map. And actually here boop
pass two arguments, but we can also cover it. For example, we can name
a function here, const, get IDs, and here we are born
to call our map on getID. In this case, we have a
partial applied function, get a d's, and we can use it to get ideas from many array. For example, here we're
right and get ideas. And we're calling
this function on the array with objects inside. And we have here a D1. And as you can see,
it is working. This is exactly the need of the current to write JavaScript
and functional way. And here's, this is
quite advanced topic. This is why it is
completely fine if you don't know this
topic as a beginner, but at least you must have
some basic understanding what is current and why
do you need it at all?
9. Adding Elements to the Array: You might get a
question like this and introduce regarding adding
elements to the array. As you can see here, we must
try to function which gets an array and an element and returns an array
with the settlement. That then actually it
sounds really easy, but you can solve it
in different ways. This is why you must
solve it correctly and at least tell
interviewer the correct way. So typically beginners
will use here array push, and then we're building
something like this. So we have a function,
for example, append, and we're getting
into arguments, array and our new element. And what we're doing here, we're using array push and
we're passing inside R, L. And after this we're
returning this new array. Then we just write here
console log append, and here we're checking, okay, For example, we
have our array 12, and here our third
element three. Now let's check if
it's working where reloading the page and
we're getting 123, and you think that you build
this function correctly. But here's the problem. Actually, I want to
write here our array. Let's name it for example, numbers, and we
haven't saved 12. Now here inside depend, I want to just pass our numbers. But after this I want
to console log numbers, were reloading the page
and we're getting 123123. What does it mean? We have this append function and we're returning
here the array. And most people will think that when we're
using this function, we're creating a new array. This is where normally they
might write new numbers. Here we're calling
our append function and we think, okay, we didn't modify our older ray, but we just get new
numbers because append function returns
for us an array. But as you can see,
this two arrays are completely equal because actual array push modifies the older ray and it
doesn't create a new array. And this is typically
a good example of bad code in the application. Why is that? Just imagine you
have one part of your application and you
have this number's array, then at some point your column disciplined function
to get new numbers. But then out of the blue, your modified your
old numbers array, which you didn't intend to do. This is why you think
that in your application some magic can
happen just because the colon of this function modifies some data
outside of this function, this is a bad approach. How we can fix it
and make it better. We should not use
here array push. It is not safe. What we want to
use here instead, for example, spread operator, we can write here
that we want to return a new array
and we want to spread all elements of our array that we're
getting as an argument. And if you don't know
what the spread, this is an ECMO
Script six operator, these are three dots. And what we're doing here, we're spread in all elements of this array inside our new array, which essentially
mean that we're creating a copy of this array. Now move one to add this
element at the following QRA. This is why we just
tried coma element. Let's check this out now. I'm reloading the page and here we are getting another response. We are getting here
123 and here 12, which actually means
this single line which will return for us new array function is
completely safe because we're not modifying any data
outside of this function. This is why this
implementation is much better if you are asked even
something that trivial, like pushing elements
to the array also have executive the
same behavior with objects. If we are passing
inside of a function, an object, and when
mutated there, then we're mutating objects
outside of our function, and this is bad. And you can also use spread with an object to create
a new object. In this case, we are
on the safe side. If you didn't know this
function like here is called pure
because first of all, this function will return
the same result every single time when we're calling it with the same arguments. And secondly, it doesn't modify any variables outside
the function. This is y, this is
safe pure function.
10. Concatenating Arrays: We've already talked
about hidden elements to the array and why Bush's not
always the best approach. But you might also have
a similar question. For example, here
we have a task, write a function which will
concatenate two arrays. And actually you might use here push and it will
be wrong answer. This is why here you
can actually write the function merge arrays. Here we are getting two arrays, for example array
one and array to. And here you might
write array one, Bush, and here you
spread of array two. And after this you can
just return array one. And actually not a lot of people will write code like this because here you are using push and then you are
spread in array to, but you might think
about such approach. Now to see the problem
we must create, first of all, our result. Here inside result, we
need to use two arrays. Array one, for example, it will be just
one and our array two here will be,
for example, 23. Now we want to call our
merger race and pass and said first of all array one
and secondly array two. And let's check and console
lock what we are getting. So first of all, result, then array one and array two. I'm reloading the page and
we're getting 12312323. This is exactly the problem, like it wasn't previous video. Bush mutate array. This is way here,
we're changing array one even if we don't
want to change it. This is why push in this case
is not the best approach. What we can use here instead
is I, the array concat, which has all the approach of JavaScript or just
a spread operator, just like we did previously. So instead of this return
and the real push, we can write here first of all, array one dot concat, and we have concatenate
function on the array. And here we're spread
in our array two, Let's check the South
where reloading the page here is our result 123 and here array one
and array two to three. This is exactly the
correct approach because concatenate does not
mutate an array. In this case, it will
return for us in new array. This is why everything is fine. If you don't want
to use re concat, you can always just
use a spread operator. Here we will use array
one as a spread. Here we're spreading
our ray tube. And actually the result will be exactly the same
where getting 123. And actually I really like this approach because it is more flexible and you can merge not only race, but also objects. You can add new elements here, and it is more modern. If you, for example, have a question to concatenate
three arrays or more, it is also possible, actually even array concat
can work with several arrays, as you can see here in so documentation here we
have three different arrays. You can write first
array dot concat, and then you have
secondary and third array. And actually it will
work correctly, but actually you can
do exactly the same with spread here you are
spread in array one, array two, array three. If you need to. Both variants are possible.
11. Check if User With Such Name Exists: You might get a question. Check that user with such name
exists in array of object. Obviously it can be
not name or not user. But the idea is that
you need to check a property of the
object inside an array. Actually, there are different
ways to implement this. And the worst way possible
is by using for-loop. Because as I said previously, for-loop is super
low level and it is not a right tool for
this specific task. Let's look how it looks
like with for loop. So here we want to
create a function, for example, is name exists. And here we must
pass two arguments. First of all, it's a name, and secondly it is
array of our users. Now inside the mask
creative property, which will be Boolean, and it will show us that we have this user inside an array. Here we can make a lead exists and by default
it will be false. Now we must write a for loop. So here we have
our lead I from 0, I less than users length. And here we're
making I plus plus. Now what we want to do inside
for every single element, we must check its name. This is where here we're
checking the users. I dot name equals our name. And if it equals,
then we want to assign inside exists through. After our for loop, we want to return
our exists property. Yes, this code will work. Let's check this out, but
it is super low level, as you can see, we have,
for example, named John. Let's try it here, Jon and hear coma our users. As you can see, we're getting
through because we hear such user with such
name inside the array. If I'm writing here just
full, we're getting false. But the problem with this code, it won't show that you are
an advanced developer. This is why I wanted to show you three other possibilities
to write this code. And actually, all these three possibilities
are occasions. My favorite will be
a single line here, so we can create a
function is name exists, and here we're getting
name and array. And as you can see here, I didn't try to
users butter ray, because now we can use
this function on any data. Now what I want to call
here is array dot sum. And if you don't know
what Sam is doing, you can call some on the ray
given set some predicates. So you want to check
something inside. In our case, some will
return a straw if we have at least one single element
which fulfills our condition. Inside some we can
drive element. And we want to check here, element name equals our names
that were passed inside. And this is literally
the same code like we wrote here,
but much smaller. Let's check the sound. I'm
reloading page and I'm just typing his name exists as you
can see where getting true. So actually some is the best
solution to this question, but it is also possible
to use other solutions. So let's comment this
out and try again. We have here again two
arguments, name, array. Now inside we can try and find the element with such name. This is where here let's create an element and we're using here array dot find where
getting our element. And here we want to check element dot name equals
our name from the top. But in this case our element
is actually an object. It's not a Boolean. This is where he'll
brewmaster wrapper element in Boolean to return
Boolean and not an object. In this case, it
will work correctly. I'm reloading the
page as you can see it as work in
exactly like this. So the main
differences that were master it a little bit more code because we must
convert it to Boolean. And the last thing that
we can use here is actually not fine,
but find index. And if you don't know
what finds the index is doing is exactly the same logic, but we're finding the
index of this element. If we can find the object with such
name inside our array. Here we're not getting
our Element button index. And after this, we'll know that if this index is less than 0, then this item was
not found. Here. We can try to return
index bigger than 0. In this case, we know or
K It is bigger than 0. We have this element
inside the array. And as you can see, this code is working exactly the same. My approach would be sum, the next approach we'll be fine. The index find is also okay, but you should not use
for-loop because it is highly inefficient
for such task.
12. Remove All Duplicates in the Array: You might also get
a task like this. Remove all duplicates
in the array. Which basically
means if you have an array of numbers
and you have, for example, 112, you
need to live on the 12. I see here three different
ways to solve our problem. Let's try with the
best solution. For example, we can create
here a function unique array. We're getting here our array
to removal duplicates. Here what we want
to do coupon to return an array and we want to spread inside new set and
where bison inside the array, if you don't know what
set in JavaScript is, it's an object
which allow you to store unique values of any type. This means that if we're
right in here and you said we're passing inside
the array, for example 112, where hidden Enter,
as you can see, we have the set only from 12 because inside our set
elements can be duplicated. This is why, as you can see, if we will spread on your set and put it
in the new array. To convert setback to array, we will get our unique elements. And actually not a lot of people know about this solution, but this is the best
solution because it is, first of all, a single liner. Secondly, it is rarely
performance if you're done no, this solution, it's not bad. You can always build
this logic on your own. The most important part
that even FOR loop here, if you're using forEach
foray is not that bad. Let's check this
out. For example, we have here the same function, unique array, and we want
to write here a loop. And of course we need to store our result in
additional property. So let's make here result which
will be our unique array. Now here I want to loop through every single element of our
array with forEach function. Here we're getting our item as every element of our array. Now what we want to check here, if we already have this
item inside our result, we can check here
result dot includes. And if you don't know, include, check if we have the
settlement inside an array and we want to
pass inside our item. So this will return
true if it includes. But actually we must put here
bank to have a negation. If it does not include this
element inside the array, then we want to push
it to our result. So result Bush and
here with the item. So as you can see,
even for each loop here is not that
bad because it is isolated inside of a function where simpler looping through every single element
and we're pushing our result directly
in the new array. And of course at the end we
must return our results. So here let's return the result and check
if it's working. Here is our function
unique array 112. And as you can see,
we're getting 12 back. But obviously our function won't work with objects
or arrays inside, and this is completely normal. So if you have here an
object with a equals one, and here you have one more
object with a equals one. As you can see, we are getting two elements and
this is totally fine because this is two
different objects and we can't compare them. And actually we can derive
this for rich by using Reduce. In this way, we will write exactly the same code button
the more functional way. So here let's create our
function unique array. We're getting here
our array and we want directly to return a re, reduce. And here inside we must pass our function with accumulator
and every single element. Here we have a function
and as a default argument, we have here empty array, exactly like we
had here where we wrote result equals empty array. Now what we want to do inside, we want to check our
accumulator includes, so we're checking our result. If we have in this resulted
array our element. So if we have it,
then we simply return accumulator so we
don't change anything. In other case, we want
to push this element to accumulator and we're
not using array push, but we're using spread. Here. I'm spread in accumulator and then I am
adding our element. In this way, this code is
completely functional. It is easy to understand and would don't have this
nasty push here. Let's fill out the page
and check if it's working. As you can see, it still
doesn't work with subjects, which is totally fine. And it works with
primitives Because here one was removed
from our array. As you can see, you have
three different variants to implement
uniqueness in array. And actually all
this reversions are completely fine to
show on the interview.
13. Sorting the array: We're already had a
certain exercise when we mapped our users in one
of previous videos. But here I want to talk about surgeon, a
little bit different. As you can see, you
can get the question, sort the array of numbers. Which actually means we
have an array, for example, 351, and we must sorted. For this, we're using certain
function in JavaScript. We simply write sort. Here we must pass a function
and we have such conditions. When a less than b, we're returning here minus
one if a greater than, bigger than 10 if they're equal. And previously we
wrote here a and B, and here we can write
a smaller than b, then we're returning minus one. In other case we're
returning one. Also, it is important to
remember that certain returns, the result of the certain, which means we can put it in variable, for example, result, but it will also mutate our
array that we've created. And actually it doesn't
really make sense here because this has generated
array on the fly. But if people put
it in the variable, then it makes sense. Here we have our array
and here we're certainly, let's look on the example. I'm console login here,
array and result. And as you can see
in browser here, we're getting exactly
the same sorted array. This is happening
because sort mutates exists in an array and we
must remember about it. Also, there is one more
important point to remember. In compare function,
we can return a number which is bigger
than 0 and smaller than 0, and it will be exactly the same. It will be before a
and sort a before B, which actually means we can
write our code a little bit differently and
not with minus 11, we can simply return
here a minus b. Why is that? Because we have
here two numbers, for example, three minus five. In this case it will
be less than 0. And then we will have this
condition sort a before B. Let's check this out. I'm reloading the page. We're getting one through
five as previously, if people right here, b minus a, then it will be
sorted in other direction. As you can see, we're
getting five through one, which actually
means for sorting, we can sort it by
returning minus 11 or something less than
0 and bigger than 0. Also, it is important
to remember that we can use sorting on
Louis primitives. If you are trying to
sort here an object, it won't do anything because you can't really compare objects, but you can sort properties
and site objects. And we have a task
to sort an array of our books by author's last name. Here we can use exactly the
same search AND function. We are writing here,
books dot sort, and here we are getting
as an argument, book one and book two. And now we must
compare them properly. So first of all, we
must find a last name of the first author and
of the second author. Here Let's write
awesome Last Name, one. And here we're taken
our book one.org. And here we want
to split our name with space and get
here first argument. In this case, we will get the
last name of our awesome. Now I will copy paste this line and here we have
also LastName too, and here is book two. And now after this weekend, compare these two strings. This is why here we can write or LastName one smaller than ASO, lastName tool, then we
want to return minus one. In the other case,
we will return one. And actually, as
you can see here, we must use minus
11 because it's not numbers were country
will subtract strings. And as you can see
here in browser, we didn't console log anything. Now let's console log our books because actually when
mutated our array, Let's reload the page. And as you can see,
these are our books. But now on the first place
we have Susan Collins. As you can see, it is sorted because previously
we had here rolling, then Mary Lou and
then John jawline, which actually means that
this code is working. And this is how you
are sorting array of objects by some property.
14. Interview Is Not What You Think: A lot of people,
especially beginners, do not understand the purpose
of interview correctly. They think that they must
come to the interview, answer a bunch of
questions and get a job. And it is not like this a tall because integer is actually a communication between
several people wherever side wanted to clarify some questions
regarding other person. For example, if we're
talking about interviewer, he's interested in
your knowledge and obviously how you
will fit in his team. It is not just about
answering questions. It is more like ping-pong. You are asking a question and interviewer
asking the questions. It should not be like
only interviewer asking the questions and use simply
answer because in this case, first of all, you can get
answers on your questions. And secondly, you are not
showing that you are interested in this company or in
this specific position. When you are talking
with tech guy and the special with each, you must show that
you are interested. You must ask some questions about company, about the team. How many working days you have? Do have overtimes here, how often people are
living the company, how long people typically work
in the company and so on. Because first of
all, you want to know what are working
conditions in this company and
not just getting some company with bad
working conditions. And obviously I can understand that if it
is your first shop, you want to go anywhere, you simply want to start working and they totally
understand that. But if you don't want
to suffer later, it makes a lot of sense
to ask these questions. Also, you must like team
lead or interviewer, and typically it will be your future boss
because you will work a lot with this person and it goes the
same with the team. It is really nice idea
to meet the whole team, at least to check what is
the mood inside the steam? Are people friendly
to each other? Are they happy with working
conditions and so on? And the same I can say
about checking the office. It is really weird
sometimes when you are not allowed to
see the whole office because this will be a place
where you will be working and you must be satisfied
with working conditions. I highly recommend you to
ask for the short-term in the office so you can at least see the
working conditions. Do you have enough light there, what monitors you
have and so on.
15. Writing Range Function: You might get a coding exercise
to implement the range. What does it have a mean? It is a helper function
which looks like this. For example, if we are
calling range from one to 50, it will generate for us an array 123456 and so on until shifted. And this is actually
really nice helper when you need to
generate some data. For example, you want to
generate fifth random users. In this case, your assembler
generates such array, and then for every
single element you are mapping and new random user. This is why this
helper exists in almost all helper libraries
like for example, a dash or Lambda. And diversity is a solution of result thinking here
is by using for-loop. This is where you can write
this function like this. You have here a function range, and you have here start and end, for example, from 150. And then inside we must write a for-loop from start
point to the endpoint. This is y here, let
I equals stars. So we're not starting from 0, but from style here we're
right in I less or equal, and in here we're
making I plus plus. Now inside this for-loop, we must push every single
index to our result. This is y. Let's create
here our lead result. This is our array. Now inside we can write result push and we're
pushing here our I. And now we just
return our result. This is how you can build a range function
by using for-loop. Let's check in browser, I am writing here range
function one comma 15, and we are getting our
array from one to 50, which means our code
is completely fine, but it is super low level
and we can make it better. More advanced level is
to leverage our array. We can write in browser array and then our end,
for example 15. And as you can see, this returns first empty array where we have reserved 50 elements and what we can right after
this dot keys. And now we're just
calling these keys and we're getting
array iterator. Now if we will try to spread this array iterator
inside array, as you can see, we're getting our 50 keys starting
from 0 to 49. And after this, we
simply need to map every single element and
add our start point to it. So here we can write dot map, and here we have every
single element and we're writing element plus
stat in our case, for example, plus one, and we're getting exactly
the same outcome. This is an array from one to 50. This is why this variant is
a little bit more advanced. Here we can create our range function and we
are getting here Stat. And then now inside we
want to return this logic. And as you can see, this
is an array where we're providing and we're making keys and we're spread in this array rater
inside our new array. And we're mapping
every single element. And where I didn't
hear our start point, Let's reload the page and
check if it's working. So I'm passing inside
orange function 150 and we're getting a
nice array from one to 15. And this is how people
typically write this function inside
helper libraries. For example, lambda,
although dash.
16. Writing Shuffle Function: You might get a
question on interview. Write a function which
implement Shuffle. What does shuffle means? You simply change the positions of elements inside an array. And actually it's not that easy to implement it with using, for example, for each. But here we can leverage method random in order to sort
elements randomly. This is actually what
we want to hear. Let's create our
shuffle items function. The main idea is
that here we are getting our array of items. And this can be whatever. It can be, just a number, it can be an object or
maybe even array of arrays. It must work in any case, this is why what
we want to do **** want to loop through
every single element and create for every element and an object with key and value. And actually they're inside. We will have some random
key generated by random. We also will have their value. This is exactly the
value of our element. In this case, we can
sort by this field, our array, and then just
remove this random key. Let's do this now. I one directly here
to return our items. And first of all,
I am calling map. And here we have access
to every single element. Let's name it high item. And what we want
to do, we want for every single element to return an object with two properties. Let's name this property sort because actually this is
appropriately for sorting. Here. We just tried math random. Here we will have
our random property and the next one will be value. Inside the value we
are storing our item. Actually when we check
our code in browser now, we're just calling
our shuffle items, for example, was 12. As you can see back, we're
getting into objects sort and here random number and
value is value of our item. And this is actually extremely good because here
inside the value, we can store numbers,
objects, or arrays. It doesn't actually
matter for us. After our mapping,
we want to sort our elements inside this array
by this certain property. This is why here we
can write sort and we're getting here
item one and item two. Here. What we want to do, we want to write item
one dot sort minus item two dot sort and
actually will know that sort using
numeric property, which actually means
here we can simply use substract and not
write minus 11. It will sort it correctly. But for us, water doesn't
matter because we just need to sort it
to change positions. And after we change positions, we want to get our value spec. For this, we must
try it one more map. And here we have, let's name a because this is our object and we want to
read here a dot value. And actually this is our
item that was stored here inside every single
object. Let's check this out. I'm reloading the page
here, shuffled items 12. We're getting to one. I'm calling it again here
to one again here 12, which means it is working with any elements and it
just shuffles it. And actually this is an
amazing way to solve this because we are
leveraging here math random. And for every single
element we're creating this sort in n value. We simply sort this
random numbers and now it is shuffled. After this, we're just
getting our items back. This is the easiest and the most correct way to shuffle elements
inside the array.
17. Find the Number of Occurences of Minimum Value in List: You might get a task like this. Find the number for currencies of minimum value in the list. Which actually means
we have an array of numbers and we first
of all must find the minimum value
inside and then calculate how many times
we have this value. And actually if you will
try to use here FOR loop, then it will be really tedious because you
need to use it twice. First of all, to find the
minimum value inside the array. And secondly, to
calculate how many times we have this value inside. This is where
actually we must find the correct function inside JavaScript to solve with easier. And actually we have
such function inside JavaScript and it is
called Math minimum. As you can see here,
we're passing insights several arguments and it will
return for us the smallest. This is why we can
use this function, but it doesn't work with arrays. What we can do instead, we can write math minimum and we can't pass
inside the array, but we can use a
spread operator here, and it will convert our
array two arguments. Here we can have an array 123
and we're getting back one. And that is exactly
what we wanted. This is why, as you can
see in a single line, we can replace our for-loop, which will be much more
difficult to write. First of all, here let's
name it mean value. Here we want to call
it on our array. And let's create here our array, which will be 123. And here we want to
spread our array. We found our minimum
value in the array. Now, how we can find how many times we have this
value inside the array. And actually the easiest variant
here is by using filter. If we will filter our array
by this minimum item, we will get an array
of our minimum items. And then we simply can get
a length of this array. It will look
something like this. We can get here
our minimum array. And what we want to
do is array filter. And here we have access to every single element and we just compare if our element
equals our minimum value. In this case inside
me an array, no, we have only our minimum values. Now we can write
here just console log min array dot length, and it will return for us exactly how many occurrences of this minimum value we
have inside the array. Let's check this out time reloading the page
per getting one. If we will add here 11 twice, then here we have three of them. And as you can see,
our code is working and didn't thrill lines
was solved our problem. This is why I highly
recommend you to always try and find the right tool
for the right jump.
18. This: In this video, we will look
on all questions which are related to this and
context inside JavaScript. You might guess some
question like this. What will be locked here? The first task that
you are getting, you have a function
with function keyword. This is important. Now inside we're just
writing console log this, and now we're colon get item. So the question is what we will see inside our console log? And actually in browser
you can see that we're seeing window and you
might think, okay, inside functions, this is
always referenced in window, but this is not correct. Instead functions, this is
referencing the global object. It may be window, it may be undefended, it may be something else. It all depends on the context. But if you define
a function keyword directly in JavaScript
code without any nesting, it will be window. Now you are getting
Question number two. What will be locked
in this case? As you can see here, we
have an object item with title and getItems method
inside get item method, work console login this here we're calling
item dot get item. In the case with objects, when we have methods
inside objects, we're always referencing
this object. This means when we're
reloading the page, we're getting this and this is an object with
title and get item. In this case, we can use
all properties inside our object because they are
available for us inside this, when we're talking
about objects, this always references
our object. Here is our task number three, what will be logged
in this case? As you can see here, we have
not an object but a class. And we also have inside the
title and getItems method, and we'll also have this inside. Now we're creating the
instance of our class and we call a getItems
method from our instance. This is important
to remember that inside methods in our class, when we have an instance, we have a reference
to our instance, as you can see in the
browser here we have this and we can see
this word item. This actually means
that this object is an instance of
our item class. And inside we have
our title ball. We can use all properties of
this instance inside this. But now we're getting a
question what will happen if we will pick a function
inside our method? So actually what we're
writing here is function, for example, some function. And inside we are right
in this console log. And after this we're just
calling our sum function, which actually means we
define the function with function keyword
inside our method and we're calling
it here directly. The question is what will
be console log inside this? As you can see in browser, this is undefined it
because as I said, instead functions, we're
not referencing the window, but we're referencing
global object. And actually window keyword always is referencing
global object. So in this case it will never
reference our instance. And this is important
to remember, which means if you have a
function inside your class, this inside won't be correct. It won't be referencing
our instance of the class and we can't
use properties of it. And exactly the same
problem you will have not just with defining
the function like this, but if you are
writing, for example, a map for array
inside your get item, and here you have a function
for every single item. Now if we will write
console log this inside, it will also be not correct. As you can see in browser
I'm reloading page. We're getting undefined at three times because
here we're using function keyword and then set function it is
referencing undefined it. Both these variants
are problematic. And now the question
is how we can fix it and get the reference
to our theories. And we have two
solutions for this. First of all solution
which is older, and it is also used when we're built-in JavaScript
all the version. For this we can simply define
before this, for example, with an underscore and we're assigning hear
reference to our list. This will be correct because
we're inside our method. Now we can consider here not this because here the
references strong, but this was underscore. Here we have another reference. Now let's reload the page. As you can see, we have a character reference to
our instance of how item. This is typically
older approach and it is used in the build
step of JavaScript that the better
approach will be to use an arrow function here
instead of function keyword. So we can simply use here arrow function from
magma Script six. And now when we're console
login inside of this, it will have the
correct reference. As you can see, the result
is exactly the same Because arrow function is getting
the context of our parent. Which actually means
from here we are getting context that we have
inside guitar item. Here we have a reference
to our instance. This is why I highly
recommend you to always use arrow
functions and not function keywords
and then you won't have any
problems with context. So to sum this up inside
function keyword, you always have a reference
to a global object. Inside objects you have a
reference to the object itself. Inside classes, you
have a reference to an instance of the class
and inside function, inside, for example, method
or directly inside class, it will be referenced
to undefined. It.
19. Classes: One of the most
popular questions on interview is of
course, classes. You might get a
question like this. Design a class for
employee which takes a DNA named urine
construction of objects. And here's a cellular property. As you can see, we're not getting super
strict requirements here and we have some
flexibility to implement it. This is why I highly
recommend you to think about it and implemented in
the best possible way. First of all here,
but wanted to create a class and let's
name it employee. And now as its head, we need to have a
constructor with the DNS name inside. This is y. Let's create a
constructor and we're getting our AD and name. And after this we're
assign them to the Sadie. Here is our AD and
this name equals name. So we're getting
these two properties. But you can do it
better because you must show that you
are a good developer. This is why it is
really nice to check if we passed inside
these two properties. So we can just add, okay, if we didn't pass AD or
we didn't pass name, then we want to throw an error. This is why I wanted to
throw here in New Era. And here inside we can
write, for example, our employee ID and
name are mandatory. Because actually this
is what it is saying in the task and it is nice
to cover this feature. Also, as you can
see, we have a line and it has a salary property, which actually means
we can set the salary. It's not like we're
getting it in constructor. We need a setter and getter
functions for our salary. First of all, we can define that set salary and it
will be a function, our setup for salary, and we're passing
inside our salary and we just store
it inside this. So this dot salary
equals our salary. This is not all because
we also want to get your show if the salary is
available inside our class. But we really want to construct this class in advanced way, which actually means
coupon to have some public API and some
methods to get our properties. This is way here I highly
recommend you to create, get salary and we don't
need anything here, and we want to return
here this dot salary. And it also makes
sense to create two getters for our ID and name. Here we can create
getID method and inside we're returning
our thes dot ID. And we're also can create
here getName method, and it will return
our thes dot name. So as you can see with thought quite a lot about our class, and it is implemented
as best as we can. Now here we can try to use it. So here we're creating
our employee with new employee and
we're passing in site ID and name because
they are mandatory. And actually we can check it, we can reload the page
and we're getting employee ID and
name are mandatory. And this is nice to check. Here is our 81 name,
for example, check. And now our employee
won't throw an error. What we can do now we can write employee set salary
and we're passing, for example, 1000 inside. And now we can check it. So I will reload the
page and here is our employee with a
DNS name and salary, but we'll also have a
getters, for example, gets salary will return to our salary and getName
will return the name. Which actually means
we implemented our class as best as possible. But now you are
getting a second task. Design a class for manager, which is employee and can
have department property, which actually means here, your interviewer wants to
see extent of our class because we can create a new class based on
our employee class. This is y here on the bottom, we can create new class Manager. Here we want to use
extends to take the functionality of
our employee class. And actually this
is almost t dt. This will take everything
from our employee class, but we also need to
create a department. This is why we just need
a setter and getter, just like we did previously. Let's create here
set department and here inside we're passing
department or just name. And here we're saving
our name inside will also need to get,
so get Department. And we don't need any
arguments here and we want to return our list
dot department. And actually it is also super important to have a
nice names everywhere. As you can see, I'm
not naming things like set or just at full over terror. I usually try to make this names as production
ready as possible. We're using here, for
example, set department, departments so it is all
clear what it is about. And it really shows on the
interview that you are a good developer and you can
write high-quality code. Here we have our set
department and get Department. Now let's create
our managed chip. So we just create new manager and we must pass
inside as always, ID and name, for example John. And now here we can
check our manager. We can make set
department and we're passing it said department
for example, development. Now we can check our manager. So we haven't said
department and there is a GET department function which will return for
us the department. This is how typically you
will answer questions regarding classes or
extension of the classes.
20. Prototypes: In previous video we talked about classes and
how to extend them. But the next question of change reviewer can be
occasional classes. But do we have classes
actually in JavaScript? We have something else because
we don't have any classes in JavaScript and they are built as a trigger
for prototypes. This is why now we must design exactly the same classes just by using JavaScript prototypes
without usage of classes. And actually you need
to do it at least once. And then, you know, what
are the problems here? First of all, we have our
class employee and secondly, manage chip, and now we want
to reflect it to prototypes. First of all, we must
move all these methods outside because actually we can try them inside
the function. And actually what is a
prototype? This is a function. We don't use class
keyword and I will use y here because we're
talking about prototypes. So this is the older
version of JavaScript. So here I have var employee, and this is just a typical
normal function with function keyword in here
we're getting a DNS name. And actually this is
also our constructor. We don't need constructor here. We directly check, okay, if we have ID and name, then we're throwing an error. But if not, we're sitting
here this AD and this name, which actually means this is our typical class when we're
doing it with prototype. Now we need to adjust
all our functions. As you can see here, I
have this functions and now instead of just set
salary like a method, we must try it it
inside a prototype. We're saying employee dot
prototype, dot set salary. And this will be a function. Here, we simply say
equals function word, and here is our function. And we need to do exactly
the same in every method. So employee dot prototype
dot getID equals, and here is our
function and the same with getName and also
with good salary. Here is prototype,
getName equals function. Keyword in here gets salary also the same employee prototype, get salary equals function. And now we've successfully refactored our
class to prototype. It was not that difficult
because we didn't do extend. For now I want to
comment out manager, so we're not getting any errors. Now let's check and browse it. I'm reloading the page and now
we have here our employee, as you can see, the code is
looking exactly the same. This is the instance
of employee. Here we have, for
example, getID method. We're getting one. Here, we have salaries so we can
make and get salary. And it is all working, which means this is how
you affect your class. Two prototypes. And now we have a
manager and extend, and it will be more difficult. So here we have a manager, we said department
and get Department. And yes, it also
must be a function. So here we can just write var. Here we have our manager and we know that
this is a function. We're also won't have said department and get
Department inside. We will write them afterwards. But here too, the problem, our manager extends
our employee, but we are setting inside the same params and actually we don't want to write
here ID and name, but we can just try
it here, params. And we just wanted to throw
all fields that we're getting and use
here our employee. And for this we can
write code like this. We can write them play apply. Here inside we are passing
this coma arguments. And what this essentially does, it uses arguments from
this function here, this. And as you can see
here, I also wrote programs were not
using them for now. But if you get a task to extend
manager with some field, you can write here
these, for example, image equals params dot image. And in this case you must also pass in your
manager and an image. This is totally possible, but we don't need
it for our task. This is why we simply
use here employee apply these arguments
and what it does, it literally makes an extent
partially of our employer. As you can see here, we
have this ID and name, and actually we're
calling this function, but we're giving it another
context where given inside the context of our manager and arguments from
this function. But here is a huge
difference that I want to show you actually when we're
jumping to the browser. And right in here
manager prototype, you can see here on a
constructor function. But here if I will write
employee prototype, you can see here
all functions that we had previously
here on the top, because actually
this single line is just calling the
constructor of employee. It doesn't have anything
to do with this prototype, which actually means
this functions IN said prototype of employee and
manager doesn't get them. And this is super important because we're
extending this class. This means that we want to
have them directly inside our prototype and we want to copy them.
How we can do that. We can write here manager
dot prototype equals, and here we want to
use object create because we want to clone
our employee prototype. And inside we're passing
our employee dot prototype. In this case, we're cloning
all these functions from our employee to our
prototype of manager. So let's check what
we're getting here. I'm reloading the page and right in here, manager dot prototype. And as you can see, this is
now a copy of our employee. And we can write here
manager dot prototype, dot getID for example. And we're getting this method. Obviously it is
undefined it because this is not an instance
but the class, but we have access to
this method inside. But here is also a huge
problem when we're writing here manager dot
prototype dot constructor. We're getting the constructor of our employee and not manage
it and this is wrong. This is why what we
must write here also, manager dot prototype
dot constructor. And we want to assign here
our manager function. In this case it will
be 100% correct. And as you can see
where I get in reference to our manager, these are two lines which
are super important when you are doing
extent with prototype. Because first of
all, you want to get all methods from our employee. And secondly, you
need to override, construct a back to our manager. And now we can use SAT
department and get Department. This is exactly the
same it was previously. It is manager dot prototype. And here we're assigning
our set department and here manager dot
prototype.js department. Here of course, we need to write the function keyword in exactly the same should
be here on the top. In this case, we successfully
implemented manager, just like it was done
previous Lucas classes. Let's reload our page and check. As you can see, we're getting our manager with ID and name, but we'll also have a
function set Department. We can write, for example
here development. And now we haven't said
Manager, also development. And we have a nice GET
department function. And obviously we can
use the same function. For example, get ID from our parent and it
is also working. This is who you typically
will use prototypes and implement classes with native prototypes
inside JavaScript.
21. I’ve Failed Interview. What’s Next?: It may be that he just failed your interview
and maybe it was your first interview
and you really wanted that job and now you are really depressed.
What should you do? First of all, you
need to understand that this is completely normal and you will fail a lot of
interviews during your life, and I failed lots of them, especially in the beginning. This is why what you
need to do you want, first of all, to continue. You should not stop just after your first interview and even
after your fifth interview, you should not stop because
sooner or later you will find your first company and
you will get your first job. First of all, you should
not be depressed. And secondly, you must use interviews as an additional
source of knowledge because actually this is a
nice place to understand what questions you have been
asked on the interview. And also you can understand what knowledge you are liking. This is where there are two
main points that you must do. After every single interview. Just after the interview, you must sit down and
write all questions that you were asked and you
didn't answer correctly, it didn't answer TO. After this, you must Google all these questions
and learn it. Obviously, you can't learn
everything in one day, but you can split this knowledge and learn something new for you. This is really important to
do it directly afterwards, because in the other
case you will forget it. The next important point is to ask for the response
from the company. And actually it might be that
you didn't get a letter or a phone call after your interview from
the company at all. And this can happen in
a lot of companies. This is where you must
write your chart with whom you spoke at
least two times, may be in day or two
after the interview, and then maybe in three days afterwards because you
must get some response. And if they said that you
didn't pass the interview, you must ask for the technical
review of your interview. You can just ask, okay, this is PT, but they
really want some feedback. What knowledge I'm liking? This is completely normal
and actually they won't provide any technical
feedback really often, but sometimes they might do it. And this is also
extremely useful for you because you will
see your knowledge from another person's
perspective. Your interviewer
can write something which is extremely
important for you to learn. This is why it don't
be discouraged if you didn't pass
the interview, this is completely normal and
you should just continue.
22. Modules: You might also get a question
regarding modular system. They mean by this EPMA Script six modules or
common js modules. For example, your
question can be created an atmosphere crypt six module
with functions getName, surname, and default
expert get full name. For this, you must know Harmodius are working
in JavaScript just because it is the
core component of JavaScript and we're
using modules everywhere. To use the inputs, we must
create one more file. As you can see here,
I have main JS. This is our main
file and index HTML. So let's say that
we are creating a new module and we
want to name it. For example, eg must
scripts dot js. Inside we will write some
Atmos Script six module. First of all, here we want
to create a method getName, and we're writing it
with export const. Here is getName, and
here we are getting as an argument name and we're
returning back our name. As you can see here, we use the construction expert const, and this is exactly one of the functions that
we must create. And as you can see, get
name and gets her name. I just didn't named functions. This is why we're writing
them and we're experts in them from this module
was export const. I will copy this line and paste
here and we must name it. Get certain name. Here we're getting
are certain name and we're just
returning our surname. The last thing that
we're mask grade is default expert, forgetful name. And if you don't know how
to create default expert, this is export default. And here we don't need
to provide a name, which means here
we directly have a function in our case may be
we can create it like this, name and surname and we
just concatenate it. And inside here we have an Atmos cryptic string and we just call here to our functions. First of all, getName and
we're passing inside name. After this we have
a space in here, we have a second function, gets her name wherever
bison surname inside. Now our script six chairs file is a module and it is
completely isolated. And on what we're expert it
here is available outside, so let's use it now. We have here three functions, biomass jumping our
main chairs in here, we must import them and we're inputting them
like this, important. Then we have brackets and
inside what we're inputting, it is getName, Coleman
gets her name. And as you can see,
my y's editor older the road from here
at my script six. And as you can see it
as of course black because we're not
using this functions. This is where here
I want to write getName and we're passing in. So for example, JAK, then we have here get surname, and here will be sparrow. This is how we're inputting
and using name experts. We're using here word import, then brackets, and
inside named functions. In our case, getName, gets her name from, and this is the path to our
file ECMO scripts dot js. Now the question
is how we can get our default expert and
for this weekend, right, just directly after input, get full name and then comma. In this case, we will get
our default expert first, then named experts just
with brackets afterwards. Now here inside our
console log we can use get fullName and we're passing
in site two strings. First of all Jack and
second less parallel. And now we can use this
functions just like they were defined it
in this position file. Now the question
is how we can use EKG prescript six
module inside our HTML. For this, we must
jump inside our HTML. Here we have script
with source Manchester. This is totally fine, but we must write
here type module and then it will import it like
Atmos Script six module. Now let's try to
reload our page. As you can see,
actually it worked but we are getting
a narrow and we're getting course error because
this index HTML country really loud Main chess
because you can't make a cross-origin
requests from file. And this is actually a problem
because here I am using this source file just like
normal index HTML file. If you're using some
front-end framework like reactor angular, you won't have such problem because you have
modulus systems, they're out of the box. But exactly for this
particular case where I have played
an index HTML, I must serve this index
HTML like a web server. And for this there is a
package which is called serve. You can install it
was known chess, and as you can see now
it is available for me just this index HTML on
localhost 3 thousand. Now as you can see, we don't have an error regarding course, but we have a problem to load our atmosphere
crypt six file, because actually
here we must put dot js to load this file. Now we're not getting the Sarah. And as you can see him console, this old functions
are available fast. Here we can see Jack
Sparrow and Jack Sparrow. And this means that
we successfully inputted these three
functions was named expert and default export from our module by using
Atmos group six modules. Now we have a next question. We must create exactly
the same stuff with common js module. And if you don't know,
common GIS model is typically used
inside known chairs. This is why now I
wanted to write our atmos Script six JS file
with using of common chairs. This is why I will copy paste tabulation and
create here a new file, just name it common dot js. And we will rewrite
everything here. In common js module, you can do the same. You can't have simultaneously default export and name experts. And this is because instead of export const, wherever
I put in here, module.exports dot getName, and we're assigning
a function here. The main point is
if Book want to write a default
expert where ICT and instead of export default
module.exports equals. And here is our function, which means here we have a default template
for our function. So what we can do in
this case is just leave this getName
and get surname as private functions
because we control the expert them simultaneously
without default expert. And as you can see here, we have Module experts just
to have our default expert. Now we can jump directly in Manchester and here import
our default function. But to do this we must
use the require keyword. This is why here I want to write const and we're getting
big get full name. And here equals require, and here is our path
common JS or just common. I can jump inside console
and right node main chess. And obviously we're getting a message getName
is not defined it because here we're trying to console log getName
and get surname. Now here I have
just get fullName. Let's try again. As you can see, we don't have any errors and we're
getting checks parents. If we really want to get
all three functions, we must jump here and
just use everywhere module.exports dot and
here will be our getName. Now here will be more at your dot experts dot gets surname. And here we want more teal dot experts and
here will be good full name. In this case, it will work and we will get our
three functions. Now we have three experts. We can jump back in Manchester. And here instead
of get full name, we can just destructure
and get three functions. Getname, gets her name, and here get fullName. And now we can uncomment
these two console logs. Let's check this out. I'm jumping into console
and run Node Manager and we still get an agile
getName is not defined it. But actually the problem here
is that inside common js, we don't have a function
getName and get surname because actually we have
them on in Module experts. This is why this
code won't work. Berlin need to
write, first of all, constitute name and then after this module experts dot getName
and here equals getName. In this case, this
function can also work. We must do exactly the
same for our get surname. Here will be const get surname and let's move it to the top. And now here is our
experts getName, and now here we have
get surname and we're assigning here our
function gets Ernie. In this case, all functions
are available for us inside this file and also outside through module experts.
Let's check this out. I am running node main chess and we don't have any errors. So as you can see, we have two different variants
at my script, six and common chest. And if you caught it
all these questions, then the next question might be, What is the difference
between Atmos Script six modules and
common js modules. And actually SAL do this set. Common chess modules are typically used
inside known chest. This is the standard
modular system for known chest ECMO Script six
modules we have in browser. This is ECM Script
six JavaScript. And actually you can
use ECMO Script six modules inside node chairs. And this is just a
sugar around require. This is why if you assume a postscript six modules
inside non chess, you know that inside
you still have required because it is
mandatory for NodeJS. Demo scripts six
modules are first of all newer than
common js modules, and secondly they are static, which actually means you
can pack this require inside if condition for
example, inside for loop. But you can't really
do it with input because input must be
always on the top. And if input is not on the top, then it will bubble
automatically to the top when
JavaScript parses it. And this is actually
much better, first of all for safety. And secondly, to implement different built-in tools on the top of Atmos
Script six modules.
23. Implement Debounce Function: One of the questions that
are here from time to time is to write
the bones function. And if you don't know
what is the bones, it means that the
function will be called only after
certain period of time, which actually means
every single call of this function
will be delayed. How can we implement
this function? First of all, we must create a function that we
want to the bones. Here I want to
create a function, for example, save input. And here we're provided
inside our name. So the idea is that inside we will simply console
log something. And we can see that this
function is working. Here is save input and name. And we're using the
bonds function. For example, when we want to send some information
to the back-end, user is typing something
in the input field. And we want to
wait, for example, 200 milliseconds or two seconds after person will stop typing
something in the input. In this case, pupils sent to the back-end just a
single request to check the validation and not a lot of requests after
every single letter. This is exactly why
we needed the bones. So we have our save
input function and now we want to
call it the bones. For example, let's name
it process change. Here we want to use a DBMS
function that we will create in a second inside we
must provide first of all, our function, this is
saving input and secondly, delay, for example, two seconds. After this, we can simply call process change with a string. And actually doesn't
matter how many times we will call this
function the main idea, it will be called on the ones. After two seconds. Here I want to register
new function, the bones. And here we are getting
as an argument. First of all, some function, let's name it funk. And secondly our timeout. And it is a nice approach
to set timeout by default, for example, to
300 milliseconds. This means that it is not
mandatory to provide. And now inside our
debonding function must return a function. Because as you can see here, we're calling the bones function and process change is also a function where
inside we can provide some data for our
savory input function, which actually
means here we must return and you function. Here we want to spread our args. And let's check what we
are getting opposites. So here I want to console
log in function comma arcs, and we can see in what
format we are getting them. I'm reloading the page. As you can see, we're getting
four times because we call this function four
times in a function. And here we have just
a single argument foo. But this spread with
args transformed our arguments to
an array because for us is easier to
work with the array. The second thing that we want
to do is create a timer and actually a time of group want to store in the closure
here on the top. Here we can just let timer
without any default value. And now inside our
inner function after our console lot with just
wanted to write setTimeout. Here we will have a
function and actually the second parameter here
will be our timeout. After what time we will
call this code inside. What we want to do here
is func dot apply. Here will be this coma aurochs. What does it have a mean? We use here are
the bonds function and here we're providing
our Savior input. It's our func. Here is our timeout. So at this moment, this process change is
this inner function. And after we're
calling this function, we're calling this part. Here, we're getting
our arguments. In our case, this
is array with foo. Here we have our console log and this will
generate setTimeout, which actually means
every single line here when we call this function, will generate a setTimeout. With this timeout, what we are doing inside
where calling func. So we're calling this save
input with apply this args, which actually means we
want to call this function after timeout with
the correct context, with the context of this
function, with this arguments. But here we have a problem
when we reload the page. As you can see,
we're getting four times in a function and after two seconds by getting
saved input full four times. And this is wrong because
here we must get it on the ones because this
is actually at the bones. We must clear our timer every single time when we make
a call to the function, because in this case, our previous set
timeout must be ignored exactly for this we
created here lead time it. What we can do here, we can assign setTimeout
to the timer. And actually if you
don't know setTimeout, give us back a
number and this is our specific ID
that we can clean. This is why before our timer, we can now write clear timeout and inside we can
provide our timer. If it's undefined,
it doesn't matter, it won't do anything. But if we have an AD, then previous setTimeout
will be destroyed. In this case, every single time when we call this
function again, all previous timeouts will be watered and now we will
create a new set timeout. And after this time we
will call our function. This is exactly the
idea of the bones. Now let's reload the page. We're getting our inner
function four times, and now we're getting
saved input for just once after two seconds. And this is exactly what we wanted when we
implemented our debits. Once again, the bones
function allow us to call something only once
after specific time. This is really
important when we're talking about
something that user can call a lot of times during inputting in
the form, for example.
24. Implement Throttle Function: We successfully implemented
are the bones function. But you might also
get a question how to implement
throttle function. And actually they
are super similar. And this is why I have
the code from our bones function because
we really need to change like 1% of the code. So the idea of throttle function is that it will be
executed immediately. And just to remind you, the bones function will be executed on or
after our timeout. Here, throttle function executes it immediately, but after that, the column of the function is completely ignored
for our team out, which actually means if
user is typing something, we can call our function only at the beginning and
then every time out, so every two seconds,
for example. And this is exactly the
core purpose of throttle. To simulate it, we must
change our code a little bit. Here we have our Savior input. This is fine. Here is process change, but we don't want to use here the bones would want to
write it with throttle. The arguments are
exactly the same. And now here we call process
change at the beginning. This is totally fine, but now I want to simulate that we're calling
it with setTimeout. Here, we're right
and setTimeout, and we want to call this function process change inside it after some
time, for example, after 1 second, then I will
copy paste this setTimeout and run it after 1
second, 200 milliseconds. Now I copy paste it again, and I will call this
function again after two seconds and
400 milliseconds, and then I will remove two
last plot's has changed. Actually, as you can see here, we put timeout 200 milliseconds, which actually
means this function must be executed immediately. This setTimeout will be ignored. This will be also ignored and download the last set
timeout will call this function because
it will happen after this time out
of 200 milliseconds. Now first of all, let's change the name of our
bones to throttle. We're getting here
the same arguments, a function and our timeout. But now here we need not a
timer ID, but a Boolean. And this boolean will show us if we can execute this
function again. This is why not lead time, but lead, for example, is waiting and by
default it is false. Now here we're also return a function we don't need
here, clear timeout. And actually setTimeout
is staying here, but we don't need time
because actually we will forbid this setTimeout
with an if condition here. We can write if not is waiting, then we want to call
this setTimeout. In other cases, we won't call anything and this code
will be just ignored. Also, it is important that we call this function directly. This is why I want to
move it inside our if condition and
insights setTimeout, we simply change our weight
in property to false back. So as you can see, this line means that at the beginning
on the first call, we will call this function. But after this, we want
to set our flag to true. This is y here where I didn't
is waiting equals true. Then we have a set timeout, for example, two seconds. And after two seconds we're
setting is waiting to false, which actually means we
can call this function on the after two
seconds and not before. So as you can see, the
code is 99% the same. The main idea is that we're building here is
weight and flag, and we just allow to access this function once
in our timeout. Now let's check if it's working. I'm reloading the page, we're getting directly
saving put foo first time. And then we see on Louvain
CV input f2 second time. And this is exactly this
code process change and this last set time mode With two seconds and
400 milliseconds. Because actually here on our first try we are
going to throttle, is waiting, is false. We're going here, we're
checking a key, it is not true. Then we're calling directly this function and we're
setting our flag to true. And then after our
set timeout and then we're changing his
weight and back to false. And we don't need
here any time RED because we never
aboard our setTimeout. The next question
that you might get. Okay, but what is the difference between the bones and throttle? And as I already said, we're calling the bones after users stopped
to do something. We're calling throttle first
of all at the beginning and then after certain
interval of time.
25. Highlight All Words Over 8 Chars With Yellow: You might also get
some questions regarding how JavaScript
is working wisdom. For example, here we must highlight all of the
words over eight characters long in the paragraph texts
with yellow background. And as you can see here, I have index.HTML and we
have our paragraph, and we have our
heading paragraph, and we have quite a
lot of text here. If you want to try it yourself, I will link the source code
in the description box below. You should not retype
this whole text. This is how it's looking now, how we can implement
this specific task? First of all, we must
find our paragraph. This is really easy that we
have just a single paragraph. Here. We can say that
we're finding paragraph and here is document
dot query selector. And here this P and this you can see I used here
querySelector. And this is super important
if you will try to use getElementByID or
get element by class, this is not the
best approach and details that you didn't
work with Tom to match. This is why you always must use querySelector
or querySelector. Oh, if you want to get a
list of your elements, in our case we get
just a single element. This is why we simply write here p and we're getting
our paragraph. We could also write here a
dollar sign at the beginning, just like in jQuery style. For example, I
prefer to do it too easily distinguished
by the name, The difference between
just two elements and DOM elements. But for now we will keep
it just like a paragraph. But we want to do now Poupon to change our content
so our inner HTML, this is why we can write
paragraph dot inner HTML equals. And we want first of all to
read paragraph dot innerHTML. And as you can see,
this is how content inside innerHTML
is looking like. So this is just a plain
string and now we can work with it just like with
normal JavaScript stream. What we want to do now
here we want first of all to split it with space. In this case, we are
getting an array of words and now we can use map to
work with every single word. So actually here we are getting word and inside we want to check if our world is
longer than eight symbols. So we can simply
return here word dot length bigger
than eight symbols. Then here we want to
write ternary operator. And if we're bigger
than eight symbols, then coupon to
wrap it in yellow, which actually means we want to write another DOM node inside. This is where here I will create a string div with style
inside and inside style, we're right and background
color, for example, yellow. Here we must close our div
and actually dv is bad. We must use here span
because this will be an inland element
inside this span where just right in our world
that was there previously. So in this case we're
returning and you don't know. And if we didn't
change the world, then we simply return
this word back. As you can see in this
case, first of all, we take our string
inside the innerHTML. We split it by words
with space where mapping every single word and
we're checking the length. In this case I'm returning your DOM node or I am
returning the word itself. And after we're
finished with our map, we must join everything back. This is where here we're
joining with space, just like we did previously. Let's check what we are getting. I'm reloading the page. And as you can
see, all our words which longer than eight symbols, will be highlighted with yellow, which means actually
initial lines. We can solve this task. You can get different
tasks regarding DOM. What you need to know is how
to get elements from Dom, how to remove them from them, how to update them, and actually how to transform DOM elements directly to
JavaScript strings, for example. You can work with them.
26. Add a Link: Another dumb task that
you can get is add a link back to the source of the
text after the paragraph tag. And actually I have exactly the same HTML like perversely. But at the end, we must provide a
link to our source. How can we solve this? First of all, we must
create a new DOM element. Now in case it will be a link, then we will provide
insight graph, and then we will just append
it at the end of our DOM. First of all, let's
create a link. For this, we can use
document dot create element and inside the womb must provide what DOM element
we want to create. In our case it is an a after this boop want inside
linked to assign our graph. So we simply write link href equals in denial case I
will copy it from here. It will be HTTPS for ipsum.com. And we're also must
provide insight, an inner text which will
be a content of our link. This is why lync dot inner text. And here we're assigning text
generated from Lorem Ipsum. Our DOM element is ready. Now we simply need to put
it at the end of our DOM. We can write here document
dot body, dot append child. And here we're just providing
our new DOM element. In this case, it will appear
at the end of our body. Let's check this out. I'm reloading the page
and now at the end we have texts generated
from Lorem Ipsum, and this is a link and it is
going on the correct page.
27. Split Each Sentence to a Separate Line: Another task with the DOM
event can be like this. Split each new sentence to a separate line in
the paragraph text. A sentence can be assumed to be a string of texts
terminated with a period. And actually we have exactly the same text inside paragraph, just like we did previously. Now the question is how we
can implement this task? And actually we
might think, okay, we have period, we can
simply split it by period. Let's try this out. First of all, I
want to find here our paragraph with
document query selector p, just like we did previously. And now here we can write paragraph dot innerHTML equals
paragraph dot innerHTML. We want to split it with dot. And let's check what we
will have in this case, after we split it and we have
an array of our strengths, we must join it back. But in this case we want
to put here first of all dot because we are
joining in by DOD. But then we need a close tag for our p and open tag
for our new p. In this case, we are
writing paragraphs for every single line and join is not applied
to the last element. This is why at the end
we want to write plus, and here we must close
our additional p. Let's check this out. I'm reloading the
page and actually it is working but
only partially. Yes, it is working for
the simple sentences, but it won't work for the sentences where we
have two or three dots. For example, as
you can see here, we have lines with
one dot on it. And this is exactly the problem
because here we split it just by one dot and this
is wrong button total, our logic is correct. We can inspect our HTML
elements, as you can see, they are wrapped
correctly wispy, and then we're closing
our list p Here. It is working, but split
by a dot is not our case. Actually here we're coming
to regular expressions. And this is some knowledge
that you must learn, at least on the basic level, because you will use it in a lot of cases when
you are working, for example, with strings and to try and check
regular expression, I highly recommend you to
use a website, reg X.com. It is completely free. You can find another websites, but here it is really nice
to see what we will find. As you can see here, you can write a regular expression and here you can provide the text
and check how it will work. Also here on the right, you can set some flags, for example, multiline
global and so on. As you can see, this is
the regular expression that we want to write. And when I'm hovering
on the symbols, it will show you what
exactly we're doing here. This is the beginning
of regular expression, and we're wrapping
regular expression always with two slashes. This slash at the
beginning and at the end is just a start and end of
the regular expression. Now here inside we have dot, but dot is a special symbol
inside Regular Expression. This is why we must escape
it with the backslash. As you can see here, this is just matches a dot character. Now here we have
square brackets. And as you can see,
everything inside square brackets
is a negated set, which actually means
this must not be there. This current symbol is
the start of our set. And here we have
thought and open tag. In this case, we are looking
only for a single dot, but not for several dots. This is everything that
we wanted to say here. And as you can see here in our
code is working correctly. And now we have this matches
only with a single dot, as you can see here, we have
three dots, button move. The last dot will be checked because we
are interested only in dot when we don't have
the second dot afterwards. This is why we can copy-paste this regular expression and
just put it inside our split. Here I must write slash at
the beginning and the end. And this is our
regular expression. And I totally
understand if you don't get a 100% what I'm doing here, because you must learn some basics of regular
expressions first. But they're extremely important for if you're working
with strings. Now let's check if
this code is working. Here. I am jumping into
page I'm reloading, and now it is working correctly. We made our split. And here, for example, three dots are still there and this is the single sentence. And when we have a one-shot, then we simply
consider the split and then we move this
text on the next line. And actually regular
expression knowledge is a little bit
outside of JavaScript, but you will still use it a lot. But also, if you will learn
that regular expressions, you can use them in
every single language. Because in all languages
it is exactly the same.
28. Event Delegation: You might also get a question
like this implemented click onto the item
as fast as possible. And as you can see here
inside index.HTML, We have such markup. We have a UL list and inside
we just have li elements. Typically you can
solve it differently. Here we have two
typical solutions, but one is much
better than another. Actually, what we can do here, we can find dollar items with document and here we're
using query selector all. And here, as you can
see in our index.HTML, Lee with class item. Here I can find by
class our item, and here we're getting
a list of our items. After this, we can loop through
this list of DOM nodes. And for every single element
we can attach a listener it. Here we can write
items dot for rich. Here we have our item
which is a DOM node. And inside we can write
item dot addEventListener. Here we have our clicker
and here is our handler. What we want to do when
we're clicking on the item, at least tried some texts
regarding our item. Actually inside we
have just a value. This is why we can write here. You clicked on item and here we can just write plus
item dot inner text. So first of all, we found the list of our
items and then for every single item in the loop
were added event listener. Let's check this out. I'm reloading the page. We see our list of items. Now we're clicking on one
item and we're getting a nice console log with
the content of this item. We're clicking on another end, we're getting console log and actually it is working
and it is all fine, but we have a task to build
it as fast as possible. And actually here the problem is if we have a super huge list, then it's not performant enough. Because actually here
we have for each, for all our items, which means that we have
here a list of one hundred, ten hundred items where add in here one hundred,
ten hundred listeners. And this is super bad
for our performance. This is why this is not the
best solution for our task. What we can do, we can find
the parent or for our list. And as you can see here, we
have UL with class Todo app. This is where here
Let's find app element and we can use here
document querySelector, and we'll know that the
class is out to do app. Now inside we can attach just a single listener
for our app element. So AB addEventListener. Here we have our click and
here is our listening. And then right in here event, so we have access to our event. And actually what we
want to do inside, we want to check what
element we're targeting. Because we can click here on our container or we can click on any item inside
and actually very interested on the
clicking on the item. This is why here
we can write a K If we have here event target, which means we clicked and
we want to check here if our event charge it has
a class of the item, then this means that
we heated our LEA. This is why here
we can try it even touch it dot class list. Here contains actually
class list property inside the node has a function contains to check if
we have such class. In case we are checking if
we clicked on our item. If this is done,
then we can copy our console lock here inside and just change
it a little bit. We're leaving here our string. You clicked on item here
instead of item.name in a text, we can write event
dot target dot text, and it will work
exactly the same. Let's check this out. I'm reloading the page. I'm hidden here on some items and we're
getting nice. You clicked. And actually if we will
click somewhere outside, it doesn't do anything. But the main difference in
this code is much faster because we have here
just a single listener for our parent. And we're not generating hundreds of thousands of
listeners for every single item.
29. Xml HTTP Request: You might get an interview
the question, right? An example of fetching data from API with XML HTTP request. And actually this is
a super old question. And normally people
should not ask this question nowadays
and interviews, but still am here in this question a lot
because some people still want to know how we
solved our fetch and problems ten or 15 years ago. The modern projects,
you will never ever use XML HTTP request natively. This is why it doesn't make any sense to ask this question, but we must learn
how to answer it. This is why let's write an
example how it is working. First of all, we must
create our XHR request. So this is why we're calling
you XML HTTP request. Now we have an instance of
our XML HTTP request and we can say what method we
want to send and on what URL. This is why we're right
and XC chair dot open. And as you can see here, we have two parameters. First of all, it's method. Here we want to write GED because we're making
a GET request. And here is our API URL and
I will paste here and API URL from github comm to fetch all repositories of
this specific user. After this, we're right in XHR
dot cn and round brackets. But it is not all. We also must specify what will happen on success and on error. And for this we're
writing XHR dot on Lord. And here we must
assign a function. And inside this
function, first of all, you want to check what
status we're getting back. So we can write here
if xy chart that status doesn't equal 200, which means it is
not successful, then we want to
console some error. I want to write
here, for example, arrow last and maybe
XHR status glass, and here XHR status text. In this case, we
can directly see what problem we have in the other case
where getting success. So here we will write
console log success. And after this, we move on to
read our XHR dot response, where inside we have
our answer and we'll also want to check for the error inside
xy chart requests. So here we can write
xy chart dot on error. And just to remind you, everything is lowercase and we're assigned here a function. And inside we can
write, for example, console log extra
charge request failed. This is how you typically
define XHR function. First of all, we create an
instance of XML HTTP request. Then we make an open
with our method and URL. Then we will get sand, and then we have onload function
and on error function to handle both incorrect statuses or an arrow with a request. Now let's check if it's working. I'm jumping into browser
and reload the page. And as you can see here, we're getting our response
and we're getting our console log success
also in our network, you can see that we have a request wrappers and
this is XHR request. And as you can see,
this is our preview. This is our response
from the backend. And this means that we
successfully implemented our fetch request by
using XML HTTP request.
30. Fetch API: Another fetch and about
fetching data from API is a little bit
more up-to-date. This is what we're
using every day. Here you have a question, right? An example of fetching
data using Fetch API. He Pi is a modern way to
load some data from API. And actually here I didn't
remove XML HTTP request. You can compare code that we
wrote like ten years ago. And now here we can use
fetch function and we just provide an input and get is the method inside
fetch by default, which means here we must
provide just a URL. The most important part is that Fetch gives us back a promise. And this means that
we can use here then and catch to get some results. Here we've got our response, but normally we want to
convert our response to JSON. In this case, we can easily
use this data in client. This is where he'll book
on to cold res.json, which is an asynchronous
function and it will transform our
response to JSON. And after this, we
can call them again. And here we will get our data. Now inside we can work with
this data, for example, console log success,
and here is our data. And as you can see, this code is much smaller and easier to read then this old code
with XML HTTP request. And obviously here
we're also wrote an error and we also
want to handle it here. This is why here we
can write dot cage. Here we will get our era. And now here we can
write console log era. And this will be triggered
when we have an error. Let's check now if
this code is working, I'm reloading the page in the
browser and as you can see, we're getting a success. Here are our response. And as you can see
inside network, we have our rapids request
and the type is fetched. And here is our response, which actually means this code is working exactly the same, but it is based on promises, which means we can
easily mix this code was any other asynchronous
operations which are based on premises. For example, if you have two or three sources,
for example, if you have several
sources of data, you can easily
combine them together because they are all
based on premises.
31. Basic Callback: You might get another question regarding a synchronous
JavaScript. For example, write an
asynchronous function, which executes Kohlberg after finishing it's
asynchronous task. And actually if you don't
know in JavaScript, we're using callbacks
quite a lot. And previously
before promises and the single weight we used
callback for fetching data also even now Kohlberg is quite popular way to work
inside the application. So actually first of all, we wanted to write some function which will make some
asynchronous code. And the easiest
way to simulate in javascript asynchronous
code is by using setTimeout
because for example, where h and some data from the
backend and it takes time. This is why I want
to create here a sinc function and they
just name it a sink, a fan. And here we want to get our
callback as a parameter. And actually callback
is just a function. But the most important
part is that the asynchronous function
doesn't know what Kohlberg is. It can be whatever because
we're calling it from outside. Now inside we're doing
some asynchronous code. For example, we
fetch data from API, or in our case here we're using setTimeout to simulate this. And we have set timeout, for example, for two seconds. And then at the end book
one to call our callback. This is where we simply
call this function or sometimes with the data
as a result of our API. Maybe here we can
write Kohlberg done, and this is our asynchronous
function is ready. Now how we're using
this function, we just tried a sinc function and we're providing
our callback inside. This is a function which will be executed inside at the end. This is why here we can
say that we are getting a function with
argument message. This is what we're
getting back from our async function
in here we can write console log Kohlberg
and here comma message. Let's check if it's working. I'm reloading the page
and as you can see, we don't have anything now after two seconds we're
getting Kohlberg done. This is exactly how
callbacks are working. This is exactly what
we implemented. We have an asynchronous
function which executes Kohlberg after finishing
it's asynchronous task. And the second question
that you might get here, what problem callback solve? And actually there are
two important points. First of all, Kohlberg
allow us to make some synchronous staff
and wait for the result. Because actually here we're just providing a function from outside and it will be called
later and not immediately. This is the main purpose
of the Kohlberg. And secondly, it's
important to remember that inside our
asynchronous function, we don't know what Kohlberg, this is why we can
build shareable things. This Colbert can do whatever
in different cases. For example, on one page, book on to fetch data and
maybe render this data. And on another page, we wanted to fetch this
data and calculate the total number of posts
or something like this. Which actually means Kohlberg
is a generic function. This is why we can easily share our asynchronous
function without specific implementation
of our callback.
32. Parallel Async Array: Here is one more example
of a synchronous question, but a little bit more advanced, as you can see here,
we have a question. Execute the given list of
asynchronous functions in parallel and return the results as an array to the callback. As you can see here, we
already have three functions, and this is given with the task. So each function have
here inside the callback, which returns 123 most
important part here, that first function
is three seconds, then two seconds, then 1 second. Then we must write the
function as sink parallel. We're inside where throwing an array of
asynchronous functions, which means every single
function a callback. And then the second
parameter we have here, ONE Kohlberg for
a sink parallel. Here we're getting our result and we're console log in here. And we must get, in this case 123 because it must print
results or fissures, synchronous function in order, which actually means we're
executing three functions in parallel and we're waiting
for all of them to complete. And after this, we have the
correct order of the results, which actually means
we are getting results of every
single function. And actually we're using
parallel fashion, for example, quite a lot every day because
we want, for example, to fetch three different
requests simultaneously and then get all data in one
place and merge it somehow. This is y. Let's build this function now, but it's not easy and we really need to think
what we are doing here. We want to implement a
sink parallel function. And actually here we are
getting first of all, an array of our
asynchronous functions. So we can write
here I sinc ufuncs. And the second parameter
is our callback. And importantly this is a
Kohlberg for a sink parallel, not for the specific
async func function. First of all, here
I want to create an array where we
will put our results. Here. I can try to result array. Here we want to
write new array and inside a sinc
functions dot length. In this case, we are prepared in the empty array with
three elements. And obviously it is
three only for our case. And it can be any length of
our asynchronous functions. After this, I wanted to
create a results counter, and by default it will be 0 until the length of our array. Why do we need that? Because actually every single asynchronous function
can be ended in random time and we must wait for all these
function to complete. This means that we must
count how many functions are already completed until
we're rich in length. This is y here let's
create our result content. And by default it will be 0. And now we want to loop through our
asynchronous functions. So here I sync
fonts dot for each, and they really
using for-loop here. And we're getting access for every single
asynchronous function. And we'll also need here
an index because we need to store the results also
in the same correct order. Now inside for each, we must call our
asynchronous function. Most importantly, we don't know at all what this
function is doing. But we know that this
function gets a Kohlberg. This is why here we can
write our callback. We're calling a sinc function
without any arguments. And inside we're
provided our colon. If this codebook is triggered, this means that we are ready with our
asynchronous function. And now we want to write the
result inside our array. This is where actually we are getting in our callback value. And as you can see here
inside every single callback, we're getting a value. And this is exactly
the value that we get an inside our callback here. Now, we want to store this value inside
our results array. Here we can write
result array and here will be our index equals value. Just to remind you, we
have our index here. This is why we will know
that we stored it correctly. For example, this is
the third function and it will be triggered first, then we will write it
on the index tomb. After this, we must
increase our results counter to know that one
of the functions is done. And last but not least, we want to check here if this
function was the last one. Here, we can check if our result counter bigger or
equal a sink ufuncs, then we want to call our
Kohlberg for a sink parallel. So here we can simply
write callback and inside we're providing
our result array. Once again, what we're
doing here, first of all, we're prepared an empty
array and our counter. We're looping through our asynchronous functions
and we're calling every single function here were provided in every
function, a callback. When we're getting success, we first of all store our result inside result index and then
we increase our counter. In this case, we know that this logic will return
us Kohlberg for a sink parallel when we're ready and when all our functions
are completed. Here we're calling our
codebook width result array. Now actually we must move this function before our
call a sink parallel, because we must
write it with const. And let's check if it's working. I'm reloading the page
and we are getting an assignment to
constant variable. Let's check this out.
Yes, as you can see, a result counter can be increased because
it is const. Here. We can write LED and
then it should work. Let's check this out. I'm reloading the page. We don't have any errors. Now three seconds pass and we are getting our
array with 123, which actually means
here are a sink parallel who waits
for every single asynchronous function to be completed and then regenerate as a Kohlberg our result
here and now we can use here our array in
the correct order. And this is completely
fine if you can't build this function fast. Most importantly, if you are
doing it in an interview, you must always say our Cloud, what you are doing and
how you are thinking. Because normally an interview
it's not that important. If you solve this
task fully or not, you must show your
way of thinking and how you want to solve
this specific task.
33. Convert Callback to Promise: You might also get another question regarding
a synchronous JavaScript. Here we must create the
premise function to be able to use callback function
via Promise approach. And actually just for you
to know previously we had a lot of callback functions because we didn't have premises. Then after some
time in JavaScript, we migrated fully two premises, and now they're supported
in JavaScript by default, which actually means we're not using callbacks
that much anymore. And as you can see here, we have a standard
callback function where inside we're doing some assumption is cold and we mastered write this function
to promise approach, which actually
means, for example, we're using some older library which is based on the callbacks, but the whole code of our
project is using premises. This is why it makes a
lot of sense to make a rapper and to use this callback function
through the premise. To do this, we
must create a thin which is called
Promises phi function, which actually means
the same function but wrapped and promise. We can name it from me, Sci-Fi, and this is the typical name
and freed a sinc function, just like on the top. Here we don't have any arguments inside here we want to
call our async function. And when we have a codebook, then we want to call our
callback from the premise. This is where here we're
master return and you promise. Here inside promise we
have resolved and reject, but we will use here on Lou resolve because we don't
have any error here. Now inside our premise, we can just call the regular async function
and put a callback inside. And actually this callback
will give us some data back. This is why I am
writing data and we even don't know what
data we're talking about. Now inside we want just
to call the resolve and pass insight data from our
asynchronous function. In this case, when the
synchronous function is done, then our Kohlberg
will be happening. Here. Inside Kohlberg,
we're getting data from a synchronous
function and work colon in Kohlberg resolve for this premise
that we created. And most importantly that this function will
return a promise. This is why we can use it now, like this premise of
high async function, we just call it ended
returns as a premise. This is why we can write here. Then we're getting
some results and we can do for example,
console log result. We're using this function as
a promise and we've wrapped our sinc function in premise if phi, Let's
check this out. I'm reloading the page
and as you can see, we're getting back
one after some time. Because here we have codebook with 3 thousand milliseconds, which actually means
we're getting our data after three seconds and
this code is working. And now everywhere
in our application, we can use this callback
function in promise Approach.
34. Map Data in Promises: You might get
another typical task of mapping data with premises. As you can see here,
we have such feature. You have two functions
which return premises, metadata from users
and users statuses to get array of users with
AED name and is active. As you can see here, we have one array users
with a D and name, and we have a
secondary user stages with the dN dt is
active properties. And actually this AD is exactly
the same like a D here. And this is exactly the
data that we need to map. So we need to get an array
with a DNS name and is active. But the main point is that these data are not
available fast. They are only available here inside get users and
get users statuses. We have two functions
which are promises, and typically you will fetch
this data from the API. This is the way here get users will return false promises. This is why we're
resolving array of users here and here are the
same with user statuses, which actually means
we have two premises. We must resolve
them and combine. There are different ways
how we can solve this task. The most beginner
approach here is to fetch first premise
and then the next one. Let's try this. Now. We can write here get users, and this gives us
back a premise. This is where here
we can write then and we're getting
our users back. Now after this, we want to
fetch our getUser statuses. Here we're calling
getUser statuses, and we also use them here, and we're getting back
our user statuses. And now inside this
function we have access to users
statuses and users. Because here we will get only after resolving
both of them, but not in parallel,
but one-by-one. What we can do here,
we can map users, so we can create, for
example, mapped users. And we need to loop through
our users with map, we have access to
every single user. And now we need to find this is active property because this is exactly what we want
to put in our array. This is why here we can
write const is active, and here we want to find
inside user statuses, our status, this is
where here we're right and find users status. And here we need to
check user status. Dot id equals our user dot ID. But this will return
faster to the status and we must try it at
the end is active. In this case, we will get
on the specific property. Now after we got our executive, we want to put it inside
every single object, but we won't use here push because you remember pushes bad. This is why Google
simpler return here and you object and we're
spread in here. All fields of our user. Glass is active property. In this case, we're Putin is active property in
every single user. And after this, we can just
console log our mapped users here and they are available for us inside our application. Let's check this out. I'm reloading the page and
we're getting are met user. And as you can see,
this as an array with three objects, ID, name, and is active, which
actually means we successfully solve this task. But there are quite a lot
of problems in this code. First of all, we have two different premises and they are not dependent on each other, which means it doesn't
make any sense to wait for first premise and Don will
then make a second premise. We actually must do
them in parallel. In other cases, it is too slow. So I want to write here
that this is solution one and they want to
comment our first solution. Now let's try the
second solution. For the second solution, we can use premise if you
don't know what his premise. So this is exactly
what is helping us to do several
premises in parallel. We can write here promise dot o, and we must pass array
of premises inside. Here we have an array
and we can write here, get users and then comma,
get users statuses. In this case, we're throwing inside premise all array
with our two premises. And after premise
all at the end, we can just try it then here we will get our
result as an array, but it's not very comfortable
to work with array here. This is why we can
directly destructure here our array to
our two properties. Here we're getting our users and here we're getting
our user statuses. And after this, we
can do our logic, which we did here
with mapped user. This is why I will cut this
code was mapped users and just put it inside here because it will stay
exactly the same. Here we have access to our users and our users status SES, and we're mapping them and
console logging it here. Let's check this out. I'm reloading the page and we're getting exactly the
same response back. The main point is here
we used promise all. This is much better
because in this case we're making this two
requests in parallel. Also, as you can see,
the solution to, but don't have this bad
nasty with then and then, and here we have just a
single then this is obviously better because we want to
avoid this deeply nested code, but we can make this
code even better. As you can see, we
have this map to users and we actually can move this code outside of our Then just to make
it more readable. Here we can create
additional function before, for example, map users. And we know that we
are getting here our users and user statuses. And actually this is
completely pure function which will just map our users. So I can cut this code
and put it here inside. Here, we don't
need our constant. We can directly return our map. And actually this code will be exactly the same like
we used it previously. And now what we can do here, we can just create mapped users. And here we're signing
map users and we're passing inside our users
and users statuses. As you can see now this
code is even better to read because here we
have simply premise all. Then we're mapping
our users with additional function and
work on so Logan them. Let's check this out as
you can see over here, exactly the same response. And actually we can improve this function even
a little bit more, as you can see,
where I'm mapping users inside out with them. But actually we can
chain our dance, which actually means
here maybe we want directly to return
our map to users. So our first, then we'll just met with the users
and return them here. And after this weekend, right One more than, and here we will have
our mapped users, and here we want
to work with them. So here I will console
log our mapped users. In this case, we split two different dance mapping of the users and working
with success. And actually here with simpler
console log our users, which means this is our success. And we can even
remove return from here and write this
as a single line it, in this case it will
be even more readable. I would say that this code
is as dry as possible. This is why if you want to show that you are an
advanced developer, you must write your
code and try to improve it as many
times as possible.
35. Rewrite Mapping Data in Async Await: The next asynchronous question in JavaScript will be for sure a sink of aid here actually will master the
previous exercise, like mapping users with two premises in a sink,
a weight function, as you can see here, we have our users users statuses
and two functions, get users and get user premises. And actually I come
into doubt our previous code so we can copy parts of it. The first thing that
we must do here is create additional function. Why is that? Because you are not allow
it to write a simpler way directly in the root part of **** JavaScript file.
This is y here. First of all, we must
create something like get mapped users maybe because we want to make it
an asynchronous function. This is where here we're
using our async keyword. In here we're creating
our function. And this assumed keyword allows us to use
a weight inside. But we want to do
now we want to get our users end-users statuses. Here I can simply write users. Don't forget this weight here. We're just trying to get users. And if you forget here a weight, then here we won't
get our users, but you will get here a premise. And this is not what we want. We want to resolve our premise. The next line here will
be user status is, and here we want to get
our get use of statuses. And obviously, as you can see, this code is much, much easier to read
because we don't have any then we don't
have premise all. It looks like it is
simple synchronous code because the lines are
executed one by one. And after this, actually
we want to copy, paste our mapping and put
it here because we won't change it and it doesn't make any sense to create
additional function. Because inside this function
we have just two lines. This is why here we can
write const mapped users. Here we're assigning the
users dot map and we're making exactly the same stuff like we did in previous video. After the third line, we already have our map data. Here we can write console
log map to users. And here we can check
our mapped users, but also must call somewhere our get mapped users function. We don't need to write
here a weight or something because we simply call an
asynchronous function. Now, I will reload this page. As you can see, we're
getting mapped users. And this is our response, which actually means this
code is working correctly. And this code is looking
super readable because we used here a single weight
by this is not enough, but always want to wrap
our byte code a try-catch. Why is that? Because if here
we will get some error, then we will never see it. We will have an error
and caught premise. This is why here we want at the beginning to write try here at the end after our console log coupon to
close it and dry it here, cage and here we're getting
our error inside our cash. We want to write something
like console log Azure. And here is error
that we can get. In this case, we are on the
safe side and we'll know if some asynchronous code does not work in here or we're
getting some errors, we will then throw an
error here inside catch. Let's check this out. Our
code is still working and we successfully use
the singular weight to the right are
promises with it.
36. You Must Use Correct Vocabulary: One more important thing
to remember is quite tricky and people are not
talking about it a lot. And I'm talking here about
your programming vocabulary. What I mean by that, actually, there are lots of words that you can use when you are
talking about programming. So person understand you
better or at least correctly, and you should not mix them. There's a beginning. It might be really difficult for you because you don't know all these terms or you are not really sure what
you want to say, but you need to keep it in mind and try to improve with time. For example, you must really understand
what you are saying. For example, I
showed a function or I created a method
inside my class. This is an instance
of the class. You must use all these terms correctly if you see a function, but you are calling that method, or maybe you're calling
it something else. This is not correct. And then you will get lots of additional questions or you will be seen as a bad developer. You of course don't want that. This is why you need
to think a little bit what words you're using and try to use them
correctly when you are describing some
programming stuff.
37. Design Request Manager: Here is another
synchronous task, which is a little bit complex. So you need some
time to solve it. And you can't really solve it like in three
or five minutes. As you can see here, we
must design a utility which takes a URL and
the value for attempts, which will attempt to
make a fetch request. If we have a failure, then this function will try
again to fetch some data with increasing delay for number of times which
user has requested. Which actually means we must create a function
which will fetch a specific URL that we will provide and also have
some amount of attempts. And we want to refresh
this data again and again for several times if we
didn't get a success message. And actually this is a
really common problem because sometimes our API is not working or data are not there and we want
to try it again. Let's try and create this function and
they want to name it, for example, request manager. And actually here we will
get our URL because we want to fetch something from the outside and every
time something new. And here we have some
options for our URL. And the last parameter
will be attempts. And by default it may
be three, for example. So we're trying to refresh
some staff three times. This is how we will use this. So we have here request manager and were provided some URL. They will use here some
URL which does not exist. In this case, we
will refresh it. We have foo.com and this function must
return faster premise, this is where here
we have, then, here we have success and error. This is where here we're waiting some response and we can
just try it console log, for example, response to
check if it's working. This is how we will
typically use this function. We want to fetch some URL
and we simply have them. And obviously here we
can pass some options. For example, method
post and somebody, or amount of attempts if
we wanted to change it, if we didn't pass anything, then here we don't
have any options and our attempt is three. Now the question is what
we want to return here? The most important point to understand how we will build it. We will run this function
recursively because this is an easiest way to call this function several times, is that we will call in the cage request
manager again here. And we will simply
provide here inside URL options and then attempts, we will decrease, which means that at the beginning
we have three attempts. Now the next time it
will be two, then one, and then we will throw
an error because we don't have any
remaining attempts. So first of all, we must return a promise because this is
what we're waiting outside. And this is where here we're
returning, you promise, and here we have our
resolve and reject. Now inside this function, we want to try and
fetch our data, and we will simply use
here fetch function because it is available
for us natively. Inside we're passing
first of all our URL and secondly options. And now here we have our, then we have catch and actually on then we can simply
call our resolve. This will pass the success
data directly inside resolve, because Resolve is a function. Here. We also want a catch. Here inside the cage. We want to do our matrix. So here we're getting
our error and we want to call our
request manager again. But here we must know when
I'll attempt is the last one. So here I want to create a
property is last attempt. And here we can just check
if our attempt equals one. In this case, we
will know, okay, this is the last time when we can call our request management. And after this we are checking
if this is a last attempt, then we want to
return reject arrow, which actually means
we're just rejecting our premise because we can't continue anymore after this EQ, but don't have 0s last attempt, then we want to make
setTimeout because actually we want to call this
function on after some time. It doesn't make any sense
to call it directly after, because maybe API is still down. Here. I will write setTimeout, for example, with three seconds. And obviously we can also
implement an argument to pass the interval
to call data. Inside setTimeout, we want
to request our data again. So here we will call
request manager and we're passing here
URL now options. And the last one will
be attempts minus one, which actually means we don't
start attempts anywhere. We simply provide recursively in request manager decreased amount of attempts. This is y here on the
first time it is three, then we're coming
here in setTimeout. It is to one. And then we check this
attempt equals one and we're here inside this IV
and we're rejecting it. So let's check if it's working. I'm reloading the browser. And as you can see,
we're getting get and an arrow because this
URL does not exist and we're getting attempts
is not defined on line 13 inside our set timeout. And actually the name of the argument here
is not correct. It's not attempt, but attempts because we
have several of them. And also here it should be attempts equal one
and not attempt. Let's reload it again. As you can see, we're
getting get header. Then after three
seconds we're getting this request again because we try it again and then again. Here we have uncaught
error failed to fetch, which actually means here we
must write not only them, but also cache, because
here we will get an error if we can't fetch data. And here we can just try
it console log error. And here we want
to see our error. But as you can see, we still get an error unquote type
pair of failed to finish, which means our code
is not a 100% correct. And actually the problem is here that this is our first call of request manager and we're handling it outside
with then and catch. But here instead setTimeout
we have request manager, but we don't have then and catch this is why
it is breaking. We have an error
in our third coal, and this is here, but we didn't specify what will
happen with it. This is what here,
boom, must write. Then here we want to
resolve it with data and also catch and on cash
we simply want to reject. In this case, it
will work correctly. Let's try this out. I'm reloading the page. We're getting through
errors and now our error is bubbled outside and we see
TypeError failed to fetch. In this case, it is
working correctly. You should not forget to bubble our inner request manager
outside with then and catch. So I may say this function
is quite complicated. So if you receive something
like this on the interview, you really must take your
time to solve it correctly. You can't really design such function in a
matter of minutes.
38. Implement Shallow Comparison: You might also get a
question regarding equality or comparison
inside JavaScript. And as you can see here,
we have a question, designers shallow
comparison function. For this, you must know the difference of
JavaScript comparison, which is native, shallow
comparison and deep comparison. Inside JavaScript, we can
simply write one equals two. We are getting false.
One equals one is true. This is working because we
are comparing primitives. But if we will
compare here a equals one and here is an object a equals one, we're
getting false. Whereas that because we can't compare objects like this in JavaScript because
they are referencing different objects
inside the memory. And you have exactly the
same problem with array. Empty array does not
equal empty array. Yes, we can understand why
it is working like this, but it is not
comfortable because normally developers
want to compare arrays and objects by values and not like reference to the
object in the memory. This is why we have
shallow comparison and deep comparison functions. So the idea is that shallow comparison is faster
than deep comparison, but it will fix problems with comparing objects or arrays. It will fix only not
nested arrays are objects, which actually means if we
will with shallow comparison, compare a, and here we have an object with B1 and here B1, we will still get wrong answer even with shallow
comparison function. This is completely normal
because in this case, we want to compare every
single value nested, and then we must use
deep comparison. And deep comparison is extremely slow because we're checking
every single value, but it will for sure I
give you a true answer. In this video, we must write a shallow comparison function, which means we want to fix comparison of
arrays and objects, but we must not compare
nested arrays and objects. This is how shallow
comparison is working. And actually here I have an
additional function type of which will help us tremendously in building
shallow comparison. And as you can see in browser, we can simply use typeof on
different types of data. For example, for number, we're getting
strained number for string word versus
getting a string. And here we can write an object and then we
are getting an object, which actually means
it is really nice to get the type of our
variable as a string. For us, the most
interesting part is this object prototype
to stream call input. And as you can see in
the input where for example one and we're
getting object number. And actually this
regular expression here will simply move object and we will get
this part with number. This is how this
function is working. Here I want to create our
shallow compare function. We must provide
here two arguments. So we have source and target, and these are two things
that we wanted to compare, for example, two variables. First of all, we want to compare a datatype because if we
have a different datatype, then we should not do anything and it means that
they are not equal. This is why we can write here. If typeof source does
not equal typeof, then here we can
simply return false. This is why it is
super performance. We don't compare anything. We simply get a type
compare them and we're out after this boom must write
logic for our primitives. And here we can simply use plain native
JavaScript comparison. I am writing here if source equals with three
equals stylesheet, then here we're just returning, which actually means
this single line. We'll compare or primitives. And now we just need to build cases for our
objects and arrays. First of all, let's
cover our arrays. Here we want to check type
off our source equals array. Then we want to
apply this logic. And you might ask, okay, But why we're just checking
source and not a detergent? Because actually
here on the top, we already know that both source and target
of the same type. In other cases, we're
already out of the function. Here. We know that source
and target are both arrays and now we
want to compare them, but actually we can make some
performance improvement. Here we can compare just
a length of two arrays. And if they are different
than we should not compare anything because
they are not equal. So here I can write IV, source, land does not equal
our target length. Then we're out here,
simply return false. Now we want to compare
these two arrays, and the easiest way to
do it is to use average. We're checking every
single element inside an array and compare it. Here I want to write
return source every, so we're checking every
single element of the source. And here we have access
to element and index. And what we can do right here is our element equals target index. In this case, we are comparing
every single element of our source with every single
element of the target. But as you can see here, we're using native
JavaScript comparison, which means it will
work for primitives, but it won't work, for example, for objects or arrays,
how does it look like? Let's reload the page and right here our function,
shallow compare. And we can provide now
array with primitives. So here we have 11 and
we're getting true, which actually means
our function is working correctly because the
native JavaScript you can't compare 11, it will be false and our
function is working correctly. Now we must try the similar
code for our object. This is why here we can write if typeof source equals object, then we want to apply our logic. And again, I want to improve
performance. This is y here. First of all, we can
check, for example, object keys and
compare the length of the keys if the length is different than this objects
are for sure different. So here we can write
object dot keys. Here we have source and
we're comparing the length. So here length does not
equal our object dot keys, and here we have our
target dot length. In this case, we
can simply return false and we should
not do any comparison. And actually here now would
need to compare objects. So for this, I will
also use every. So here I want to return
our object dot keys, and I'm getting an array of strings of keys of our object. And here we're
providing our source. After this, we can use every and here as an
every single element. We're getting our key. Now we can compare source key. So we're getting
the value and we compare here target key. In this case, we are comparing every single value
of our object. But as you can see with
plain JavaScript comparison, which means it will
work for primitives, but it won't work for deep nested elements.
Let's check this out. I will reload the page. Here is our shallow compare. In this case, we want to compare object a and object
that you want. And as you can see
here, I have some typo. Here is not source. Let's change this. Now as you can see,
it is working and we can compare our objects. And actually now I want one
more comparison for dates, and this is extremely
easy to do. Here. We can try type of
source equals state. Then we want to compare just two numbers because
actually we can compare every date two milliseconds and compare numbers is
extremely efficient. This is why here we can write
return source dot get time. This will get milliseconds
equals target dot get time. And in this case we
are simply comparing two numbers and this
is totally fine. This is how we're building
shallow comparison function. And actually this is
how I want to see comparison by default
in JavaScript, but unfortunately
we don't have it. This is why we must build this function on
our own or use it from some library like Rumba
la dash or just NPM package. If you're answering
such questions about shallow comparison, you must say that it is super performance in
comparison to deep comparison, but it can't compare
nested elements, which is totally fine. And you just need to know for
what case you are using it.
39. Implement Deep comparison: In previous video we wrote the function shallow comparison. But you can also get
a question, Okay? But how we can write the
function for deep comparison? This is what we want
to do in this video. Actually, as you can see,
I didn't remove any code. I have here a type of and shallow compare and they want to copy-paste it fully and compare later with
deep comparison. This is why, as you can see, I copy pasted the whole
function and they just want to rename
it to deep compare. And actually the code will be 90% similar because
first of all, we want to check for
datatype and it is stay the same and
that the end we will compare date and source and target for primitives
in the same way. So actually biomass
just change comparison of our arrays and objects and actually
even the code inside will be almost the same. So first of all, for race,
we're checking length. Here we have every, but here we must remove
our comparison of element because it is
native comparison. But here we want recursively to check
every single element. This is why here we
can simply write deep compare and we're throwing inside our element
coma target index. In this case, what we're doing, we're colon deep compare again. And actually here it might
be that we have an object, then we're coming recursively
and say deep compare. And we will compare the subject and we're
doing it again and again until we compare the whole object or
the whole array. And it doesn't matter how deep the subject is or how
deep this arrays, which actually means
this is not performance. This is really slow, but it will give you the correct answer when
you are working with nested data and exactly the same we must do now
with our objects. Here we can leave our
comparison with keys. This is totally fine. Here we have our Every, but we must remove this comparison and call
deep compare instead. And we're passing
inside our source key and here target key. In this case, we are comparing two values of our
target and our source. And we're also do it
with deep comparison. And this is actually, it
will fully transformed our shallow comparison
function in deep comparison. Let's check this out now, I will reload the page here, the shallow compare A1, A1, it is true, but actually
here inside shallow compare, if I will throw a B1, so we have a nested
object and here a B1, it will return false, which actually means
shallow compare can't work with nested data. But here we're calling our deep compare and we're getting true because dip compare is recursive and it
will compare n in estan correctly in exactly
the same we have for a race. For example, if we have
here an array of arrays, let's say array with array one. And here we have array
and array one inside. As you can see, we're
getting through and we can compare arrays of any level.
40. Create Memoization Function: You might also get a
question about memorization. Here as you can see
where mask design a memorization
function which adds ten to provide value and take it from cache if it was
all the calculated. If you don't know what term memorization in
JavaScript means, it means that we're
caching values to avoid making the
same operation again, which actually
means, for example, we want to subtract two numbers. And if we did it previously and we're already
know the answer, then we must just return the sensor and not
calculate it again. Obviously it doesn't
make sense to make it we subtract or some, but it makes a lot
of sense when we have some difficult
calculations. This is why here we must build an example of
memoization function. And actually it's
not that difficult. So here I want to create
a function memorize, add. Instead this function. We
don't need any arguments, but we want to create
a cache inside. This is why here I will
create cash property. This is just an object. Now here I want to
return a new function. And you can see that this is
a closure because actually we can store on with some variables when
we have a closure. This is why here I will return
the function with value. Now here is how we're
using it outside. Here we want to create new add function and we
just call him MIs add, in this case, new AD user
function and we can use it. This is why here we
can write new ad, for example nine, and
this is our value. And doing this case
will be output 19 calculated by 19 because actually as you can
see in our future, it must add ten to
our provided value. We're throwing inside nine
and we're getting back 19. But actually when we're calling new ad with Snyder, again, the output will be also 19, but it should be
taken from cache. It should not be calculated. Again, this is exactly what
memorization is doing. Now we just need to implement
this memoization logic. So here we can write if
we have a value in cash, so we're checking if we have such valid inside our object, then we want to just return it. And here I want to
write console log so you can see that
it is minimized. Here will be fetching from cash. And after this, I want
to write return cash. And here is our value. As you can see, we don't
do any calculations here. We simply return value
and we'll also have else. And here we have
calculations were right in here
calculating results. And after this, we must
really calculate it. So let's create here a
value, for example, result. And we want to put
here value plus ten. And after this we must put it in cash before we return it. In this case, we're storing our result for the next stripe. This is where here we can write
cash value equals result. In this case, we are assigning
cash for our number nine. In this case when, when
next time right here nine, then we're getting
the value from cash. And after this, we can
simply return our result. And this is just the value
that we calculated here. Let's check this out. I'm reloading the page. As you can see, we are getting
calculate end results. This is our first try
here and calculated 19, which actually means we
really calculated something. But the second time this coal, we have fetching from cash 19, which actually means we
didn't calculate this time, this number, but we
took it from cash. And this is how you typically
implement memorization. You can get different task, but the idea is the same. You have some cash, you have a closure, and you must deliver the
value from the cache and put it in the cache
on the first calculation.
41. Fibonacci: Welcome into some really
hilarious questions, because this stuff
you will never use in your everyday life
like a programmer, but you must know
how to solve it. And the first one here, which is my favorite design, a function which returns if Fibonacci sequence
value and they didn't try to function to get the Fibonacci value
in the last 12 years, which actually means
it is not needed. But I am constantly hear this question again and
again on the interview. And actually I think
that it is totally fine to ask the interviewer. Okay, I don't know a
formula for Fibonacci. Can you please save and
then they can code it. It's not a problem. This is totally fine
because you should not know by heart all
mathematical formulas. This is where here actually
you can get something like this as a result
for your question. So here you can see
that Fibonacci sequence is an integer sequence
where the first two terms are 01 after the next term is defined it as a sum
of previous two terms. And the else term is the sum of n minus one and n minus two, which actually means this is a typical start of the
sequence we have here 0112. And as you can see
here, we can sum for example 11 and we're getting to here with some 12 and we're getting three
and so on and so on. So how we can solve this, we must provide an R function, a Fibonacci sequence value, which actually means the
index in the sequence. For example, if we will
provide seven as an argument, then we must get here
at band-to-band, because actually we will sum
up 813 and we're getting 21. Now let's call this exercise. And actually here we
will use recursion because we want to
calculate it recursively. Here we can create a
Fibonacci function and we get here n, which is our index here. First of all, we must check
if it is less than two, because in this case
our logic bonds work because here we have 01. This is where here
we must check, okay? If n less than two, then here we want to return one. In other cases, we
must apply our logic. Here we simply return Fibonacci, and here we're
passing n minus two, which actually means we
calculate this function recursively and every single
recursive call of Fibonacci, we'll call it again and again until we will come to
this first condition. Here we have
Fibonacci n minus two plus Fibonacci and minus one. And actually this is the whole
code that you must try it. Let's check this out. I will just jump into console and right here Fibonacci seven. And as you can see,
we're getting 21, which actually means
our code is working. But here's some important
stuff to remember. As a programmer, you
must know how to convert mathematical
formulas or some logic. In JavaScript, functions are functions in any other language, but it's totally
fine to not know by heart all mathematical formulas. This is why you should not
afraid to ask about them. And secondly, I
think it is totally fine to ask in return. Okay. I can't really coded, but are you using this stuff every single day
in your project? And probably you will
get an answer no. This is why actually
it doesn't make any sense to ask this
stuff on the first place.
42. Palindrome: One more popular question
that I'm hearing a lot is please write a function
to check the palindrome. Because actually this is what programmers are doing
every single day. They're checking palindromes. But whatever we can solve it. Actually, if you don't
know what palindrome is, this is a string which is the same from the beginning
and from the end. For example, if you
have full string, it's not a palindrome. But if you have, for example, for o full string, it is a palindrome because it's the same strength from the
Stat and from the end. So let's try this now. And actually it is really easy. What we want to do here, we want to create a
function is palindrome. And what we want to do with
one to solve with wisely. And actually it doesn't make
any sense to split it by letters and check every
single letter and so on. You can simply reverse
a string and compared. This is why here we can
write that our string equals and we can compare
it with string dot split. And here we just provide
an empty string. So we split it by letters
now with just make reverse, reverse in our array and
then we're joining it again, which actually means
where the reverse in this world and we're
comparing two same words. In this case we will get the same string if
they are equal. Let's check the South
here where right in East palindrome and we're providing insight full
and we're getting false. But if we will write foo, foo, then we're getting true. The task is solved.
43. Anagram: One more question that I
hear often is to write the function which checks
that string is an anagram. And actually this stuff is super similar to palindrome,
as you can see here, anagrams of words that have the same characters
in the same quantity, which actually means two
strings are anagrams if we can rearrange strings
and get the other. And here are some
examples of anagrams. For example, listen
and silent and so on. So now let's write the
function is anagram. Here we have ys
anagram and we know that we are getting
here two strengths that we want to compare. Let's name it's 31
and stream two. So what we want to
check here is that these two strings have
the same letters. But in order to check this, we must adjust sort our strings. In this case, we can simply compare the strings by equality. But first of all, I would
like to check here a length, because if we have different
length in these two strings, then it won't work. This is why here, if length of our first string does not equal the length of
our second string, then we just return false
and we don't check anything. And of course here
should be bank and not equal because we want to check
that they are not equal. The second thing that we
want to do is convert it to lowercase because actually
we can have different case, but the strings are
still valid. This is y. Let's name it lower strand one. And here we simply called
string1 to lowercase, and we have two lowercase
directly inside JavaScript. Here Let's name lowest string, and we're convert
string to lowercase. Now what we want to check, we want to check if these
two strings are equal. In this case, we mastered on false because they
are not anagrams. This is why here I
will write the flow of string1 equals
lowest string two, then this is false and
this is not an anagram. And the last one we
must write our logic. And what I want to do, I want simpler to convert
our strings to array than certain array and merge it directly back in string
for this weekend, right? For example, sorted string one, and here we will write
lowest string one dot split. And here we want to
split just by letters. And here I am just calling
sort without any arguments. It will be sorted in some way. And after this **** one to get a string back, this is y here. Join will get us back a string. I want to do exactly the
same on the second string. And here now we can
compare them because in this case we sorted all our letters in
the same direction. And now here I can
simply write return sorted string one
equals sorted string. In this case, we are comparing two strings which were sorted, and we already know that it is enter Chrome if they're equal, let's check this out. I'm jumping into browser and
we're writing is anagram. Here, we're just
providing full and Byron. And as you can see, it is false because these are two
different strings. But let's now try with listened
and silent. For example. Here I am writing lesson, and on the right I
am writing silent. And actually we are
getting here true, and it is working what
we're doing here. First of all, we're checking
if the length is the same. Welcome in here, we
have two strengths, lowercase, so we're not here. And now we're just
certain these two strings which were
converted to our arrays, and then we're converting
them back to strings. In this case, we're getting
something like E and St. but it is totally fine because we want
to just compare them. And this is how you are writing function to compare anagrams.
44. Finding Vowels: You might also get
a task like this. Write the function which
counts vowels in the string. And it is not always vowels, but something that you
must count in the string. And actually it is
not that difficult because the main idea
is that first we must define something like array of possible wobbles
or possible symbols. And then just try and check every single letter inside our strength. Let's do this now. First of all, here
we want to create a function phi and vowels, and we're getting here
string as an argument. Now second liver must
define what our vowels. Here we can create vowels
array and let's define here a, e, I, o, and u. And we can solve with, with two different ways, either with for-loop
always reduce and actually both
are fine. Here. First of all, I want to create a counter because we want to increase it every single
time when we find our vowel, would need a for loop. So here we can write
lead character off, and here will be
string to lowercase. In this case, we
get an access to every single character inside our string and we can check, okay, if vowels
includes our character, then we want to
increase our counter. So here will be
count plus, plus. And after this for-loop, we just return our
account that we created. Here. Let's try to find the bowels and we
have some string, as you can see here, we're
getting three vowels because we have
here e three times. And actually I would say
that this code is okay, but we can write it
better with reduced. This is why I wanted to comment
out this lead count and follow-up directly
here, return a reduced. So here first of all, we want to convert our
string to lowercase. So here we can just try
string to lowercase. And after this, we want to
split it in characters. This is y here will be
split empty string. Now we want to call here reduce
and we're getting access, first of all to our accumulator and secondly to every
single character. After this function, we want to define our count
and it will be 0. Inside are reduced. We want to do exactly
the same logic. We can return here
that if our vowels array includes character
that we're checking, then we want to
increase our counter. Here we're increasing our
accumulator with plus one. In other case we don't increase it and just return accumulator. Let's check the salt
I'm reloading the page here is the same string
and we're getting three. Actually this code is better
because first of all, we can read it line by line. And secondly, this fully
pure and functional.
45. Convert to Title Case: You might also get a task to convert your string title case. And actually it may be tricky. This is why it is
really good that here we got provided test cases. So actually we must build
a function title case. And when we're provided
inside I'm a little teapot. We should return a string and
it should be capitalised. And as you can see,
every single word here is capitalised, not only the first word, and this is important. Also. It doesn't matter
how we provide our string, it must be capitalized
correctly. Let's build this function now. And actually again, we have two possibilities here we
can use for-loop over, can use native
JavaScript methods. So first of all, let's
write it by using for-loop. Here we're create
entitled case method and we're getting
string as an argument. First of all, we want to
create here an array. We have every single
character here. We can write here
that our string equals string to
lowercase split, and here will be one space. So actually here we're
writing array inside string. And actually I'm
writing code like this because I want to show you how you should not write your code. And it's not just about logic here that we're using for loop, but regarded what you are doing, as you can see, first of all, the bad practice here is to use the same argument
like we have here. Overwrote our argument inside, which means first of all, we might modify it. Yes, it's not the
case with the string, but it will be like this. With arrays are objects because we're more
defined in a reference. Secondly, here we're
getting back in array, but here we're writing
it in such stream, which makes it confusing. And both these things you must not do in your code
or in interview. Because with this
you are showing that you are writing embed code. So much better approach
here will be to create additional property array
or whatever you want. Here we're getting a string to lowercase split and
we're totally fine. After this, we must
write for loop here we can just write
plain native for-loop, which I also don't advice. So here we can write
var I equals 0, I less than string length. And here I plus, plus. And of course here is not
stream but our array. So here inside now we can
mutate every single elements. So we can write here
array I equals, and here we have the same
element dot character at 0. And actually what it does, it takes the first
element of our stream. In our case, every
single element of our array is a string. And here we're getting the
first letter so we can capitalize it was this
way right into uppercase, which is also a native
method inside JavaScript. And here we can write
a i dot slice one. And in this case we're getting all our elements of the string except of
the first letter. This is what we want.
We want to capitalize the first letter and then just take all the other letters. And after this, we can
simply join back our array. We're right in here,
return array join, and we're joined
in, in by space. Now we can write
here console log, where colon here in case were
provided inside our string. I'm a little teapot. Let's check if it's working. I'm reloading the page and by getting I'm a little teapot, which actually looks fine
and we solve the task. But first of all, we
used here negative four. And as I previously said, it's not the best
approach if we're looping through every single
element of the array, at least you must use for rich, for array and not native four, then your code will be better. Second thing that they don't
like here is that we're overriding every single
element of our array, which actually means we're
not creating new array, but we're overriding
the previous one. And it is also not the
best approach. This is y. Let's rewrite this whole code just by using plain
JavaScript methods. Because actually here we don't
even need FOR loop at all. What I wanted to do
here, I want to take our string and I want to
convert it to lowercase. This was totally fine. After this, we want to
split it with space. This was also totally fine. But after this we
can use map because essentially what we're
doing here is a map. We want to change every single
element inside the array. This is why I am calling map and we're getting
here our board. And actually as you can see, it is more clear
now because we're using property world and not some AI or array where we don't know what
we're talking about. And here we want to do exactly the same word
dot character at 0. So we are getting first element. Here we're using to uppercase, and here we're using plus, and we're taken all
other letters with word dot slice and here is one. And as you can see, this code
is essentially the same. We didn't change
it, but it is much more efficient, easier to read. And it shows that you are
more advanced developer, because here we're not
using for-loop but map, which is not that difficult. And here we're
just returning for every single word in your work. And it is important here to
mention that character add and slice not mutate
in functions, which means we are getting
youth stream and we didn't mutate Alt stream.
Let's check this out. I am the Lord in this
page and we're getting our array whisk
capitalised strings, which means I forgot at the
end to make our giant here, we can simply call I would
join with space inside. Let's check this out and we're getting exactly the same string. So I highly recommend you on the interviewer to
watch your naming, to check that your
datatypes are matched with your names and make your code easier to
read if it is possible.
46. Convert the Time Input Given in 12 Hours Format to 24: Here's one more task which requires a little
bit of thinking. And as you can
see, we must write the function which can convert the time input given in 12 hours format to
24 hours format. Here we have use cases. This is why it is
easier for us to check if we're covered
everything correctly. So let's try to
create this function. And once again, this
is not a function that you can solve
in thirty-seconds. So you can take your time and think about it a little bit. Let's create here convert
to 24 hours format. And we're getting
here time text. And actually what I
wanted to do here first, I want to convert
it to lowercase, because actually here
we will get AM and PM and we want to be sure
that they are lowercase. This is why here we can
try time to xt lower. And here we want to call
time text to lowercase. The second thing
that I want to do is get hours and
minutes separately. What I want to write
here is time tech slower split and we want to split it by column
because actually we have colon in
every single case. And on the left we
have our hours, and on the right
we have minutes. And actually here I want to make a destructure and
assignment here directly. I want to get first of all our hours and
secondly minutes. In this case, we are creating
two local variables. If you don't want
to write like this, you can name it with some
temperature T variable and then just read this temporary
variable dot hours and minutes. But here we come to
difficult stuff. As you can see,
sometimes we have just a single digit and
sometimes we have two digits. But also we have a case where we have zeros at the
beginning. Here. We also have one more case
that we need to cover. If we have here 12 as ours, then we must convert
it to zeros 0. This is why I wanted to
write exactly this logic. So Eve time tick slower dot and width and
actually ends with Israel. A nice function in
JavaScript which is checking the tostring is
ending with something. Here we can check for AM because actually we
know that here we have 12 AM and it means that we
must convert it to two zeros. This is why here I want
to write ours equals, and here we're
checking if our hours equals 1212 as a string, because here we're
split in our string, then we want here to get 0. In other case, we are
getting here hours. And as you can
see, first of all, I wrote here a single
0 and not two zeros. And this is also important. Here I just directly
assigned hours, which actually means we covered this logic to get a single 0 and in all other cases
would just get what we get. If it is five,
we're getting five. If it is 01, we will get 01. We covered our AMK is now
I wanted to cover PM case. This is why here we
can write else and even maybe else-if because
we want to check for PM. And here we can write time
tech slower dot and width, and here we are getting our PM. And in this case we want
to apply different logic. We want to assign
here our hours and we want to check if
our hours equals 12, because this is
again another case. In this case we want
to apply here hours, or we want to write
here string and inside plus hours last 12. This code is doing a tall,
as you can see here, I wrote plus hours, what it does actually, we're getting our
hours as a string. So let's say that we
are getting here 12. Now if I will write here
plus at the beginning, we're getting here directly
number from a string, which actually means we
are converting this to number and then we make plus 12. Why is that? Because let's
say here we're checking PM, for example, this case with 01, and here we're checking, Okay, hours equals 12, No, Then we want to
make 01 plus 12. Let's check the South
how it will be. So we are getting here 01 and actually it is
converted to one. And now after this
we're getting plus 12 and we're getting into tin, which actually
means by adding 12, we're converting it to
the correct PM time. And if we have 12 PM like this, then we simply leave it like 12. So actually here we
could write 12 over, could just take our hours. So what I want to do now, I want to check what we're
getting inside hours. So here I want to console log our Convert to 24 hours format, and here is our time
texts and our hours. And now I want to copy all
these cases and just run them. In this case, we can check that they are working correctly. I'm reloading the page
and we're getting assignment to
constant, variable. And as you can see here, we're trying to overwrite ours. And of course it's forbidden. This is why here
we must write LED. Let's check this
out. I am reloading and we're getting
412045512120113. Here we have PM 11231022, which actually means our
logic for hours is correct. After this, we must add a
leading 0 in this whole cases. And as you can see,
sometimes we don't need it and sometimes
we must had it and we can easily solve it with one more plain
JavaScript function. We can write here,
ours dot pad start. Here. We can provide to 0. What it does is you
can see here it pads the current string with another string multiple
times if needed. Which actually means here
we're providing tool, which means we will have two
symbols and here we have 0, which actually means if we
don't have a symbol there, then we will put 0 inside. And actually now I want
to copy this part and just put inside our console
log to check if it's working. I'm reloading the page
and as you can see now, we're getting correct time. So here we have two zeros, 05, and then all are
correct numbers. Now we must implement our minutes and actually
it is much easier. First of all, just
to remind you, inside minutes will also have PM and TM and we must
get rid of it. This is why we can write
here directly means dot slice and here we're
using 0 minus two. In this case, we will
get rid of two symbols, AM or PM, and we will
get just minutes here. And after this, I want
to use PET strand, just like we did previously. And here will be also 20. In this case, we
will check, okay, If we have here eight, then we must get
here pseudo aid. If we will have here two digits, then it is totally fine. Now we can just remove
this console log, but don't need it anymore. And actually here in
every single case, I want to write console log. This is y. Let's change this. Now. I want to write here
console log, then open it. And here we have convert. And let's close it was bracket. Now we have all our cases. Let's check them
out. I am reloading the page and we're
getting our time, and it is looking totally fine
actually here for example, we have minute zeros 0
through 35508 and so on. But the problem is that we forgot to put a
column between them. This is where here
we must write plus and between them just put
a string with a colon. And as you can see
now, we're getting a nice time in 24 hours format. And actually from
my point of view, this is difficult to solve this task in five
or ten minutes. You really need to
sit there like maybe 15 minutes or half an hour
to check different cases, how you want to
solve it and so on. So this is a nice task to
check how you can convert different things between
them with different logic. But it is not
something that you can solve in one or two minutes.
47. Mapping Data: Here's one more task for you which is taken from
the real project. This is not just some
tasks for the interview, but the tasks that you will
see in your everyday life. And as you can see,
where must map data to the front and format, which actually means we are getting our data, for example, from the backend, not
inform it like we want. This is why we want
to convert them. The main element
is location key, and we need to map
all data to it, and we will have it
then five objects. As you can see here. First of all, we have
a location array, and here we have two objects. First of all, location key and this is our unique identifier. And we have here
some ideas and outer assign exactly the same
in the second object. And now here we have a
bulk configured rate. This is also the
array with objects. And inside every
single object we have a data values and conflict keep. The main point is that we're
mapping them one-to-one, which actually means
the 0 index in location array equals
bulk configs 0 index. And in this case, we need to map everything to the structure. At the end, we must
get an array of objects with first of
all, conflict key. This is this part and location closer to
two, as you can see, location kids a22 is this part and also
outer assigned from it, which actually means a
second element will be also conflict 100
location kit when T2, this is our second number and then outer assign
and so on and so on. And there's said that
unique ID fast is this, which actually means we are
getting here 12345 objects. So Advent we must have an
array with five objects. Now let us try to
write this logic and actually we won't have
anything complicated here. It's all about data mapping. Let's try it here. Our result, as I want to do it directly result for
loops in efficient way. And they won't here
to work with location just because inside we
have our unique IDs. And here inside location
we're getting map, which actually means we're
looping through these objects. Here inside the map. We're getting location element and also we are
getting here index. This is why I must put
additional brackets here. Location n, the index
are what we need to. Now inside we can do our magic because now inside
location element, they're getting
every single object we want here, one mole map, because inside our
location element, we want to loop through
our location key. This is why here we can
return our location element, and here we have
our location key. Here I also have
a map and we have access to our location key. And as you can see,
I wrote it with CamelCase because we're right in JavaScript code and typically all our variables are camelCase. Now here inside we want to
return what we need to. First of all, we need
here allocation key. This is why here I am
writing location key. We can leave it with
underscore like from backend, overcome, convert it to uppercase just depends
on what you want. And here we're just
assigning our location key. After this, we must
get our conflict key. This is extremely easy to do because here inside
bulk conflict, we can just get this
conflict key by index. This is why here we can write Bow config index because it is the same lake and location dot data values, dot config key. And the last part is
outer assign delta sign. We're getting inside location
element dot out a sign. And this is how remapped
what we needed. So first of all, we
have a map through our location,
through the subject. And in a map we have
for our location key. This is why for every
single unique ID, we can map data that we need to. Let's check this
out. I will write console lock here our result, and let's check if it's working. I'm reloading the page and
we get an array of arrays. The first array
we're getting here, location key configured outdoor, assign, and all is good. The only problem that we have is that we get an array of arrays, but we actually
want a flat array. This is why we must do
something with this code. We can use here reduce to
just create a flat array because we don't have flattened method natively
inside JavaScript. Here we have our array
and the accumulator. And at the beginning we can say that we are getting
an empty array. What we want to do inside is
to use array.com catenate. And here we're concatenate
and this was accumulator. What is done here by default, we have here empty
array and we have every single array
that you can see here. And we want to concatenate
our array with accumulator. So essentially for
every single element, we're concatenating it
with our accumulator. Let's check this out. I'm reloading the page and we're getting our fled
array with subjects. And this is how you
map data, for example, from backend format to
our front-end format.
48. Replace Parameters in URL: You might also get
a task like this. Create a function to
replace parameters in URL. And actually this is a real-world task because
here we have an initial URL, like it is generated in old routers for all
front-end frameworks. And in this case we
have initial URL slash, both slash and here column post AD slash comment slash
column comment ID, which means these two
parameters with columns will be replaced by IDs at
some point later. And actually
demonstrate a function replace params in
the URL where we can throw inside the URL with such structure and
array of replacements. And as you can see inside
every single object we must provide from and
to, for example, from post-COVID means that we must replace colon
post AD with id1, and here commented with 83. And of course this
function must be genetic. It is not only for
posts and comments, but any replacements inside URL. And actually before we
will start solving, I want to show you
one more thing, how you can think about
solving problems. For example, you can write
something like to-do list. And in this case, we're
trying to think in steps regarding what
we want to implement. For example, what will
be the first step here? As you see, we have an
array of our replacements, which actually means we have a function with two arguments. And actually we want
to loop through every single replacement and apply this replacement
to our URL. So actually here we can write
go through replacements. The second will be maybe replace parts of each replacements. The last thing we'll be here, return in your stream. This list, in this case might sound like
an obvious thing, but it can help if you
write something like this to implement
more complex logic. And actually directly want to implement here a
correct solution. And we can use reduced for this because it's huge our code best. But I also want to show you the single problem
that you might do. Actually here we want
to create our function, replace params in URL, and we're getting here URL
and our list of replacements. And actually what we want
to turn here is reduced for our replacements,
replacements dot reduce. And here we have
our function with accumulator and each
of replacement. This initial value we
have here our URL, because this is what
we want to change. Now here inside the function, we must return updated string. And for this we can use a plain JavaScript function
which is called replaced. And actually here you might
try to drawn like this. You can think,
Okay, I have a URL, we can simply write here, URL equals URL dot replace. Here we're replacing
first of all, column plus
replacement dot from, and we're changing it
to replacement dot t2. This is it. And after this, we want to return our URL. And actually this code
looks kind of correct. And now I want to move our
initial URL and results here to the bottom and write
console log result URL. And let's check what we have. I'm reloading the page
and we're getting exactly slash post slash one, slash common slips three, which actually means this logic with reduced is
working correctly. We're looping through
every single replacement. Here we updated our URL and here we return it and
don't looks good, but actually you have
here a huge problem. As you can see, my
accumulator variable is not highlighted, which actually means we
are not using here reduce correctly and we're not
using accumulator at all. What we're using, we're
using this URL from params and with directly mutate
this URL every single time. And actually this is
completely wrong, first of all, because we
should not mutate our params. And secondly, the most
important part we're using here reduce like a
for-loop because actually we simply
mutate our variable from outside in the loop and we're
not using our accumulator. Actually the correct code
here is not replace, but simply return
accumulated replace. Because as you can see, we
provided here rail here as an initial value and we should
not use URL here inside. We don't want to change our URL. We want every single
time to update our accumulator and return
in new accumulator. As you can see that this code is working exactly the same, but this is
completely different. Previously, if you would
write code like this, this is completely wrong on the interview because you
are not using reduced, reduced, but just like for-loop, the same goes with map. If you're using the map
just to loop through things you are doing
a trend with map, you need to transform your
array and return it back.
49. Validation Messages: You might also get a
question like this for MOD backend validation
message to front and format. And actually this is a
real example because sometimes we are getting
backend validation messages, not in the format how
it is suitable fast in the front end for
our JavaScript forms. This is why here we are getting our backend errors
in such format. We have here an
object with keys and every single key is a
property from the back-end. Our field that we're validating,
for example, e-mail. And here we have filled errors, and this is what
is interested in files errors is an
array of objects. And inside every single object, we have message property
with some message. For example, here we have
password with two errors. This is what here is an
array with two objects. Here is message must
contain symbols in different case and must be
at least eight symbols lens. What we want to do
in this exercise, we wanted to convert it
to our front and format. This is just a planar array with strings and every single
stream is our key. So our fueled like email, and now we have all our
concatenated mistakes like for example,
can't be blank. And if we have two
of them that we simply concatenate
them with comma. So actually you can solve
it in different ways, but I highly recommend to
use an object enters here. We can simply write here object dot entries and provide
inside our backend errors. And as you can
see, we're getting such nice format like
array of arrays. And every single array
here is first of all, follow a key and the value
is what we had here. So we have a value with errors and inside
we have our errors. And this is really
comfortable format to work for us because we can't really call map in
JavaScript on the object. This is why what we
want to do here, we want first of all, to create some normal
property may be human readable backend errors. And now we want to call
here object dot entries. And we want to provide
inside our backend errors. Actually now we have
array of arrays and we can map here
every single value. And you already saw
what we get here. We're getting an
array with email as a key and some value. And actually here I want
to use the regular this structuring to get first of
all our key and second loop, we're getting our value. This is the easiest way how you can use map on the object. And here we are
getting first of all, our field and secondly
value with the errors. This is why we must
prepare our errors. In this case, let's
name them, for example, field messages and we
must concatenate them. So we can write here
value dot errors. So we're getting our
array of errors. And now here we need to
map every single error. Here we're calling
map without error and we want to return
error message. And as you can see
here, this is true. We have here array
with objects and every single object
contain our message. Here we're just
mapping this messages. And after this group wanted
to get the name them. Here I will put join comma and space because we're born to
have a nice readable string. And after this, we
simply need to return our string because
we're inside map here. I want to use here ECMO
script sixth string, and inside they wanted
to provide our key. But here's the problem. As you can see, it is
always capitalized. First of all, we must
capitalize it and we're already did it
in previous videos. This is where here we can
name it capitalize field, and actually I think
fill this better name. So let's rename
our key to field. And now here we
must call on field, first of all character at 0. In this case, we are taken
our first element and we want to concatenate it
was filled dot slice. And here we're putting one, were cut in one symbol. In this case, it is our
capitalized name of the field. Now here we must provide
this capitalized field, and here D is important. In other case, we can
think that this is a function and after this
was simply put column space. And here our field messages. What we're doing here,
we're mapping through our object entries where getting directly our field and value. First of all, we're joining
our field messages. And secondly, we're
capitalizing our field and now we're returning stream
for every single error. Let's check this out. I'm reload our page and
let's check what we have inside human
readable errors. And as you can see, this is our nice array in
the correct format. So we have here strings for every single field and we capitalize the name
of every field. And here we've
joined our errors, which means we're successful
to solve this problem and transform data in
the correct format.
50. Nested List: You might also get a
question like this. Transform flat list
to nested list. And this is some
super real stuff. Typically from the backend, you're getting all data
as a flat list and typically this data can have
children from one another. Which actually means for
us in the front end, it is not comfortable
to render this data. We can simply go with for loop
because we have children. We need first of
all to render on little levels and then
for every single element, find its children
and render them. This is why typically you
want to transform your data from flat list to
nested list only once. And this is exactly what
we must do in this video. As you can see here, we have our flat list and every
single element is an object. We have unique ID, some name and parent data. And first first of all, it is important because this is our unique identifier
and secondly, parent ID and it can be
either add of another item. For example, here, parent one, this is this item. So this object is a
parent of this item. And secondly, parent
data can be null if this is a root element and it
doesn't have a parent. So as you can see here, we have two root elements
with ad1 and two. Now we have a D3, which is the child
of parent edu one. So this is the second level. This is where the name his
level two, item three. So you understand the level. And now we have a default, which is apparently D three, which actually means
this is a child of this element and actually
this parent three is this. This is why it's level
three, item four. And here we have ad5, which is actually a
child of parent D two, which means this item and actually this is
how we're typically getting data from the backend. Now we must transform
it in such format. So we have a flat array
with just two elements. So as you can see here, we have two objects object with
81 and the object with ad2 because they
are both through elements and their
parent data is now. Now inside we have a
new property children. And this is exactly children
which are mapped inside. And here as you can
see, we have ad3 and also children
inside because actually ad4 is nested inside D three and exactly
the same we have here. We have inside D two children
and here ad5 and children. And I omitted here names because they are not
important for understanding. But obviously you can have all additional properties here. And as you can see
in the last level, one, you don't
have any children. Then we get in here,
children, empty array. So our task now is to transform
flat list to nested list. And as the elder
said previously, for some people it is much
easier to just try to points how they will solve it and then just code it. This is why. Let's try to do it now. So first of all, I will write here to do what we are doing. The first point is to get rid of elements because this is
what we want to render. Let's try to, just like this, get the root elements. So we must have an array
of our root elements. The second point is
to check all children and understand if our two
elements have children. If no, then we simply
return them today. If yes, then we need
recursively to find children. And we must do it recursively
because we need to check every single element
and check if it has children. So we can write here
something like this. Check children if
they have children. And now the next point
will be, if not, then we just return item
with empty children. And number four here is if yes, then we want to
go to number two, which actually means
we're making number two recursively until we are at
the end of our elements. Now let's try to write the code. So first of all, I want to
assign it to our nested list. And what I want to do, I want to take our flat list
and find on little elements. And for this, we can just use
filter because we want to find all elements where
our parent ID is now. In this case, we can simply
say that we have our item and item dot parental
ID equals null. So we're good to go. Let's check this out.
Time to load in the page. And now we have our nested list. As you can see, we have
our array of objects. And here we have 81 and 82 because their
parent. These are now. This is exactly what we wanted. After this, I want just to write that map and inside the
function as children. Why I'm doing like this? Because actually this
function will be called recursively and it would be a completely stateless function, which actually
means we must call this function on any
item and it must work. This is what I want
to create here. Our ADD children function
and we get in here an item but don't need
anything else because here we have our flat
list on the top. If you don't have it
available on the top, then maybe you can get
here a second argument, a flat list in your code, but it will be in
your real project. Here we have access
to our fled list. So what we're doing here, we're looping through
our root elements and we're mapping at children, which actually means
if we want to add children to every
single route element. So first of all, we
must find our children. So let's right here, children. And we know that our
children is just flat list, which is filtered by
parent data where ID equals item dot
ID. So let's do this. Now we simply take
flat list, dot filter, and here we have our child and let's
name it, for example, child item and we want to check child item dot parent ID equals
in our case item dot ID. In this case, we are
finding all our children. Let's console.log
what we have here. So I'm just writing children
underlined in the page. And as you can see here,
we got one single element, because this is a child of
photo element with a D1. And here we have
also one more child of fruit element with parent 82, which actually means it
is working correctly. The next point is to check
if we have any children. So here we can write. If our children length
bigger than zero, then we must do our
recursive magic because we need not only
get children of children, but we must do it recursively. What I want to do
before I want to create a property lad was own
ness to children and they want to assign here empty array because
actually if we are not inside the SIF then we
don't need to change anything. We simply need to
return empty children. And as you can
see, I assigned by default empty array here so we can return here object
assign and here I am. Right, an empty object
then comma, item, comma. And here is our children. Nested children. Why
I wrote like this? Because actually, if
you will use here push or just with stored, you are saying that here
are our nested children. Then you will mutate the item, which actually means you
will change this item inside flat list because we have an object reference.
We don't want this. We simply want to
return your data. This is why I am using here object assign with empty object. After this we're using our item so we copy
all properties of our item inside this new object and were signed in here in
your property children, which is our ness to children. And in this case,
we simply have just let nested children
empty object. Let's check this out.
Time to load in the page. Here is our nested list. And as you can see, we have now children empty array because actually we didn't write
any logic for this eve. This is why we simply
return data in such format ID name parent ID actually all fields and
additionally children. And as you can see, we have
here only two elements, which actually means everything
is working correctly and we must just call
recursively here our code. So what we want to do here, we want to look through
every single child and call at children
function on this child. So we can assign here
our nested children. And this is just our
children, that map. And we have access to
every single child. And we we're calling it
children with our child. So what is happening
in this case? For example, we found the child. We're checking here, okay? We have a child
in, say, children. And here we are mapping
through our array. And for every single element
were calling at children most important part that were Colin this functions
recursively. First of all we called it
here inside root element. Now here inside the children
were Colin it was map. And when we were
calling it here were chicken children of this child, which actually means it will go recursively until we don't have any children and we're just
not going to this condition. So, for example, in our case, here were Colin at three times. First of all, for
you do one then for ID3 and then for a default. And this is exactly why we need recursion here. Let's
check this out. Time to load in the page. Let's check our nested list. And as you can see,
we have now children. And inside item one, we have just one child with ad3, and we also have a
children property inside and we have
one more child here, level three, item four, and we have children empty array because actually our recursion ended and we simply got here empty children and
we assign them here. So once again, first of all, we must get all
our road elements. Secondly, we must create
a function which we can call recursively
on any element. And this is our children. Now, inside, the children
were, first of all, trying to find all
children of the item, and secondly, bear chicken. If we need to make recursion for our children,
if we have any. If yes, then we're Colin
at children recursively. If no, we simply make an object assign and the return
here our children. So this is how you typically
do it in the real project.
51. Homework: You successfully
finished my course regarding preparing to
JavaScript interview. And I think that you are awesome if you
finished it together, we implemented 59 JavaScript
interview questions. And actually a lot
of them were not easy if you didn't
try it yourself, but just follow the loan. You can still do that. You can just randomly pick some video and try to
implement it yourself, even if you saw it once, it makes a lot of sense
to try and do it. Also, I just wanted to remind
you to not be depressed. If you fail the interview, it will come with time and you will for sure
find your chop. You just need to
gather more knowledge, understand what question
you are being asked in the interviews and
prepare yourself better. I hope that you
learned a lot and I will see you in
my next course.