Ep20 - Intermediate JavaScript Course

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hey there sam let's talk about a var keyword and why we shouldn't use it at all suppose we have a variable called a which is defined using a let keyword and we have another variable b defined using the var keyword and lastly a cons variable c and here's a situation let's create an if statement and are passing through in a round bracket so the if statement will run and inside if statement will redeclare variable abc and reassign the values to the number 2. now if i console out the variables a b and c after the if statement what do you think will happen what would we see in the console pause the video and think for a second the answer might surprise you so let's take a look at what will happen for a we get the string a which is the initial value for b we get 2 and for c we get the initial value as well so what the hell is going on here let's break it down bits by bits before we move on i want to introduce you the concept of scope now in javascript every time you see the curly braces it means we're entering a new scope it could be an if statement a for loop a function or even just a pair of curly braces on their own just a side note even though the curly braces of an object is the same as the curly braces of a scope they are not the same concept so don't get confused by them you can think of a scope as a room that separates variables whatever variables that we define in a scope stays inside the scope and once we exit the scope the variables will just be dumped into the garbage bin and this explains why are we getting the original value for a and c so the variable a and c that we define inside the if statement is different to the variable that we define above and once we exit the scope they will be gone and the variable a and c down here is referring to the a and c that we define up there now you might be wondering why b has changed the reason is var variable sucks and they do not follow this rule in other words var is not scope safe i'll show you why this could cause an issue in just a minute for now let's take a look on how javascript finds a value for a variable suppose we can slow out the variable a when javascript run this line it was first looked out for the declaration of variable a in the current scope it found the declaration in this case but we're trying to grab the variable before we declare it that's why we're getting an error if javascript couldn't find any declaration in the current scope it will try to look up in the periscope i'll show you what i mean if i comment out the variable a in the current scope the console.log here will be referring to the a above which is from the periscope and if javascript couldn't find anything in the parent scope it would go further up into the grand parent scope and great grandparent scope until it couldn't go further up anymore in other words it won't stop until it hits the global scope which is everything underneath the script tags so now let's go back to our previous question how could var cause an issue if it is not scope safe the short answer is it could unexpectedly override the value of an existing variable and causes bugs in our program let's take a look at an example suppose we have a variable called index and this index variable holds some very important information that's needed later in our code and now let's say we've got a for loop which coincidentally using the variable index as its counter and now let's see what will happen to the index variable after the for loop oh should we get 4 which means our important information has been overwritten can you see how this could lead us to bugs in our code our program now thinks that the number four is the important information that we previously defined and carry on to use this number to perform the corresponding important operations and this is very very bad so how can we fix this the answer is very simple do not ever use the var keyword if we change var to lat our problem is instantly gone the reason is by using lat the variable index in the for loop lives inside the for loops scope and it is not the same as the index that we define outside so as soon as we leave the for loop the index variable in there is gone forever and the index variable outside remains as itself and now for the next part let's take a look at another weird behavior of the var variable let's create a scope and inside this scope we have three variables defined using the var led and keyword and we'll console them outside the scope as expected our lat and cons variable give us an error because we are outside the scope but the var variable is printed out just fine why is that again this is not a weird thing about var this is something called hoisting so hoisting means raised up when we declare a var variable it doesn't care about what scope we are in it will always get hoisted up to the global scope so even though we declare this variable inside the scope javascript will hoist the declaration up to the global scope and assign the value to the variable inside the scope so to javascript this section actually looks something like this so again var variable sucks and they are hoisted up whenever we declare them moving on let's look at another example we'll correct three new variables again a lat variable var variable and a const variable now if we try to access the let and const variable javascript will throw us an error and that's normal because how can we access something if that's not declared yet right well to var rules doesn't exist javascript will not throw us an error if we try to access the variable before it is declared why because of hoisting when we declare a var variable javascript will hoist this variable upwards to the very top so similar to before to javascript this block looks something like this and that's what we get undefined for this variable so the conclusion here is that we cannot access a let occurrence variable before declaration but for var variable javascript will not throw us an error but will get undefined for the value the last weird thing about var is that var variables are added to the windows object by default so if i try to console out windows.ava we get a value but if we try to console out the led variable we get undefined so these are the differences between var and lab and const if you can get one message out of this video i hope that it will be do not ever ever use va otherwise people will start to hate you alright key takeaway var sucks and var is not scope safe var variables are hoisted up that means they are raised to the top of the global scope we can't access a left or const variable before declaration and finally var variables are added to the window object by default that's it for now and i'll see you again shortly hey there sam there's a special variable called this in javascript what does it do well it represents the context of your code i'll show you what i mean for example let's say i have a car object here and a car has a model and a brand property and also a drive function and let's close lock out the disk keyword inside the drive function and we'll run car.drive and surprise surprise we see the car object so why is that and again this keyword represent the context so in here we're calling the drive function on car the contacts here is the car object and therefore we get the car object from the disk keyword now what would happen if i set a new variable equal to the drive property of the car object and then we'll call it right away what do you think will happen here would there be any changes only one way to find out and we get a windows object what the hell is going on here let's break it down so again this keyword represents the context here we made a copy of the drive function into a boom variable and then when we call this function we're no longer calling it from the car object so the context here is no longer the car object the context will be by default the global object which will be the windows object so that's the reason why we see windows in the console.log and one more question what do you think will happen if i just console out this out of nowhere it is the windows object why because as we talked about just now this keyword defaults to the global object which is the windows object in the browser okay now why do we need to care about this keyword the reason is that this keyword could be handy when we want to update the properties of an object inside an object's function for example suppose we are creating a game and this game has a toad character the toad has a x and y position and also some functions to control the movement so move left will be a function that takes in a unit input which will tell the total to move to the left on how many units so here we want to update the x position we will just decrement the xposed property by the unit supplied so what we can do here is to type in this dot x position minus equal to which means decrement and our unit parameter so this line will decrease the x position by the unit supplied in other words move the x position to the left and similarly for the other direction we can do the same using the same format and we also create a getposition function which will just print out our x position and y position and now if we tell our toad to move right by 50 and we call the getposition function directly after it will get 50 and 0 because now the x position property has been increased by 50 units by our move right function and all we're doing here is to use the this keyword to update our object properties let's take a look at another example before we end the lesson now suppose i have an inner function inside my get position function here and inside the email function i'll just console out this keyword what do you think will happen if i try to run the inner function would this inside the inner function be the window object or the toad let's find it out we'll run the inner function and we get the window why because we're calling inner on its own without any predefined context so by default javascript set the context to the global object which is the window object so a quick way to find out what this keyword is is to check what is calling a function if we are calling a function from an object then this keyword would represent the object itself however if we're calling a function on its own just like the inner function here that this keyword would represent the window object and that's a quick intro to this keyword in javascript key takeaway for this lesson this keyword represents the calling context by default this keyword resolved to the global object which is the windows object in the browser this keyword is very useful to access information in the current context for example to get or update properties inside an object that's it for now and i'll see you again shortly hey there sam so we know that there are two types of function in javascript first of all the normal function and also the arrow function let's take a deep look on how error function is different to the normal function difference number one we can omit the return statement and the curly braces in an error function when the function logic is a one-liner for example let's say we have a function called multiply and the multiply function accepts two arguments x and y and the result of this function is simply x multiplied by y but instead of writing out the curly braces and also the return statement we can shorten it to x multiplied by y directly after the arrow it looks much cleaner right if we take advantage of this feature it can really cut down a lot of lines in our code okay difference number two when the function only has one argument the round bracket is optional for example let's create a function that will add 2 to any number that i passed to it so in this function num is the only argument so i don't need to surround it with a pair of round bracket and this function will return num plus 2. and again the function logic is a one-liner that's why we don't need the curly braces in the return statement and finally difference number three this keyword in an arrow function is automatically bound to the parents context i'll show you what i mean suppose we have a car object and we have a property color and a drive function which has an inner function we'll declare this in a function using the traditional function syntax and inside this inner function will console out the this keyword and we'll call the inner function right away now what do you think will happen if i call the drive function what would this keyword be only one way to find out so we see the windows object in the console but why is that the reason is we're not calling the inner function on any context so javascript by default will resolve to this keyword to the global object which is the window object if this doesn't make sense to you feel free to watch the previous video where i talked about this keyword the link is in the description now let's see what will happen if we declare the inner function using an arrow function let's create a new function on the car object called honk and the logic of this function will be exactly the same as the drive function a set that we're using an error function for the inner function what do you think will happen now would we still see the window object or something else let's find out what will happen well it turns out to be the car object and this is exactly what i meant by binding to the parents context so when we're creating an error function javascript will try to pass this keyword in the current context to the function itself in other words javascript will try to grab the disk keyword immediately right above the inner function which happens to be the hong function in our case here and set this keyword of the inner function to be the same as this keyword in the hong function the this keyword in the hong function from our function call here would be the object itself and that's why we see the car object in the inner function this is a very convenient feature that the error function offers to us without the error function we will need to call the bind function on our inner function if we want to bind the context to something else for example if i want to set this keyword in a drive inner function to our car object i'll just call dot bind right after the function definition whatever we pass in inside the bind function will become the context of the inner function so if we pass in this which represent a car object the inner function will now console out the car object if i pass in a string hey the disk key would not represent the string hey so the arrow function is really just calling the dot bind this combination for our convenience the reason is because we almost always want to access the parent contacts inside an inner function if you don't want the context to be automatically bound for you just don't use the arrow function and stick to the traditional function and call the bind function alright key takeaway for this lesson we don't need a return and curly braces in the narrow function if the function itself is a one-liner if there's only one argument the round brackets are optional arrow function automatically binds the parent's context to itself that's it for now and i'll see you again in the next video hey there sam a function can return a string a number an array or an object but what if i tell you a function can return another function interesting right so the concept of a function that is returning another function or taking a function as its argument is known as a higher order function and higher order functions are one of the key pillars in functional programming and we'll be discussing more about functional programming in a future video for now let's take a look at why you might need a higher order function in our code so in general higher order function let's write cleaner and more maintainable functions let's take a look at an example suppose we have a main element and i want to create multiple headings with different colors inside our dom first of all let's target our main element so we can easily manipulate it later on next i want to introduce you to new concepts the first one is something called a factory function which is basically a higher order function that generates or return a function the second concept is called closure which is a fancy word for a function that was defined in another function now we'll be creating our headings using these few concepts that we just learned so a heading has two variables the color and also the content of the heading the idea here is that we'll be creating a factory function that accepts the color of the heading and the factory will create another function that creates the heading with the specified color i'll show you what i mean so we'll declare a new function called heading factory and it accepts one argument which will be the color of the heading and inside the function we define a closure which is what this factory will return later on now this closure is where we actually create the heading so the closure here is a function that accepts a single argument again and this time the argument will be the text content of the heading we're going to create a new variable heading which is equal to document correct element h1 and we want to set the color of the heading to the color specified in the factory function so we'll set the style attribute the value will be color colon and the color argument that we pass into the factory function next we'll set the text content to the text argument and finally return the heading as a result of this closure then we'll return the closure as the result of heading factory okay now let's take a look at how we can use this factory function the benefit of using a factory function is that it is very very flexible and they make our code very declarative and reusable so here let's say i want to create a red heading to do that i'm going to call my heading factory function and pass in the color red to it and let's set the result to a variable now let's break it down the heading factory will return us a function so correct red heading is a function and this function is the closure that we define inside the factory function which accepts a text argument and will return a heading with the color red let's try this out i'm going to try to call the correct red heading function and pass some random text to it and append the result to a main element and it works we can now see a red heading inside our browser let's take a look at another example let's create a gray heading this time and repeat the process and now we get a gray heading in our dom and every time i want a new red heading or gray heading i just need to call the correct red heading or correct gray heading function over and over again which is very descriptive and convenient now at this point you might be wondering what's the difference between this technique against a normal function that accepts color and text to create a similar heading which looks something like this a short answer there's not much difference it's really all about your personal preference however it does make a huge difference when you've got a complex function that has a lot of arguments and logic by applying the techniques that we learned in the past few minutes we can break down a very complex function into smaller bits and execute the complex logic in multiple steps which helps in debugging and also maintenance in the long run so that's a quick intro to closure and also higher order functions we'll discuss more functional programming concepts in the future key takeaway for this lesson higher order functions are functions that accepts another functions as this argument or return another function as its result closures are functions that are defined inside another function in other words a function within a function functional programming techniques can really help us to write more declarative and cleaner code if we use them appropriately our code will be easier to read and maintain in the long run and that's it for now and i'll see you again in the next video hey there sm a function can accept a number a string a boolean an array or an object and as we talked about in the previous video it can also accept another function as its argument now this function that we pass into another function is known as a callback function in javascript and callback functions exist everywhere in javascript i'm pretty sure you have seen it before just a quick example if i add a click event listener to my windows object the function here that handles the event is a callback function why because we're passing this function as an argument to the add event listener function and our function here will eventually execute by the add event listener function somewhere down the track now let's talk about why do we need callback function in the first place the main reason why we need a callback function is because it allows the end user to customize the logic and offers a lot of flexibility let's use the add event listener function as an example the author of the add event listener function doesn't really know what you want to do when you click on an element he can't write a logic for you can he because he doesn't even know how would your website look like and this is exactly where callback functions comes into the picture by using callback function we as the user can decide what to do when an element has been clicked now let's make this concrete we'll be looking at how callback functions work behind the scene now suppose i want to do some shopping let's create a function for that our shopping function will set one argument the budget for our shopping and that's how we spend a hundred dollars in our shopping trip so our budget now will be equal to budget minus spent and the result of this function will be the remaining budget so far so good however right now the user who use this shopping function might want to do something after the shopping and they don't really have the flexibility to do anything because of the way how we structure our code at the moment so what should we do then the answer is to introduce the codec function so let's create a second argument for our shopping function and i'll call it after shopping callback so this argument will be a function that is defined by the user and we'll run this function right before the return statement and now let's try to use our shopping function we'll go shopping and the budget will be a thousand dollars and for the second argument we should pass in a function and let's say after we finish shopping we'll go and watch a movie so i'll just console log watch movie let's test our code and now in the browser we can see watch movie in the console let's break it down for one more time so we pass in a function as the second argument of shopping and now this function becomes the after shopping callback and within the shopping function we're calling this function right before the return statement and that's where our custom function gets executed okay moving on suppose the activity that we want to do after the shopping is dependent on the budget remaining from our shopping right now there's no way for us to access the budget remaining from our shopping trip so why don't we pass our budget to the callback function just like the other functions so now that means back in our callback function definition down here we should receive an argument which represent the budget and just like the other functions you can name the argument to anything you like i'm just going to name it budget to keep things consistent and now if we console our budget we would expect to see 900 and there you go if we compare our shopping function against the add event listener function can you see how similar they are and this is exactly what's happening behind the scene in every callback function let's finish up our shopping function let's say the movie cost us thirty dollars we'll deduct the budget by thirty dollars and return the remaining budget as the result of our callback function in other words the callback function will give us back whatever is remaining after the activity so back in our shopping function we can reset budget to the return value of the upper shopping callback and now if we set the result of our shopping function to a variable and we can't lock it out we'll see the leftover after everything and that's how some cobalt functions requires you to specify a return value because it needs to use that return value to do something okay now there's one last thing before we end the lesson there's a concept called callback hell in javascript what that means is we're nesting callbacks after callbacks inside callbacks if you have no idea on what am i talking about take a look at this let's say we go for shopping again our budget is still a thousand dollars and inside the callback function suppose we want to do another round of shoppings after the first shopping trip so we're gonna call the shopping function again and let's say after the second round shopping we're still not satisfied because we're a bunch of shopaholics so we go for a third round and a fourth round and on and on and on can you see where this is leading us to not a shopping mall but towards call back hell this code here is very very ugly and definitely not something that we want to do there is a solution for this and it is called promise which we'll be talking more about in the next lesson key takeaway for this lesson callback is a function that is passed to another function the idea of callback function is to allow the end user to customize the logic of a function callbackhealth is not pretty it is very hard to read and also to debug we should try to avoid it as much as possible that's it for this lesson and i'll see you again in the next video hey there sm there are two types of operations in javascript synchronous and asynchronous operations synchronous operations or sync for short are operations that run on the spot for example when we set a variable or we want to console something these are all considered as sync operations because in javascript system javascript will run them right away asynchronous operations or async for short on the other hand are operations that would delay their execution for example set timeout and set interval are considered as a synchronous operation because when javascript sees them javascript will not run them immediately javascript will only run asynchronous operations once all the synchronous operations are completed i'll show you what i mean so if i add another cluster log right after my set timeout what do you think will happen here what would we see inside the console i've set the delay of my set timeout to be zero second so technically it should run immediately right after the first console log right let's find out in the browser well it turns out hey babe runs after you and there but why is that the reason is set timeout is an asynchronous operation and javascript will only run it after all the synchronous operation when javascript sees an asynchronous operation it will throw into a queue system known as the event loop let's visualize this with my amazing drawing skill so suppose we have a list of operations here every item in this list represents an operation awaiting javascript to run it's sort of like a to-do list for javascript so we have a synchronous operation one followed by another synchronous operation s2 and right after s2 we have an asynchronous operation one and after that we have another synchronous operation s3 followed by two more asynchronous operations a2 and a3 and lastly at s4 and now let's say this is the cube system the event loop which looks something like a box and now let's go through our to-do list as javascript so when javascript sees our first synchronous operation s1 you'll run it right away so s1 check s2 is synchronous as well so we'll check it off immediately next we have an asynchronous operation a1 we're not going to run it immediately so we'll put it inside the event loop so bring it over to the box next we have synchronous operation s3 we'll do it right away and after that we have a2 and a3 and similar to a1 we bring it over to the event loop and lastly we have s4 in the list we'll run it immediately just like the other synchronous operations now that we have completed the list we'll now go to the event loop and start doing the item from the top to the bottom so a1 done a2 and finally a3 and we're done so that's how javascript deals with synchronous and asynchronous operations in a nutshell we first finished all the synchronous operations then the asynchronous operations and now i want to introduce you a new concept called promis in javascript a promise is another type of asynchronous operation in javascript it is essentially an object that holds some sort of logic to be executed later it works the same way as promises in real life so when we make a promise we won't do it right away our promise holds until we start to take action to fulfill our promise since we're not completing our promise right away this make it an asynchronous operation i know this sounds a little bit abstract but i promise i'll go through this with you so let's make a promise to buy an ice cream i'll create a function that accepts an argument called amount which represents the money we're gonna spend on ice cream now in this function we need to return a promise we will return a new promise i'm using a new keyword here to create a new promise object we'll talk about the new keyword in more details in a future video for now to create our promise object we need to pass in a handler function inside the round bracket this handler function is also known as the executor function it contains the logic of our promise which will be later on executed inside the event loop now the executor function has two arguments resolve and reject you can name them anything you want as long as you reference them properly inside the executor function so the reserve argument is a function that we should call when the promise is successful on the other hand the reject argument is a function to call when the promise has failed in our case here if we have successfully bought our ice cream we should call the resolve function otherwise we should call the reject function i'll show you what this mean in just a second now the only rule about the executed function is that the logic in it has to be an asynchronous operation for that purpose we usually put our logic inside a set timeout function our logic will be very simple if the money given is less than three which is too little to buy an ice cream we're gonna reject this promise in other words this promise will fail so we're going to call the reject function by putting a round bracket after it and passing the message i'll just say not enough money otherwise if we have enough money we will resolve this promise in other words this promise is a success so we're going to call the result function again put a round bracket after the resolve argument and pass in a success message i'll just put in an ice cream and that's how we use the resolve and reject argument okay now let's take a look at how we can use our buy ice cream function we're going to call it i don't need to supply any argument here because the amount argument has a default value of 5. now the buy ice cream function is returning us a promise and there are two functions that we can call from a promise object the then function and the catch function the then function is used to handle the success promise response it accepts a function where we put in a logic to tell javascript what to do when the promise is successful and this function accepts an argument and that argument represents the data that we pass in to the result function so if i console out response i will expect to see an ice cream in the console now the other function the catch function works the other way the cache function is where we handle a failed promise and similar to the dot then function the cache function also accepts a function and that function is where we put in a logic to tell javascript what to do when the promise has failed so if i pass in 2 to my buy ice cream function i will expect the promise to fail because 2 is less than 3 so the reject function will run and we see not enough money in the console the thing about the dan and catch functions that they will also return a promise object and that's a reason on why i can call the dot catch right after the dot then because then function is returning us a promise and i'm calling the cache function on that promise object so knowing this we can change a lot of then function on top of each other and whatever you return in a previous 10 will be pass on to the next then as the argument of the handler function for example if i return a string i bought an ice cream in my first den function and i change another damn function right after it consulate out the response change 2 to 20 and we see i burn an ice cream in a console because the string has been passed on to the next dan function if you don't like to do it this way you can also break out the promises into multiple variables i'll set a variable by to be the result of by ice cream and by 2 to be the result of the first 10. and by three to be the result of the catch function on by two however i do not recommend you to write your promises in this way because it's very ugly now here's a question that you might have at this point does the location of the catch block matter can we put the catch block in any order that we like for example move the catch block to line 42. the answer is yes it matters a lot here's the thing the catch block is only able to capture errors that happens in the then functions before it i'll show you an example so if we show an error in the first then the catch function is able to capture it so far so good and line 47 is undefined because the cache handler is not returning anything so the response is undefined now if we show another error in the second then let's see what will happen we get an uncaught error nothing is catching this error and therefore javascript is not happy about it and this is what i meant when the cache function is only able to catch errors that are thrown above it writing a promise seems to be a lot of work involving it that's actually a simpler and cleaner way to write a promise the trick is using the async keyword let's take a look at this i'm going to replicate the buy ice cream function but in a much simpler way so i create a new function called buy ice cream 2 and instead of setting it to just a normal function i'm going to add the async keyword before the function keyword and inside this function we no longer need to create a new promise object the async keyword does all the heavy works behind the scene for us we only need to focus on the logic that we put in inside a set timeout function if you want to reject the promise we just need to throw a new error and to resolve the promise we just need to return the result as a normal function take a good look and compare between these two functions they're doing the exact same thing but the async function is way cleaner than the first version let's test our bioscrim2 function and it works just like before now that's another benefit of using async function i'm going to introduce you another keyword it is called the await keyword the await keyword can only be used inside an async function and what it does is allow us to execute promises synchronously let's take a look at an example i'm going to create a new async function called main now to demonstrate the power of the await keyword i'll console out hey and then i'll await by ice cream 2 so the await keyword will force the promise to resolve immediately and the result of this statement will be the data that we pass on to the result function inside the promise so if i set the result to a variable here and closer lock it and after that i'll console out another there just to show you it's running synchronously and run the main function and now we see an ice cream before the word there here's a question though why do we see an ice cream for two times the reason is the awake keyword will force the event loop to run and remember the task in the event loop has an order to it the promise in line 47 is put to the event loop before the promise in line 52 and that's the reason why line 47 is run before line 52 and we see an ice cream for two times now the last thing i want to cover before we end the lesson is the main benefit of using promises which is avoiding callback hell so in the previous lesson we talked about how combat health can look very very ugly so the weakness of callback can be easily resolved by promises let's take a look at the demo i'm gonna buy an ice cream and after that in the den function i want to buy another ice cream i can simply call the buy ice cream function again and return it so the result of the buy ice cream function will be passed on to the next then and in the next stand i'll call the biasing function again and so on and so forth can you see how this has solved the main issue of callbacks we're no longer nesting callbacks upon callbacks but instead we're keeping our indentation shallow and that is the main reason why we prefer promises over copacks alright key takeaway for this lesson synchronous operations run on the spot while a synchronous operation run later in the event loop event loop is named for the queue system that javascript uses for asynchronous operations promises are async operations that aim to solve the problems of copac async function returns promise so instead of writing a boilerplate to create promises we can just use this nice helper keyword before our function and that's it for this lesson and i'll see you again in the next video hey there sam there are a lot of websites that has this click to copy button to help us easily copy content to our clipboard let's learn how to do that in javascript we'll start from scratch i'll create an article element where i'll put in some crap for javascript to copy later i'll also create a button so when we click on it we'll copy the content in the article next we'll attach a click event listener to our button let's store our button as a variable and we'll call the add event listener function with the click event and here when we click on the button we want to get the text content of our article so we'll target our article id content copy and grab the text content property once we get the content we'll need to find a way to write the content to our clipboard the browser does offer us a very simple way to work with clipboard content by using the built-in clipboard object and similar to the console object the clipboard object is also one of the available tool in the browser the documentation link is provided in the description below so feel free to check it out after watching this video the clipboard object is a sub-object of the navigator object so to use it we need the codenavigator.clipboard and to write content to our clipboard we will call the writetext function and the right text function accepts one argument which is the content to be put into the clipboard and now if i click on the button i will expect the content in the article to be copied to my clipboard and i'll paste it in in my vs code and we see the crap so far so good now let's learn how to read content from the clipboard to read the text content we simply call the read text function and we'll console out the copy content and click on the button oh no there's something going on here so there are two things i need you to be aware of one for security reason access to the clipboard is blocked by the browser by default so the user need to explicitly allow a website to access the clipboard by clicking on this button why do we need this because we copy sensitive data like our password or credit card number all the time if we happen to visit a malicious website while having our credentials stored in our clipboard at the same time that would be a massive disaster now the second thing is the red text and the write text functions are promises so that means they are asynchronous so to read the text content in our clipboard right after we copy it we either need to use the den function or use the await keyword i like the await keyword better so let's use that to use the await keyword we first need to turn our function into an asynchronous function by adding the async keyword before our function definition and await the write text function and also the read text function and now we're seeing our copy content is printed out in the console which is great we can also paste images from our clipboard let's create a new article element for us to paste in an image and also a paste button and similar to the copy button will also store the paste button as a variable and add an event listener to it when we click on the paste button the idea is we'll read the content from the clipboard and paste them into the article so first we need to store our article as a variable and we should clear the content of it when the paste button is clicked now to get non-text content from the clipboard we need to call the read function on the clipboard object again the red function is a promise so we should use the async and await keywords again now the data returned by the read function is an array of clipboard items to get a clipboard content we need to retrieve the first element of this array now the clipboard content belongs to the clipboard item data type it has a few helper functions that allow us to grab data from the clipboard to get image data we can call the get type function from it the get type function accepts one argument which is a string that represents the file type this type of string is also known as the mime type it's using a convention of file type slash extension type if you want to take a look at the other mime type i have attached a link in the description below so the get type function is also a promise so we should put an await before it and it'll return us something called the blob blob stands for binary large object to put it simply it is just a giant string that represents a file our goal here is to put this blob inside an image tag so we can show it in the browser dom the blob is stored inside a temporary location in the browser so first of all we need to grab the url that points to the blob to do that we can call the windows.url dot create object url function and pass in the block object then we'll create an image element and set the source attribute to the blob url and finally append our image element to the article let's test our code i'll go to unsplash.com and randomly copy an image and click on the paste button and it works however at the moment our code could fail why because if the content in our clipboard is not an image javascript will explode i'll show you what i mean so if i click on our copy button which will copy the text into our clipboard and i click on the paste button and see that that's an error we can easily fix this by using a try and catch block so i'm going to try to capture any errors that was thrown inside our image handling logic if that's an error that means we cannot copy the image so we're going to call the rig text function instead and set the text content of paste article to the text let's try our code again we paste the text in and we see the crap and if we copy the image from unsplash paste it in and the image is showing and that's it key takeaway for this lesson the built-in clipboard object allows us to manipulate the clipboard with javascript blobs or binary large object represent file as an object so we can work on them using javascript you can convert pretty much anything into blobs including images pdfs or even videos mime type is a string convention to describe a particular data type that's it for this lesson and i'll see you again in the next video hey there sm api or application programming interface is a scary word for a very simple concept the word interface here has a huge weight in the meaning of api let's explain api starting with the word interface so what is an interface an interface is a point of interaction or a tool for us to work with a much more complicated system for example a computer is a very complicated system for us average human to understand however in order for us to work with a computer we don't really need to understand the inner working of a computer that would be too much to learn instead all we need to know is to learn how to use the keyboard and mouse for us to interact with the computer the keyboard and the mouse are relatively simple compared to the computer system and that is exactly what an interface is a simple tool to work with or interact with a much more complicated system let's take a look at another example a car similar to a computer a car is also very complicated for us average human to understand so to make our life easier the car manufacturer has made available a few interfaces for us to drive a car for example a steering wheel a gearbox the indicator handle and a speed pedal with these interfaces we can interact with a car without knowing the inner working of the car now api is exactly like these interfaces the only difference is an api is an interface to a computer software so if a software has an api we don't really need to know the inner working of the software but only need to learn the api provided for us to interact with the software in other words api are just a set of functions provided by a software for us to interact with it generally there are two types of api programming api and web api let's take a look at a few examples to make this concrete so programming api is just really a set of functions that we can use directly in our programming language i'll show you what i meant the browser is a large piece of software that has lots of components in it just name a few examples we have the console the dom and the local storage we can think of each of these individual components as separate software and the browser does offer us ways to interact with these components in other words the browser offers a programming api for us to interact with these components and we have seen it lots of times already for example to work with the console we simply just need to call the console functions console.log or console.error are functions that we can call on the console object in other words the api of the console to interact with the dom again we are calling functions from the document object and again all the functions that are exposed by the document object are the api of the dom and we're using these apis directly in javascript that's why it's called the programming api if you want to take a look at all the available apis offered to you by the browser you can go to the web api documentation and check out all these apis available to us the link is in the description there are lots of interesting apis here for example the bluetooth api where we can let the browser to interact with bluetooth on our device imagine you can remote control a toy car using a browser how cool is that the geolocation api is another interesting one where we can get to know the location of our website visitor so applications like google map or uber will have relied on this api to get to know the user's location that's enough for programming api let's move on to web api have you been to some website where you can share some posts directly to your twitter account or your facebook account or a website that has google map embedded in it they are not owned by google facebook or twitter but yet they are using these third party services on their website and if you're wondering how they did this it is through the magic of web api there are millions of web applications out there and the majority of them are closed source that means the source code is not open to the public which means we can't interact with them directly in our programming language and therefore there's no programming api available to us so what should we do then there are typically two ways for us to interact with a web app the first way which is obvious is to use the user interface provided by the website the second way is to use web api as we mentioned earlier apis are essentially functions exposed by a software in contrast to programming api we will run these functions directly in our programming language for web api we'll be running these functions through http before we dive in any deeper let's first look at what is http and how it works http stands for hypertext transfer protocol and again it's a scary word for a very simple concept we humans has lots of ways to communicate with each other when we want to talk to our friends we can either call them by phone or send an email or text them and similar to humans computers can talk to each other by different ways as well and http is just one of the ways the other methods include ssh ftp and git and many others each of these communication methods involves different rules and procedures just like how when we make a phone call we gotta use a phone and dial the other person's number or when we text someone we need to type our message out now let's go through http in more details suppose this is a computer that you are using right now and this is a server that sits somewhere in the internet and now suppose your local machine wants to talk to the server via http the http rules says that your local machine will send another request to the server and the server will reply with exactly one response so with one request we are expecting to get back one response nothing more nothing less now for both requests and response each of them has two components the header and the body the header contains metadata about the http request or response for example the content type or the language or the origin of the request or response if this doesn't make sense to you don't worry we'll go through a real-life example later the body contains the payload for example if i was to log into a website my request body will contain the credentials and the response body will be a message telling me if my login attempt is successful or not http request has different types of methods or flavors if you like to accommodate different types of operations the most common methods are get post patch and delete the method is typically specified in the header of the request a get request is generally for downloading reading or viewing resources for example downloading a html document to render in a browser or getting an array of users facebook post post request is for creating new resources or for any miscellaneous operations for example creating a new user account or a new facebook post or simply login to our web application a patch request is for updating resources for example when we want to update our facebook post or comment or our profile picture a delete request is self-explanatory whenever we want to delete resources we'll just send a delete request now let's take a look on how http works in action we'll go to google with the chrome developer tools open and we will switch to the network tab this is where we can investigate all the http requests happening inside the browser make sure you selected the old filter to view all the http requests there are other types of filters available to us to filter out different types of http resources now that you'll notice there's a list of resources going on here these are the http requests that have been sent by the browser since the page was first loaded in chronological order we can click on each individual item to investigate the request in more details let's go with the first one the header tabs here tells us more about the headers in our request and response so if we scroll down a little bit more we'll actually see what's inside our response header and also our request header you'll see a lot of scary stuff here but don't worry you do not need to learn all of them at once we just need to know a few of them in order to understand http in general so under the request headers we have methods it's a get request which means the current request that we're investigating at the moment is a get request and remember a get request is for downloading reading or viewing data so in this case if we go to the response tab we see a html document that means we're downloading a html document from google's server and if we go to the preview tab we will see the rendered version of the response so chrome will render the html document right inside the developer tool but you'll notice this is a little bit different to the one that we're seeing in the browser now the google's logo is missing the icon is missing why is that the reason is at the time when this html document is downloaded we only have an image tag inside a document that's pointing to an external image file somewhere in the internet so at a time when the browser tries to render this page and when it sees this image tag it will then send another get request to grab this image file and once this get request for the image file is completed then the browser will put this image inside the dom the same applies to all the javascript files css files and so on and so forth and that's the reason why we're seeing all these resources loaded inside this list the first item is always the main page and a subsequent request are the items that is required by the main page or sent out by the javascript file of the website so if we try to click on the other request we'll see my account avatars the google's logo and lots of icons and again all these requests are fired by the main page and they're all get requests because we're just downloading files or resources from another server let's take a look at another example we'll go to this website codepen.io and i'll try to log in with some garbage credentials now notice very carefully at the request list as i hit the login button a new request has been added let's take a look at it first of all it's a post request rather than a get request because right now we're no longer trying to download something from the server we're trying to perform an action and remember post request is for creating new content or any other miscellaneous operations like login and if we scroll to the very bottom we can actually see the payload of our post request these are the body of this post request sent to the codepen.io server and they matches with what are entered in a text input of the website if we go to the response we're now seeing a json response rather than a html document let's go to the preview tab to look at the pretty printed json string so this is what the server has sent us back when we entered a garbage credentials it tells us the username and password is incorrect and notice that the error message is exactly the same as what we see in the user interface here okay let's break the whole process down and go through this together so here's the server and it has lots of predefined urls that are listening to incoming http request each of them has their own roles and responsibilities sending a http request to each of these routes will trigger a function in a server to perform some sort of task and when the task is finished the server will send back a response to the browser can you see where this is going now we can let the user to run a certain functions on the server without even letting them to look at a code this is exactly how a web api works we are running functions on a server by sending a http request to a certain url or endpoint and the server will send us back the result of the function one thing to note here is that different http methods could have different behavior on a certain endpoint for that you need to consult the documentation provided by the applications developer for example if we send a get request to the login endpoint the server might run the function that will return us a html document dac however if we send a post request to the login endpoint the server will trigger a different function this time it might take a look at the request body for the credentials look up in this database and try to find the matching credentials if it found one then the user is authenticated otherwise the server will show us back an error in json format all these behavior of the endpoints are all predefined by the author of the application so if we want to use a web api provided by an application the first thing to do is to read through the documentation and go through all the endpoints and see what they can do let's take a look at an example now we'll be looking at github's api going through the documentation here we can get a list of open source licenses from the api as we can see here it's a get request i'll just copy the link here and paste it inside the browser's url bar by default the browser will perform a get request on the url that we entered in the url bar and now we're seeing a json string returned back by the api endpoint which is an array of licenses if you're using the chrome browser you might not be seeing this pretty printed json string out of the box i'm using this extension called json formatter to do the job for me the link is in the description if you're interested now there's one last thing i want to go through before we end the lesson which is the concept of http codes you might have already noticed this already whenever we send a request to a server there is this thing called the status code being returned back in the response header the status code is also known as the http code and as a convention we normally use these codes to indicate whether a http request is successful or not if you go to this website you can take a look at all the standard http codes that are used in the internet today just a quick overview the 200 series normally means success without any errors the 300 series normally means redirection where the server wants to send us to a different web page for example after we logged in the server might want to send us to the app dashboard and in that case the server will return us a status code of 302. the 400 series normally means that's an error within our request it could be our endpoint is misspelled or the payload is incorrect or we are unauthenticated the 500 series means there's a bug on the server side and that's usually nothing we can do when we see this error other than contacting the site's owner i hope it makes sense so far we'll be building a very simple app in the next lesson using web api and javascript i'll see you there key takeaway for this lesson apis are just functions exposed by a software where we can use the api to interact with the software programming api are consumed within the programming language itself we call the functions directly inside the code in contrast web api are consumed via http where we don't have access to the source code of the software by using http requests to trigger functions of the software http comes with two parts the request and the response the browser will send a request to the server and the server will reply back with a response and both of the requests and response would have a header and a body the header contains metadata about the request or response while the body contains the payload hey there is sam so in the previous lesson we learned about api and http but we haven't really gone through how to use api in javascript yet here's the app that we'll be building by the end of this lesson using web api this is a very useful app for us to answer yes or no questions let's try it out we'll ask a question and the computer will decide for us let's try it one more time bam we get a no again okay let's give it another try for one last time damn it is smart so before we dive into the code i want to quickly introduce you on how to send out http request using javascript so that's this api here that will fetch us all sort of information about the latest status of copy 19 across the globe and here's the documentation the link is in the description if you're interested let's use this api for a little demonstration here we'll try to call this country's endpoint so i'll copy this link and now let's go to vs code we'll create a new variable for this api endpoint the browser has offered us a very simple way to send out http request using the fetch function the fetch function accepts two argument the first argument is the api endpoint so i'm going to pass in url in there and the second argument is the option for our api request so the options include the method of our http request which in our case here will be a get request so i just need to put in the string get we'll also put in the headers which will be telling the server that we only want to accept json response there are other options available the documentation again is attached in the description below now the fetch function is an asynchronous operation and it will return us a promise so to handle the response we'll need to call the dot den function on the promise and the callback function accepts one argument which is the raw response of the api represented by a special response object we know that this api is returning us a json body so to read the response object in json format we'll need to call the json function on the response object the json function here again is returning us another promise and we'll pass a result to the next then let's console out the response and we'll see it inside the browser and we get a massive array with 248 elements in it which is the expected api response as written in the documentation and from line 21 and onwards it will be up to us to do whatever we want on the data that we got from the api response the possibilities are endless we could build a chart to display all this data or to build a travel app that indicates how safe a country is if we were to travel to there okay now that we know how to use a fetch function let's build our decision making app first of all let's put down our layout we'll need the form for the question input and we'll put down a label and the input element with an id of task and inside the label we'll put down the heading for our input let's see how it looks like in the browser looking good we'll put in some placeholder for the input field as well our form is aligned to the left at the moment which is not that great let's center it with flexbox we'll create a few helper css classes d flex to set a display property to flex so that we can create a flex container justify center to center items on the main axis flex code to set the flex direction to column and align center to send the items on the cross axis and now let's apply our helper classes on the form we'll make it a flex container and set a flex direction to column to align the items vertically and then we'll apply our align center class to center the items on the cross axis which is on the horizontal axis let's test it looking great after the form we need a place to display our result we'll create a new section and give it a class of image container within a section we'll put an article to display the yes or no image and after that we have a h1 to display the word yes or no and that is our basic layout let's start writing our javascript now before we move on let me show you the api that we're going to use in this app it's a website called yes no dot wtf so the idea is every time we refresh the page this website is going to give us either yes no or maybe depending on our luck and if you look on the lower left corner they do provide us an api which is exactly what we're going to use in this lesson so this is a get request with the url of slash api let's store this url as a variable in our script so we can reference it later next before we start coding let's write down our story or the pseudocode for our app here's the plan when the user type in a question in the input and hit enter we should then call the api once the request is completed then we'll display the result in the image article and answer text element so first of all let's add an event listener to the form element we'll listen to the submit event and we'll create a handler function called decide inside the desired function the first thing we want to do is to call the prevent default function to stop the page from refreshing from the submit event since we have an input inside the form element every time the user hit enter it will trigger the submit event on the form and that would trigger our desired event listener next we'll try to call the api so i'm going to call the fetch function and pass in the wtf url with some options method will be get and headers will be accept json next in a then function we will retrieve our api response and store it inside a variable called result response.json is returning us a promise and we're using the async and away keyword here to make our code a little bit cleaner so we don't need to change the result to the next then result object contains three fields answer force and image we should put the image property inside an image element and load it to the dom so let's create an image element set the source attribute to the image property in the result and put it into image article we also want to put the answer property into the answer text element so let's do that as well all right let's test our code oops i've got the type of that let's try it one more time boom it's working let's give it another try and that's an issue the new image is appended to the dom without clearing the existing image let's fix that so before we call the api we should really clear out any existing content within our image article element and the answer text element we can do that easily by setting the inner html property to an empty string and now it's working fine but it takes a few seconds for us to get the result from the api in other words the user needs to wait for a few seconds after hitting enter on the input field let's set up some sort of loader during the waiting time i'll put in a new article element and have a heading says let me think in there and by default we should hide this element so let's create a new class called hide and i'll set the display property to none next we'll create some helper function to show this thinking element or to hide this thinking element in a short thinking function we'll simply remove the height class from the class list of thinking article in contrast in high thinking function we'll add the height class to the class list of thinking article and then before we call the api we should call the show thinking function to show the loader and when the api code is finished we'll then call the high thinking function let's test our code and the thinking heading is showing functionality wise our app is completed but it looks very ugly at the moment let's start first of all let's change our background color and also the font we'll target the body element change the font family and make a dark theme background with white text next we'll start the input first of all change the background color to transparent and we'll give it a default border of one pixel solid and we'll set the font color to this grayish purple and set the font size to large give it a little bit of breathing space by setting the padding to 10 pixel and also increase the width to 500 pixels when the input is focused we also want to increase the border width and change the border color to slightly lighter and also remove the outline next we should make the result center and also the thinking loader center to do that we just need to add our helper classes to the image container element set it to flex and also justify center working great but now we do want our answer text to sit on top of our image to do that we can make its position absolute and set the position of our image container to be relative so the absolute position of answer text is relative to this image container and will also make the answer text uppercase by setting the text transform property to uppercase let's test our code working great and one last thing let's just add a little bit of space on the top of our image container i'll set margin top to be 50 pixel and give it a final run everything looks great so that's a quick intro on how we can send api requests in javascript using the fetch function it is a very useful function and we'll be using it more in the future lesson when we get to learn to build our own api server if it doesn't make sense to you feel free to re-watch the video or visit the documentation the link is again in the description key takeaway for this lesson we use the fetch function to send http requests in javascript the fetch function accepts two arguments the first argument is the api endpoint in other words the url that we want to send the request to the second argument is an object that represents the options related to the request the fetch function returned as a promise which means it is an asynchronous operation and we should call the dot then function to handle the response of the api that's it for this lesson and i'll see you again in the next video hey there sam sometimes we just want to test a certain api or play around with the api as we read through the documentation but do we really want to go through all the trouble of going to our code editor writing the fetch function and finally running our javascript in the browser personally i think this is just way too much of work just because i'm a lazy aka efficient person so let me introduce you a better way to do this that's an app called postman that will solve our problems in just a few clicks let's download the app and run it the link is in the description once you sign into the app this is probably the first thing that you will see it looks very scary so let's just click on the close button and then you'll see this screen and this is where we spend most of our time on imposement so here we can select our request method the api endpoint and the configuration of our request we can put in any parameters that we want to send along with our request the authorization type the request headers body or write a pre-request script for people who wants to automate some tasks and the test panel is for automation again which is for advanced applications and we won't be looking into it in this lesson now let's try to send our very first api request let's type in google.com in the url bar so now we're sending a get request to google.com and we get a html document back in the response body we can select a pretty printed version where postman will highlight the syntax and the raw version which is just a plain response from google and preview will be the rendered version of this html document postman also allows us to investigate the cookies and headers of the response all the data is listed in here let's take a look at a more concrete example here's the copied api that i introduced to you in the last lesson the link again is in the description if you want to take a look let's pick an api endpoint that accepts parameters this endpoint here will get all copied cases for a certain country and this endpoint accepts two parameters the from and two parameters the from is a starting date and two is the ending date of our data let's try to call this endpoint imposement i'll copy the main url without the parameters and paste it inside the url bar now i'll put in the from and two parameters according to the documentation click on the send button and now we see an array of data returned from the server let's try to change from and to date and see if that's working and the data now returned back is now based on a to and from dates if we want to test different types of http methods remember we just need to select the corresponding methods from the drop down here so that's a quick intro to postman it is a great tool to test out api and investigate the responses key takeaway for this lesson postmod is a wonderful http client we can use it to send http request to test out different kind of api endpoints that's it for this lesson and i'll see you again in the next video hey there sm suppose we have an object called car here and we'll set the color to blue now let me create another car and i'll set it equals to car 1 and i'm going to change the color of cartoon to red and if i console out car 1 here what do you think you'll see inside the console would the color of car want to be blue or red pause the video for a bit and make a choice so the answer is surprisingly red what is going on here so it turns out that in javascript objects are references rather than the data itself i'll show you what i mean so behind the scene javascript stores data in a space called the hip and the hip is located inside our computer's memory you can think of the hips as a back that holds all sort of data and this is where things becomes a little bit more interesting so when we created our car one object just now javascript will store the object inside the heap however the variable car 1 is just a reference pointing at the object that is stored inside the heap car 1 is just a reference it is not the object itself so when we created our variable car 2 we're essentially making a copy of the reference so cartoon is pointing at the original object inside the hip as well that means any changes that we made towards cartoon will affect the original object directly since it's just a reference pointing at the object so that's the reason why when we change the color of cartoon the color of car 1 changes as well because both variables are pointing at the same object this is a very dangerous behavior and can cause very nasty bugs in our program so how can we solve this then there are two ways that i can show you one is to use the object assigned function the object of science function accepts two arguments it will merge properties from an object to another object the first argument is the target object and the second argument is a source object in our case here in order to break the reference link or to clone the object we'll need to create a new object so for the first argument i'm putting in an empty object and the second argument will be car 1 so the object assign function will copy all the properties inside car 1 over to the new object that we're creating and now the variable clone here is a reference pointing towards the new object rather than car1 so now let's try to change the color of the clone object to black and we're going to console out car one again now notice that the color of car 1 remains as red and that's a proof that we have broken the reference link clone and car 1 are no longer related the second way is to use something called the spread operator the spread operator is used for unpacking array and objects let's see how we can use it in our case here we're going to create a new variable clone2 and it has to be a new object of course because we want to break the reference link and the content of our new object here should be the same as car one so let's use a spread operator to unpack the content of car one so i'll put a triple dot which is the syntax of the spread operator and car one right after them and this will unpack car one into our new object and now if we change the color of clone 2 to green and console out color 1 again we still see car 1 has the color of red so that's a quick intro to object and references in javascript be extremely careful next time when you want to copy an object now let's talk about the spread operator more the spread operator can be used upon arrays as well spreading an array means unpacking the array for example i can unpack an array to pass the elements of the array as the arguments of the function for example this line of code is equivalent to this another use case of the spread operator is it allow us to join arrays together in a very clean way so suppose we have two arrays here with different numbers and i want to join both arrays together into a third array what i can do is to create a new variable array 3 and inside the array 3 i'll unpack array 1 and array 2. so if i console out array 3 i'll get the combination of array 1 and array 2. and similar to array we can use this technique to join objects together so let's say we have an object one with a property hey in there and another object with a property hey as well and also a food property and now we'll create an object three which will unpack object one and object two and we'll console our object three and we see the hay property and the food property since object 2 is unpacked later than object one and both of them has the same property code hey object two will overwrite the hay property in object one now the spread operator has another form called the rest operator and is only used in functions where we want an arbitrary numbers of arguments let's take a look at an example suppose we have a function called app and this function takes in two arguments x and y and it will return x plus y back it is not very flexible at the moment because we can only put in two numbers each time when we want to use this function we might want to do something like this where the user can put in all the numbers in one go and here's where the rest operator saves our day the rest and spread operator share the same syntax but their meaning is very different spread is for unpacking rest is for joining and the triple dot will only become a rest operator when you put it inside the function's argument definition let's modify our add function so it uses the rest operator in the round bracket i'll put in triple dot and the argument name that represent the arguments passed to this function the rest operator will pack out the arguments and turn them into an array so if i consolidate out nums we will see an array of numbers to complete our add function i'll just write a simple for loop that look through the numbers and return the sum and that's it now we can pass in any numbers of arguments to our add function and it will always work key takeaway for this lesson javascript stores data in the hips and hips is just a location inside the computer's memory objects are references in javascript to make a copy of the object we should clone the object by using the spread operator or the object assigned function triple dots are both the spread and rest operator the spread operator is used to unpack arrays and objects on the other hand the rest operator is used to pack functions arguments so we can write functions that take in an infinite numbers of arguments that's it for this lesson and i'll see you again in the next video hey there sam suppose we have an object called car here and it has a few properties brand name and color now if you want to extract these properties into separate variables one way of doing this is to create them line by line which is pretty tedious is there a better way of doing this yes and it is called object destructuring let's see how it works so here's the syntax if we just want to extract the brand property out we'll put it inside the curly braces on the left hand side and to the right hand side of the equal sign we'll put our card object there so now if we console out brand we'll see toyota if we want to extract the other properties out we'll just put a comma right after brand so can you see how this single line of code is replacing what we had before from line 16 to 18. it is nice and clean right and if for some reason we want to change the variable name into something else we can just put a column after our key and put our new variable name there and now javascript is showing us an error because the variable brand does not exist anymore and now if we console our brand one two three it will print out toyota again we can destructure array as well suppose we have a fruits alright and if i want to extract the first two elements out this time i'll put in a square bracket instead of a curly bracket and assign my variable names inside a square bracket now apple will represent the first element and orange would represent the second element and if we console out apple and orange we see the corresponding fruit string in our fruits array just to be clear you can name your variable to anything you want it doesn't need to match the content of the array i'm keeping them the same just for demonstration only so if i rename my first variable to apple one and console it out it will still work as before array destructuring is a very useful technique if we just want to grab the first or second element of an array if we want the remaining elements to be packed into a new variable we can use the rest operator to achieve this for example let's add a new fruit grape to the end of our array and right after i destructure apple and orange i can pack kiwi and grape together into a new variable called other by putting the rest operator in front of it so now if i console out other i'll get an array containing kiwi and grape we can also skip an element by not assigning a variable while we're destructing the array for example if i want to skip orange i'll just remove my orange variable now the other variable still represents kiwi and grape one of the most useful application of array destructuring is it allow us to swap variable very very easily so now let's say we have two variables a and b and i want to sort the values around traditionally if i want to achieve this i have to create a temporary variable and assign it to a then swap a with b and b to temp which is pretty tedious however with already structuring i can achieve this in just one line of code so here i'm destructoring the array on the right hand side a and b into the variable b and a so now i'm reassigning the variable b to be the first element in the array in other words i'm swapping b with a and the same goes with a and b and that's a quick intro to array and object destructuring key takeaway for this lesson object destructoring is useful to extract properties out already structuring is useful to extract the first few elements out from an array using this technique we can easily swap the values of two variables in just one line of code that's it for this lesson and i'll see you again in the next video hey there sm when it comes to programming there are three types of paradigm procedural object-orientated and functional in the early days of programming there's only procedural styled programming procedural codes are written as step-by-step instructions for example declaring a variable and writing an if statement here are procedural because we're just writing down the instructions in sequential order without any fancy magic although procedural style programming is simple it does have its shortcoming procedural code is very verbal that means it's very explicit because we need to write down the step-by-step instructions in a very detailed way and that makes procedural code very hard to read and lengthy which is not very convenient for us human to read and understand the code it is also very hard for us to reuse procedural code if we want to apply the same logic in multiple places in a lot of time the only way to do this is to copy and paste which is a big no-no so programmers eventually came out with a new paradigm called object-orientated programming to solve the issues of procedural programming now in object orientated programming as the name suggests everything is based on objects so now instead of writing step-by-step instructions in one place we will delegate or separate the task into smaller chunks and put them into entities called object in other words we're hiding the programming logic within object and this concept is called encapsulation in object oriented programming so by splitting our logic into smaller modules it helps us to reuse and maintain our code better in the long run if something breaks we would know which object is causing the problem and we will just need to fix the logic inside that object rather than going through a few thousand lines of code and find out which line is causing the problem we actually have seen object-oriented programming in javascript a lot of times already for example the console.log function this is a perfect example to demonstrate object-oriented programming so the log function is living within the console object and a console object is a built-in object provided by javascript when we use this log function we don't really need to care about how it was implemented all the logic is hidden within the console object as the user all we need to know is that the log function will print out a line in the console and every time we need to lock something in a console we just need to call this function from the console object over and over again in other words we can easily reuse this function across our program another example would be the getitem function from the local storage again the getitem function is just a function that lives within the local storage object we can keep reusing this function wherever we want without worrying about how it was implemented inside the local storage object can you see the benefit of object oriented programming now by hiding the logic within objects we can abstract away the complicated logic and just worry about how do we interact with these objects and it makes our code looks very very clean and easy to read the third paradigm functional programming relies very heavily on functions as the name suggests in functional programming we describe our programming logic using functions and the code will read very much like english functional code is very declarative that means just by reading the code we will know the intention right away i'll show you a quick example so suppose i have an array of fruits here and i want to convert every one of them into uppercase and then filter out the fruits that has less than 4 characters to achieve this in functional programming we'll call some of the javascript array helper functions that use functional programming techniques first i'll map each fruit into uppercase once i'm done i'll call the filter function on the result and filter out all the fruits that have more than four characters now looking at this code it reads a lot like english right and it tells us what it's doing in a very declarative way again when simply mapping each fruit or converting each fruit into upper case and we're doing a filter when we tell javascript we only want the fruit that has more than four characters and that's the whole point of functional programming creating meaningful function so our code will be easier to read and cleaner if we were to achieve the same in an unfunctional way let's compare how it would look like against functional programming code first i'll create an empty array to store our result then i'll have a for loop to look through the fruits all right and in each loop i'll check the length of the fruits if it is greater than four or not if yes then we'll push the uppercase fruit to our result array and now let's just stop here for a few moment and compare these two blocks of code the lower block is much more verbose than the upper block and we have to read and try to interpret it before we can understand the context of this code while the functional programming way tells us right away what the code is doing and that is the power of functional programming we are writing cleaner and clearer code and just one more time procedural programming is where we write our logic as step-by-step instructions object oriented programming oop for short hides logic within objects and we call it encapsulation in programming terms functional programming or fp describe the logic using functions now at this point you might be asking which paradigm does javascript belongs to the answer is surprisingly none of them javascript is a very unique language it is actually based on something called the prototype we'll be discussing more about the prototype in a future video however javascript is a very flexible language and it does support the functional and object orientated style of programming and in the next few lessons we'll be looking exactly on object oriented programming in javascript so i'll see you there key takeaway for this lesson procedural programming is about writing logic as step by step instructions object orientated programming or oop for short is about splitting the logic or task into modular components known as objects so that you can easily reuse our logic functional programming relies heavily on functions and we describe our logic using functions javascript is a prototype based language however it does support features in object-oriented programming and functional programming that's it for this lesson and i'll see you again in the next video hey there sam as we discussed in the last lesson object-orientated programming is all about encapsulating our logic within objects now suppose we want to create a few cars we'll create an object called toyota and give it a name property a brand property and also a drive function and now if i want to create a second car i'll have to write out all the properties again and if i want to correct the third the fourth the fifth car things will become tedious very very quickly it would be great if we can create a template that will create a car for us so we don't have to write everything from scratch is there such thing in javascript the answer is yes and the template is called class let's learn how to create a template for our car object now to create a class we first start with the class keyword followed by the class name and as a convention we would capitalize the class name so next time when you see something with a capital case it's very likely that it is a class and we can create an object out of it after the name we put a curly braces and this is class in the most basic form and now to create an object out of this class we are going to use the new keyword so let's create a new variable and set it equal to new car the new keyword will create a new object out of the class and we refer this process as instantiating a new object out of a class and we refer suzuki as an instance of the car class let's complete our car class now to give a default property to the object instantiated from this class all we need to do is to type out the property name and set it equal to some value and now if we console out suzuki.name we should see a car in the console and there we go however we don't want default value we want the ability to customize the name of the car when we create an object out of a class and this can be done using something called the constructor function in short the constructor function is a special function that will run every time we created an object out of a class to define a constructor function we simply need to type in the word constructor followed by a round bracket and curly braces and just for demonstration i'm going to add a console.log inside the constructor and now we see creating a new broom in the console because the constructor function runs when we created our suzuki object now the constructor function can accept arguments let's make it accepts two arguments name and brand and we supply the value to these arguments at the time when we created the cart object so the name will be swift and the brand will be suzuki and now back in the constructor i'll console out name and brand just for demonstration and we see swift and suzuki in a console now using this behavior we can customize the property of our object instance because now when we create a new car we can pass anything we want as the argument to the constructor we just need to reset the name property to the arguments applied to do that we'll use the this keyword this keyword in any function inside a class represent the object instance created from this class so in our case here that this keyword would represent the suzuki object so for us to change the name property of the object created we just need to set this dot name equals to the name argument and for the brand even though we don't have a default value for it we can still set it to the object instance in a constructor using this keyword and now as you can see in the console.log the suzuki object that we created out of this class has a customized name and brand just like what we passed into the car constructor now the only item remaining for our class is the drive function to define a function we just need to type the name of the function and set it equal to an anonymous function and in our drive function here i'll just console out room room again and that's it i can now call the drive function on suzuki and we see group room in the console that's a shorter way of defining a function in a class we can put a round bracket right after the function name and skip the function keyword all together defining a function this way is exactly identical to what we had previously it's really just a personal preference i like the short version better because i'm lazy and that's it our class is completed we can now create a new car easily using the class that we have just written without writing everything from scratch and again just a quick demo i'll create new instances of car and slightly change the name these three objects are all different to each other and have their own name and brand can you see how easy it is to create a new object out of a class and compare to what we had before this way is much cleaner now the class syntax is actually only available after es6 es6 is a javascript version that was released back in 2015. it is one of the breakthrough in javascript's history that has brought in a lot of good stuff so prior to es6 the way we create an object template is to use something called the constructor function so here's how we declare it i will replicate the car class using the constructor function we'll start with a function keyword and give it a name and again we'll use the capital case and this function will accept the name and the brand of the car and inside the function we can set the name and brand property using this keyword and the drag property will be an anonymous function and that's it and we can instantiate object out of this constructor function using a new keyword as well there's one last thing i want to show you before we end the lesson we can dynamically add a new function to our constructor function or class using the prototype so let's say i want to add a start function to car what i can do is to say car.prototype.start is equal to a function prototype is a special property that exists in every object it is an advanced topic and i'll discuss it in a future video for now we just need to know that prototype can be used to add functions on a class and now i can call the start function on the suzuki object and we see starting car in the console if we do the same on our car 1 constructor function we'll get the same result as well so i'll call the start function on new car and we see starting from car 1 in the console.log as well so that's a quick introduction to class and the constructor function in javascript we'll learn more about object oriented programming in the next lesson key takeaway for this lesson class is the template for creating our object we use the new keyword to create object instances from class a class constructor is a special function that runs whenever an object is instantiated the constructor function is an alternative way to create an object template the class and the constructor function have the same purpose it is just a personal preference that's it for this lesson and i'll see you again shortly hey there sm imagine we're creating a game and this game has different types of characters let's create a class for each of them we'll have a night class and at the time when we instantiate this character we should give it some health and magic in the constructor and let's also add some methods to our knight in object orientator programming a class function is also known as method so the next time when you hear someone mentioning about the word method they're simply referring to a function in an object or class so a knight can walk can fight can write and can charge into an enemy i will not implement these functions as they are not the purpose of this lesson so i'll leave them empty as it is now let's say i want to create a new character type called mage and similar to a knight a match has health and magic as well so the constructor will look pretty much the same and the mage can walk and can fight as well the mesh probably couldn't ride or charge into an enemy so leave them out and instead we're going to replace it with a function called cast which will let the mage to cast a spell now here's the issue both of our class looks very very similar we are repeating ourselves here which is a big no-no is there a better way to do this and the answer is obviously yes we use something called inheritance to stop us from repeating ourselves inheritance is a concept of having a base class or what we call a parent class and we'll have daughter classes that would extend or inherit all the properties and methods from the base class if that doesn't make sense to you let's try to refactor our code so we can use inheritance to solve our issue here so now let's create a base class and i'll call it corrector so the character class will contain common methods and properties that both our knight and mage class would have so i'll move the constructor function to the correct class and also the walk and fight method and now our code is much more shorter than before let's make our knight and mage class inherit from the character class to do that we need to use the extend keyword we'll just type out the extend keyword after the class name so now knight is extending the correct class and therefore has access to all the methods and properties from the correct class and we'll do the same for the mesh class as well and now let's create a new knight object and see if we can call the fight method i'm going to add a console.log inside the fight function definition and call the fight function on karen and it works so karen is a knight and is inheriting everything that characters has to offer there's no limits on the inheritance level of a class for example if we want we can create another class that extends knight i'll call it wario and the extend keyword and night so now wario is a grandchild of character and again it has access to all of the properties and functions of knight and character there's one more thing i want to introduce to you which is the super function so let's say we might want to instantiate knight differently than the other characters in other words we want to overwrite the default constructor function and to let knight accepts different arguments when we instantiate it so to do that we simply need to override the constructor function right well yes and no first of all we're repeating ourselves to set the health and magic property this is not good and we shouldn't be doing this secondly we see this error in the console where javascript tells us to call the super function so the super function is a special function that represents the constructor in the base class and the super function is exactly what we want to avoid repeating ourselves here we can replace these two lines with the super function to let the base class constructor set the health and magic properties for us and that is pretty much it the lines after the super function will be specific to the night class only and we can customize however we want so that's a quick intro to inheritance in object-oriented programming it's a very powerful technique but use it sparingly because it has a massive drawback as you'll see in the next few lessons key takeaway for this lesson inheritance is a concept of a class extending another base class or parent class so that it can access all the properties and methods of the base class the super function is a special function that represents a constructor of the base class so that we can call the base constructor in the child class that's it for now and i'll see you again in the next video hey there sam polymorphism is a concept where there are classes that have the same methods but different implementation for example suppose while writing a payment gateway where we will accept payment and also provide refund let's write a class for that we will have a connect method where this function will allow us to connect to our payment provider and we should call this function inside the constructor so we can connect to our payment provider at the time the object is created we also need a pay method and a refund method to handle payment and refund so that's our generic payment gateway now let's write some specific ones we'll create a class called paypal and it will extend from payment gateway now paypal should have its own pay refund and connect function and those logic should be specific to paypal because paypal will have its own rule when it comes to accepting payment and getting a refund next we'll create another class called visa and similar to paypal it should extend payment gateway as well and will have the pay refund and connect functions and again visa will have its own rule so the implementation of this function should be specific to visa let's create one more example mastercard and the same rules apply it will have its own pay refund and connect functions now can you see a pattern here these classes have the exact same method but the implementation is different and that is exactly polymorphism the same set of functions but different classes and implementation at this point you might be asking why is this useful the answer is because we can reuse and write more generic code let's take a look at an example now suppose we have a customer class and a customer has a function that allows them to make a payment when a customer wants to make a payment they need to specify which gateway they want in other words they will need to choose whether to pay by card or paypal so we'll let the function to accept a gateway argument and the amount to pay since all the gateway has a pay function we can simply call the pay method on the gateway object and this is exactly the benefit of polymorphism it is nice and neat right without polymorphism we might need to implement functions like pay by paypal pay by mastercard or payba visa and implement the specific logic in each of these methods which will make our customer class very messy and hard to maintain in the long run so let's not do that it's much more better to delegate those specific logic into their own class and now moving on our customer also needs the ability to get a refund we'll create a get refund method which looks very similar to our make payment method again every gateway has a refund method so we're just gonna call it in here and last but not least the customer might complain if something went wrong and now let's put everything together let's see how our classes will work with each other first of all i'm going to create a new customer called karen and we also create a paper object and a visa object and now when terence wants to make a payment we can just pass in the paypal or card object into the make payment method and that's it it's very clean and readable but karen will complain regardless that's another benefit of using the polymorphism pattern that is in case we have a new provider in the future we just need to create a new class word without even touching the customer class as long as our new payment gateway has the same methods as the others we can be sure that our code will work alright key takeaway for this lesson polymorphism is a concept where classes have the same method signature but different implementation it helps us to write cleaner and more generic code so our code will be easier to maintain in the long run that's it for now and i'll see you again in the next video hey there sam inheritance using the class syntax is great however it has a major flaw that is not very flexible i'll show you what i mean let's say we have a class called animal an animal can eat and sleep and we have different types of animals out there let's create a mammal class which extends from the animal class and also a bird class extends from the animal as well now our first impression on birds is that they can fly but that's not true ostrich and penguin are birds but they can't fly so it probably will make sense if we create two further subclasses for bird birds that can fly and bird that can't fly in the birkenfly class we'll add the fly method bros that can't fly either needs to know how to run or swim ostrich can run but can't swim while penguin can swim but can't run so what should we do here should we create two new classes that says bird can't fly but can swim and bird can't fly but run can you see where this is going it's getting more and more complicated inheritance using class or what we call classical inheritance is not very flexible and things will get even worse when we take account into the bird's diet some birds are herbivorous and some are carnivorous so we have vegan bird and meat lover bird and that means we have to create even more classes to categorize the birds so for the burke and fly and bird can't fly classes we need to create two additional variants for each of them the vegan variant and the mid-level variant and things will get out of control very very quickly for the broadcom fly class we need to create a vegan and mid-level variant as well and for each of them we need a swim and run variant again the number of our classes will increase exponentially and that will be a big nightmare for us to manage in the long run and that's also another issue with classical inheritance it's very hard for us to share functions with other classes for example imagine the fly method here is a very complicated function birds can fly but there are other animals that can fly too for example insect or mammals like bat is either we copy and paste the code which is very very bad or assigns a function using the prototype now what if i tell you there's a solution that will solve everything that we just discussed it is something called object composition rather than classical inheritance so object composition is the idea of building an object using multiple smaller object blocks rather than defining a massive class where it's not flexible and hard to reuse let's take a look on how we can create an animal using the composition technique first we'll start with an animal object and same as before we'll have an ip method inside the animal object and now here's where we want to shift our mindset for a little bit we need to think about what makes an animal rather than the animal category because we're now going to build our animal using multiple building blocks for example i'll create a new building block called movable and this movable object will contain all the logic to let an animal move we'll also have another building block called flyable which is for animals that can fly and again it contains all the logic for an animal to fly in regards to diet we can create two additional blocks called can eat meat and can eat veggies for herbivores and carnivores if an animal is both meat and veggies then we simply add these two blocks to the animal we'll also add our swimmable block for animals that can swim and runnable clock and now our building blocks are ready let's see how we can create an animal using these building blocks let's create a penguin and it is equal to a function and the function will return a new object so the idea here is that i'm going to merge the building blocks that will have written so far with this object there are two ways to do this the first way is to use the spread operator so we'll unpack the building block that we need into the penguin object so the penguin is an animal so we need the animal object and also the movable swimmable and the can it meet object and that's it our penguin object is completed so the next time we want to create a new penguin we just need to simply call our penguin function let's see if that works and we see the object in a console so far so good the second way of merging objects together is to use the object assigned function where we discussed in a previous video so basically the first argument is the target object in other words the object where we want to merge the other objects into and the following arguments are the objects that we want to merge so again it will be animal movable swimmable and can it meet and our console.log is printing out the same as before so it's working just fine i prefer the spread operator way so i'll comment out object assigned we also want the ability to let the user to customize the penguin object so the penguin function should take in an argument i'll call it option and set a default value to an empty object and back in the object i'll just unpack the options now take a brief moment and review what we have done so far building an object using the compositional way is way cleaner and more flexible we can reuse our building blocks on other objects as well and we can easily add or take out features on different objects as we see fit isn't that neat let's create another example to make this concrete i'll create an ego and again it'll take in an option argument and to build the eagle object we need animal movable flyable can admit and the option argument we don't even need to care about classes anymore and that is the beauty of composition it is highly flexible and we can reuse the building blocks in any way we like comparing against classical inheritance the composition way is much cleaner right let's test our ego function and it works now that we learned about the benefit of using composition over inheritance does that mean we should ditch inheritance completely the answer is no there are still cases where inheritance can be very useful in the end it's just a personal preference and you should decide the structure of your program however as a general rule i do prefer composition over inheritance as i have less issues writing code in a composition way key takeaway for this lesson inheritance is not very flexible and it can be hard to maintain so use it sparingly object composition is a better way to create an object template rather than using a class object composition is the idea of building an object using smaller building blocks and join them together into one big object that's it for now and i'll see you again in the next video hey there sam when you console an object instance have you ever seen a property called proto attached to the object instance confused i'll show you what i mean let's say i have a constructed function called fruit that accepts an argument color which i'll then use it to set to the color property of the object instance then i'll create a new object banana out of this constructor function and let's console our banana so in the browser as expected we see our fruit object in the console however there's an extra property called proto in our object what the hell is that let's expand it and we see more crazy stuff but hold on this constructive property looks interesting does that look familiar to you it looks like our fruits constructor function here why don't we try it out i'll create a new variable apple and set it to new banana proto constructor and pass in our apple argument in it and console our apple and it works we're getting another instance of our fruits constructor function so what the hell is going on here let's go through it step by step the product property is a special object called prototype in javascript javascript will automatically attach this product property to every single object that we create in javascript and everything in javascript is an object by everything i mean everything accept two things now and undefined so if i have a string here since everything in javascript is an object by theory i should be able to grab the product property of our string here let's load it out and there is something in there and it is referring to the strings prototype object let's go through the rules of prototype in javascript rule number one every constructor function or class has one and only one prototype object so that means the prototype object is shared across all the class or constructors instances rule number two every object instance has a product property as we seen just now in our fruits instances the product property is a reference or link to the prototype object of the constructor function rule number three the prototype object has a property called constructor which is referred to the constructor function itself just like what we have seen just now when we created the apple object on line 17. still confused let's put this on the diagram so we can visualize this so here's our fruit constructor and this is its one and only prototype and we have instances on the left hand side so just now in our code we created the banana object using the fruits constructed function and the banana's product property is referring to our prototype here and the prototype object has a constructive property that is pointing back to the constructor function itself and we can use that constructor property to correct new instances of fruits one constructor function can only have one prototype so if we have more instances of fruits the product property will point towards the same prototype object now spend a few moments and try to understand this diagram if you can digest this you will now understand the basic on how prototype works in javascript so going back to our code since the product property is just a reference to the prototype object so in theory if we compare the two using the equal operator we should get true and we do get true which means great and i'm not lying to you now object instances can access to all the functions that we put in inside the prototype object so if we add an eat function to the prototype object we can now call the it function on all instances of fruit because again based on rule number one the prototype object is shared across all of the instances so now it brings us to another question what's the difference between creating a function within a constructor function again storing the function inside the prototype object if the question doesn't make sense let's take a look at this example now suppose i have a constructor function called car and i create a new instance method called drive using this keyword in other words i'm creating this function inside the car constructor function and now in a second case i'll create another constructor function called car 2 and this time i'll put a drive function inside a prototype so what are the differences between these two which one is better the answer is the car 2a is better and more efficient why because in the first way every time we create a new car object javascript has to create a new function from scratch and assign it to the drive instance property so there will be one new function for each car instance so if we got 1000 cars that means javascript has to create 1000 drive functions for all these instances in the second case however since we are storing the drive function inside a prototype and the prototype is shared across all the instances javascript no longer has to correct the drive function from scratch for each new instance of car so there's only one drive function so that's why storing function inside a prototype object is better and more efficient before we move on let's take a look at another example we can create an array using a square bracket or using the array constructor function we simply need to type in new array just like how we create our fruit object now based on what we have learned so far with the product property of our array instance equals to the prototype object pause the video and think about for a second the answer is yes next question with the constructor property inside the prototype equals to the array constructor function itself the answer is yes again the last question with the constructor property inside the product property equals the array constructor function itself the answer is yes of course because the product property is referring to the prototype itself if you got any of this wrong be sure to rewatch this section and make sure you understand the basic of prototype because we're going to dive even deeper next now i want to quickly show you something before we move on let's take a look on what is inside the array prototype there are a lot of things in there do you find them familiar these are the array functions that we have been using so far so javascript stores all these functions inside the array prototype instead of loading them in every single array instance and just like what we have discussed before this is a good thing to do because we're not wasting memory all right let's move on i want to introduce you something called the prototype chain in javascript everything in javascript is an object so it's okay to say that everything in javascript inherits from the object constructor and we know that every object has a proto property that refers to its prototype and that brings us to a question what is the prototype of a prototype let's see what will happen if i print out the product property of the arrays prototype it seems like we're getting the prototype of the object constructed function let's test our theory and we get true what is going on here so going back to the point that we made before everything javascript inherits from the object constructor javascript actually builds its inheritance system based on the prototype so when we try to access the product property of the arrays prototype we're essentially accessing the prototype of array's parent which is object let's go back to our diagram and go through this in more details so we have the object constructor here as the parent of our fruit constructor function and this is its prototype so if we try to access the proto property on any of the fruits instance it'll point us to its parents prototype which in this case is the object's prototype so let's put everything together the object is the root ancestor of every data type in javascript the other types of object like array or our custom constructor function fruits here simply inherits from the object the inheritance system is based on prototype so behind the scene when we inherit something javascript will simply build the new constructor function on top of the prototype of the parent object so it kind of form a chain of prototype and we call this chain the prototype chain and we can look up this chain by keep calling the proto property on any object instance with each proto referring to its parent prototype we're able to call the product property until we reach the end of the chain which is the object prototype now this brings us another question what would happen if we print out the product property of the object's prototype we get now why because as we discussed object is the root ancestor of everything and there's nothing else above it so its prototype will be now okay let's take a look at a few more examples to make this concrete i'll create a variable name and store a string in it our name variable here is now an instance of string what do you think is the product property of name if we console.log it we see the strings prototype and again name is an instance of string so the proto property will point at the strings constructor's prototype what about the product property of the strings prototype we see the prototype of the object's constructor because object is the parent of string so we're simply getting the prototype of the parent here and if we print out the proto property again on the object's prototype we will see now just like what we discussed before let's look at one more example before we move on let's create a num variable and set it to one what is the product property of num we'll console log it and it is a prototype of the numbers constructor function next question what is the product property of the numbers prototype console. and we see the object's prototype as expected now let's move on so we know that everything in the prototype object is accessible by all instances here's how it works behind a scene when we try to call a function inside an object javascript will first try to look for the function inside the object instance if the function is not found then javascript will try to look inside the prototype object of the constructor function if it is still not found then it will look inside the parent's prototype and keep going until we reach the root ancestor which is the object constructor's prototype so knowing that if we add a function to the object's prototype that means this function will become available to all object instances in javascript for example if i add a function called hey to our object prototype and i create a new instance of array and try to call the hay function on fruits guess what will happen it works why because of the rules that we described just now so when we call the hay function javascript is going to look inside the fruits instance which there's no function code hey next it's going to move on to the array prototype and there's still no such function called hey so javascript will then move on to the next parent which is the object instance and find the hay function inside the prototype which is the function that we just defined so we see hey in our console so the concept to take away from here is that every object instance has access to everything inside their ancestors prototype objects now for the last part of this lesson let's talk more about inheritance let's create a person class if i console out the prototype of person we see its prototype as expected and the product property of the prototype is again pointing at the object prototype nothing special here just like what we have seen so far now what about if i create a child class for the person class let's create a class called student and extend from the person class if we consult out the prototype of student we still see the prototype of student but now with the name person attached to it because it is extending from the person class so far so good but what about the product property of the student's prototype we see the person's prototype why because person is the parent of student and the product property is pointing at a parent's prototype so we see the person's prototype object and if we go one more level up we'll see the object's prototype again and that's how javascript builds its inheritance system every time we create a child class we're simply extending the prototype chain the way javascript does things is very different than the other languages the concept of the prototype object is very unique and different than the other programming languages again the concept of prototype is an advanced topic in javascript if you can understand this you're now in a good position all right key takeaway for this lesson prototype is a special object that is attached to every constructor function a constructor function can only have one prototype and it is shared across all its instances so all the instances have access to the properties and functions inside the prototype object the object constructor is the root ancestor of every data type in javascript javascript's inheritance systems is based on the prototype chain that's it for now and i'll see you again in the next video hey there sam imagine we're writing a massive program a program that has a few thousand lines long putting all this code inside one file is certainly not the best thing to do because it is very messy and very hard to maintain in the long run so what should we do then well we could split our code up into multiple files and load them in inside index.html in sequential order that looks something like this however this is a no-go as well because it's very hard to keep track of the variable names on the global scope we could have the exact same variable declared in app1.js and app3.js in other words the global scope would be a mess to maintain if we were to write our program in this way it's very hard to track what variables have been declared and what functions are available so that's no goal as well is there a solution for this the answer is yes it is called the es6 modules and just a quick recap es6 is a version of javascript that was released in 2015 and it brings in a lot of good features to javascript and modules is just one of the many the concept of module is where we write our code in small packages all the variables and functions that we declared inside the module stay inside the module unless we export them and when we import this module in another file the variables and functions that we exported will be usable let's take a look at how we can use modules in action so i'm going to create a new file called app.js and this is where we'll put our main logic in and now back in index.html we will need to load app.js now in order to make more juice to work we have to set the tab attribute to module in our script tag if we don't do that javascript will show us an error now let's go back to app.js and suppose we're building a calculator we'll need some mathematical functions like add or subtract let's build a module for that we're going to create a new file called math.js and that will be our math module where we store our mathematical functions for modules javascript actually allows us to use a dot mjs extension rather than a normal.js extension using the dot mjs extension makes it clear that this file is a module but naming modules with a js extension is ok as well i'll use the dot js extension for now so inside our math.js module let's define our mathematical functions i'll quickly define two functions add and subtract for the add function you'll take in arbitrary numbers of arguments and calculate the sum and the subtract function will look very similar to the add function once we're finished defining the functions it's time for us to export these two functions here are the rules when it comes to exporting modules rule number one we can export multiple things in one file as you'll see later we'll be exporting the add function and our subtract function here rule number two there are two types of export one is called export default which is also known as a name export the other one is called name export let's explore them in more details with export default whatever we exported in this way will become the default import of this module here's the syntax we simply need to type in the export keyword and the default keyword and whatever we put after the default keyword will become whatever we import so if i put a string abc here it will become the default import of this module let's try to import this module in our app.js file so to import our default export we need to type the import keyword and give a name to our unnamed export in this case i'll just call it math and after that we have to specify which module we're importing so we'll use the from keyword and the path to our module now if we console out math we should see the string abc because abc is the default export of our math module let's run this in our browser and we see the string abc in the console so far so good an important takeaway here is that whatever we export will be whatever we import and typically we will put an object in the default export let's try to export our subtract function and we can already see the console in our app.js is printing out an object that contains one property which is our subtract function so back in app.js if we want to use our subtract function we just need to call the subtract property from the math object and it works alright next let's talk about name export so name export is pretty similar to default export the difference is we don't put in the default keyword when we're exporting and when we're importing we have to be specific on what we're importing from the module so let's try to export our add function using the name export method so we're just going to type in the export keyword and followed by the object and put our add function in it now back in app.js to import a name export again we're going to use the import keyword and now we have to specify which item we want to import from the module the way to do that is to use a pair of curly braces and put in the name that we want to import we're importing the add function here so i'm just going to type in add and after that similar as before we'll use the from keyword and the path of our module and now let's try our add function and it works sometimes we want to overwrite the name of the export so to override our add import here we could use the s keyword and supply our own custom name after it and now in a console log instead of calling the add function we'll just call our some other name variable and it works just like before the reason why we might want to overwrite the default name of our import is that we could have variable name collisions in the same file so using the as keyword we could name our import differently and avoid any collision if there's any there's no restriction on how many exports we can use inside one module we can have as many as we like so i could export a variable hey here and another function called hello and back in app.js we can import them separately inside the current braces however it's a good practice that we put everything inside an object under one export keyword because it's clearer and we don't need to look for dxmod keywords all over the place alright key takeaway for this lesson es6 modules help us to organize our code and improve reusability across our app we can just write our module once and import it anywhere in our app there are two types of export the default export and the name export when we import a name export we'll need to specify what item to import but not with default export that's it for now and i'll see you again in the next video if you enjoy the content of this video don't forget to hit the like subscribe and the bell icon for more content to come it will really help me out thanks for the support [Music] you
Info
Channel: Acadea.io
Views: 5,981
Rating: undefined out of 5
Keywords: javascript, intermediate, js, oop, functional, crashcourse
Id: 8hKo9Xa4cXk
Channel Id: undefined
Length: 130min 46sec (7846 seconds)
Published: Mon Apr 19 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.