ES6 Tutorial: Learn Modern JavaScript in 1 Hour

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] in order to build applications with react you should have at least three months of experience programming in JavaScript so in this section I'm going to cover the essential JavaScript features that you're going to use a lot in react applications such as let versus Const P words objects that this keyword and how it behaves differently arrow functions object is structuring the spread operator classes and modules make sure you know all these topics well before going further otherwise you're going to have a lot of difficulty later down the road I just need to clarify that in this section I'm not gonna go really deep in these concepts because this is a react course not a JavaScript course as I told you before I've got two other JavaScript courses for you one is called JavaScript basics for beginners and the other is object-oriented programming in JavaScript the focus of the first course is on the art of problem solving it teaches you how to think like a programmer unfortunately there are a lot of developers out there in the industry who can build applications with angular react and all kinds of fancy frameworks but they cannot solve simple programming problems because there are self-taught programmers they have never attended a college or university they never learned the fundamentals of computer science and software engineering and that's why I've designed this course the focus of the second course is on more advanced topics such as constructor functions objects prototypes inheritance polymorphism classes and more all right that's enough introduction now let's get started [Music] you to demonstrate the modern JavaScript features I'm gonna use a brand new react project so in this project let's open up index j s and delete all the code here and focus on plain vanilla JavaScript so the first thing we're gonna look at are the new keywords for defining variables and constants so let's define a function call it say hello here I'm gonna define a loop so for VAR I we set this to 0 as long as it's less than 5 we increment I and login on the console pretty simple right let's call this function save the changes back in the browser so here we see these numbers 0 to 4 pretty straightforward however there is a problem with the VAR keyword in JavaScript in most programming languages when we declare a variable that variable should only be accessible in the block in which it's defined this is what we call scope right so in this case I should only be accessible inside of the for block however I can come here and log I on the console and you will see that I is still accessible here save the changes back in the browser look we've got I displayed here because in the last iteration I becomes 5 and because 5 is not less than 5 we exit this loop so this is what I want you to take away when you declare a variable with the war keyword that variable is accessible inside of the function in which it's defined and this is one of those weird things about JavaScript that is different from other programming languages so in ECMO script 6 or es6 which is the version of JavaScript introduced in year 2015 we got a new keyword for declaring variables and that is let so let came to solve this problem when you declare a variable with the let keyword that variable is only accessible inside of that block let's see the result so same to change us back in the browser now we get this error on the console I is not defined so here's what I want you to take away variables declared with the VAR keyword are scoped to the function whereas variables declared with the let keyword are scoped to the block in which they are defined so going forward you should prefer to use the let keyword unless you have a very valid reason for using the VAR keyword now we also have another new keyword in es6 and that is Const we use cons to define constants I'm going to show you that in a second but similar to let variables defined with Const are also block scoped so they are only accessible inside of the block they are defined now let me show you the difference between let and Const so I'm gonna delete all this code here let's define a variable with Const set it to 1 now if we reassign this and save the changes back in the browser you can see that X is read-only in other words when you declare a variable with the Const keyword that variable cannot be reassigned that's why we refer to that as a constant so technically it's not a variable because it cannot change it's a constant so let's quickly wrap up throw away the VAR keyword and prefer to use Const over let use let only when you need to reassign a variable alright now let's take a look at objects so once again I'm gonna use the Const keyword to define a variable well more accurately a constant and set it to an object so as you know objects in JavaScript are collections of key value pairs so I'm gonna add a couple of key value pairs here the first one is name which was set to a string and the second is wok which was set to a function now in object-oriented programming terms if we have a function inside of an object we refer to that function as a method so here we say Walk is a method in the person object now starting from es6 there is a cleaner and simpler syntax to define a method in an object so let's add another method here I'm gonna call this talk now here we don't need to add a colon and the function keyword we can define it like this so basically we drop the colon and the function keyword and here's the result so here we have a personal object with three members one property and two methods there are two ways to access these members we can use the dot notation which you are probably familiar with so dot talk or walk we can also use the bracket notation so person we add square brackets pass a string and this string determines the name of the target member so if you want to access the name property we pass that here and now we can reassign that to a different value in terms of practicality we use the bracket notation when we don't know ahead of time what property or method we're going to access let me show you what I mean so I'm going to define a constant call it target member and set it to name imagine this target member is an input field on a form depending on what the user types in that input field we're going to access a different property in this personal object that's when we use the bracket notation so instead of hard-coding name here Pass Target member and once again this could be an input field so we could access the value property like this and then dynamically access a property or a method in an object if we know ahead of time what property or method we're going to access we use the dock notation so we write person dot name we set it to a different value next we're going to look at that this keyword in JavaScript so we have this person object with a walk method now let's modify this method and do a consult that log of this what is this this is a special keyword in JavaScript which confuses a lot of developers because it doesn't behave the same as this in other programming languages like C sharp or Java in this languages this always returns a reference to the current object let me show you so here I'm gonna call person dot walk save the changes back in the browser so we see our personal object on the console so in this case this is returning a reference to this person object right however this in JavaScript does not always work that way let me show you why so I'm gonna define a constant call it walk and set it to person dot walk note that I'm not calling the walk method I'm just getting a reference to this function so walk is now a function let me show you so console the log of walk now back in the browser so you can see our walk constant is set to this function right now let's see what happens when we call this function so I'm gonna call walk save the changes back in the browser what's going on here so we don't get a reference to the person object we get undefined that's why I told you that that this keyword in JavaScript behaves differently from other programming languages the value of this is determined by how a function is called if we call a function as a method in an object this will always return a reference to that object however if we call a function as a standalone object or outside of an object this will return the global object which the window object in browsers but in this particular implementation we didn't see the window object here we got undefined the reason for this is because in this react project the strict mode is enabled by default if you're not familiar with the strict mode it's basically a mode to execute JavaScript code in a more protective way so it prevents potential problems that's why in this case instead of getting a reference to the window object we get undefined so in the last lecture you learned that when we call a function as a standalone function outside of an object this by default returns a reference to the global object which is the window object and if the strict mode is enabled it returns undefined in this lecture I'm gonna show you how to fix this problem so no matter how we call the walk function this will always return a reference to this person object so one thing that might be new to you is that in JavaScript functions are objects so here person dot walk is actually an object don't believe me let me show you so dot look these are all the members of the walk object so every function in JavaScript is an object with these members we've got this method here bind and we can use this method to bind a function to an object what do you mean by this so when we call this note the first argument is called this auric what we pass here as an argument will determine the value of this in this case if I pass this person object here the point method will return a new instance of this walk function and set this to point to this person object so now when we call this walk function we will see this person object on the console let's have a look save the changes back in the browser look the blind method fix our problem so let's quickly recap functions in JavaScript are objects they have properties and methods we can use one of the important methods that you see in a lot of reactor applications is the bind method with the point method we can set the value of this permanently so when we call bind on the walk function we get a new walk function and in that walk function the value of this is based on the argument that we pass to the bind method so because here we're passing the person object as an argument we'll get a walk function that is always attached to this person object and that's why when we call it here without a reference to the person object we'll still see the person object on the console one of my favorite features in modern JavaScript is arrow functions so let's define a constant call it Square and set it to a function that takes a number and simply returns number times number so this is the old JavaScript now starting from xmas script 6 we have a cleaner way to write the same code so let me duplicate this so you can see both versions side by side to convert this function to an arrow function we get rid of the function keyword and put a fat arrow between the parameters and the body of the function now if you have only a single parameter we can exclude the parentheses if you have zero parameters we have to add empty parentheses so this is a function that takes no parameters okay now let's revert this back we have a single parameter number now if the body of our function includes only a single line and returns a value we can make this code even shorter we can get rid of the return keyword as well as the curly braces and this is the end result so the code we have on line 5 is exactly equivalent to what we have here you can see the syntax is cleaner and more compact and you can read it like number goes to number times number so we can call this square function like this and lock the result on the console and let's remove this otherwise we'll get an error because we have declared the square constant twice so save the changes back in the browser we get 25 on the console now let me show you where these arrow functions are really useful let's imagine we have an array of jobs so each job object has maybe an ID and a property called is active which was set to true or false now I'm gonna add a couple more here and make the first two jobs active and the last one inactive okay now let's imagine we want to get only the active jobs so we call jobs that filter method the argument that we pass here is a predicate function a function that takes a job object and returns a true or false so when we call the filter method this method iterates over this array for each job object it takes that job object and pass it to this predicate function the job of this predicate is to determine if that job object should be returned from the filter method so here we can return job that is active if we return true here that job will be returned from the filter method so we can get the final list and call it active jobs okay now here we have a simple function and this is a perfect opportunity for us to use an arrow function and make this code cleaner and more readable so I'm gonna duplicate this line so we can compare them side by side so as I told you to convert this to an error function we get rid of the function keyword delete put a fat arrow between the parameters and the body now we have a single parameter so we can get rid of the parenthesis and you have a single line here we're simply returning a value so we can get rid of the return keyword as well as the curly braces and we don't add the semicolon here so this is the end result you can see this code is cleaner and easier to read so filter jobs where job is active there is less noise in this code one thing you need to know about the arrow functions is that they don't rebind this let me show you what I mean so I'm gonna start by defining a person object here we gonna have a simple talk method let's log this on the console okay so we call person the talk what do you expect to see on the console a reference to the person object right let's make sure everything's working so back in the browser so we have this and next to that we have a reference to our person object right now let's see what happens if you wrap this line inside of a call to the set timeout function so as you probably know in JavaScript we have this global function set timeout we can give it a function and a timeout value let's say 1000 milliseconds so set timeout we'll execute this function after this delay one second right now in this callback function I want to log this on the console so previously when we logged this on the console we saw the person object now let's see what happens when we lock this inside of this callback function so save the changes back on the console we get the window object not the person object what's going on here the reason this happened is because here this callback function is not part of any objects so it's not like the talk method in the person object it's a stand-alone function and as I told you before when we call a function as a standalone function outside of an object by default this returns the window object now in the previous example instead of the window object we got undefined because in that particular case when we got a reference to a method in an object the strict mode kicked in and returned undefined instead of the window object but in this particular case in case of callback functions the streak mode does not overwrite this behavior so this returns a reference to the window object so how can we solve this problem in other words how can we have a reference to the person object inside of this callback function well here's one solution so in the old days we used to declare a variable call it that or self and set it to this so we set this variable outside of this callback function and now we can use self inside of this callback function to get access to the person object right so now let's log self on the console so self and self save the changes back in chrome you can see we have a reference to the person object so this is the pattern that we used in the old days now with error functions we no longer have to do this because arrow functions don't rebind this in other words if we change this callback function to an arrow function it will inherit that this keyword let me show you so I'm gonna change this to an error function and revert this back to this this write save the changes back in the console you can see this returns a reference to the person object in other words here in this callback function because we have used the arrow function syntax this is not reset instead it inherits this in the context in which this code is defined so this is what I want you to take away arrow functions don't rebind the disk keyword ECMO script 6 introduced a new method in arrays called map this is a very useful method and in react we use it to render lists as you will see in the next section so whenever you want to render a list of items that's when you use the map method of arrays so let's say we have an array called colors with three items red green and blue let's imagine we want to render these using list items so for each color we want to have a list item like this right so we call the map method on this array colors map here we need to pass a callback function the job of this function is to transform each element in this array so this function is called by the map method for each item in this array it takes one item at a time and returns a new item so a callback function takes an item and returns a new item now in this case I want to rename this item to color because we're dealing with an array of colors now we take a color which is a string we simply return a new string like this we had the opening li tag plus color plus another string that includes the closing Li tag now this map method returns a new array so it does not modify the original array let's call that items ok now we can simplify this code we can make it cleaner so we have a callback function it's a very simple function and a great candidate for converting to an arrow function so we get rid of the function keyword and put a fat arrow here we have a single parameter so we can get rid of the parentheses we have a single line where we're returning a value so we can get rid of the return keyword as well as the curly braces put everything on one line get rid of the semicolon and this is the end result so your mapping or transforming the array of color for each caller will return a string like this now we can take this to the next level and make this code cleaner this concatenations here are a little bit ugly so instead we can use template literals in es6 so instead of using single or double quotes we use the backtick character that's the character before number one on your keyboard here we can define a template for our string so we want to have the opening and closing Li tags and in the middle we want to render the color dynamically so we add a dollar sign and curly braces this is an argument placeholder what we put in between the braces will be rendered dynamically at runtime so here we want to render this color that we have here right so this is what we call a template literal now we get a new array let's lock that on a console so console the blog items save the changes as you can see we have an array with three items so this map method is very useful in react when rendering lists as you will see in the next section one of the modern JavaScript features that you see a lot in react applications is object restructuring so let's imagine we have an address object like this we have Street set some value city and country now let's say somewhere in the code we need to extract the value of these properties and store them in separate variables so this is what we typically do constant street we set it to an address but street and similarly city we set this to address dot city and finally country the problem with this code is oops I missed a T here the problem with this code is that we have this repetitive address dot address dot address dot code in multiple places these structuring solves this problem so if we want to have three variables or three constants street city and country and we want them to be set to these properties in the address object we can rewrite this code like this so constant we add curly braces this is the destructuring syntax we add the name of the target properties in this case street city and country we set this to the address object so what we have on line 11 is exactly equivalent to these three lines and we no longer have that repetition of address dot so basically we are extracting the street property from the address object and storing it in a constant called street now you don't necessarily have to list all the properties in the address object maybe you're only interested in the city property in that case you can drop these two other properties now what if we want to use a different name here for example what if you want to call this constant s T we can use an alias here so we add : s T with this syntax for defining a new constant called s T and we're setting that to the street property of the address object so this is object restructuring that you will see a lot in the future sections another modern JavaScript feature that we use quite a lot in react is the spread operator let's say we have two arrays first with three numbers and second with three more numbers let's say we want to combine these two arrays one way to combine this is like this so combined we get the first call the concat method and pass the second array this is the old way of doing things now with the spread operator we can rewrite this code like this so a constant combined we create a new array we spread the first array and that means we'll get every item in this array and put it in our new array and then similarly we'll spread the second array so the spread operator is represented using three dots right in the first class you may say there is really not much of a difference between what we have on line four or line five in terms of the length of the code so why is this an improvement well what if we wanted to add an element somewhere in the middle so we can simply come here and add an element right in the middle but when using the concat method if you want to get the same result our code would end up looking more complicated similarly we can add another element here at the end so B we can visually see what the end result will look like so we have a new array first we spread all the items in the first array then we have a and so on so basically when we apply the spread operator on an array we'll get each individual item in that array now using the spread operator we can easily clone an array let me show you so I'm gonna comment out these two lines let's say we want to clone the first array but define a constant clone we create a new array and simply spread the first array now if we log first and clone you will see they are identical save the changes back in the console so here is first and here is clone now we can also apply the spread operator on objects so I'm going to rewrite this code but use an object instead so let's delete everything don't worry you're not gonna forget this so let's define a constant call it first we set it to an object with the name property set to maash then a second object with another property job instructor okay now let's say we want to combine these two objects into one object but declare another constant called combined we create a new object note that previously we created a new array because we were combining two arrays now we're combining two objects so we create a new object now in this new object we want to add all the properties are the first object so we spread the first object then we'll also spread the second object we can optionally add other properties let's say location Australia now if you log this combined object on the console we get this object with three properties similarly we can use the spread operator to clone an object so if I want to clone the first object I can do like this and your object we simply spread the first object and boom we're done now let's talk about classes so look at this piece of code we have this personal object with two members named and walk what if you want to create another personal object that can walk well let me temporarily duplicate this code and call this other object person two now there is a problem here the problem is that we have duplicated the implementation of the walk method now this implementation is currently a single line of code but in a real world application this method can be five to ten lines of code or maybe more if there is a bug in this method then we'll have to come back and fix it in all person objects that doesn't make sense right so when we have an object with at least one method we need a blueprint to create objects of that type and that's when we use classes so let me show you how a class can help us solve this problem I'm gonna delete the second person object and create a class so we start with the class keyword give our class a name person and note that here I'm using post call naming convention so the first letter of every word should be uppercase as another example if you wanted to call this class cool person would have to name it like this so note that C and P here are capital okay so here's our class then we add a code block now we need to move our walk method inside our person class so I've selected this code I'm holding down alt and then press a down arrow so we can move it like this easy right finally we need to add another method here that method is a special method that is called constructor so just like the walk method constructor is a method but the name is reserved it's a special keyword that's why similar to the class keyword it is orange okay now this constructor can take parameters so we can pass the name from the outside and initialize it here how well we use this in this case this always returns a reference to the current object so we set the name property on that object to this name argument that we received from the outside now we have a blueprint for creating personal objects so let's delete this code on the top to create a personal object we can do something like this so person we set it to a new person object so this new keyword or the new operator is very important here when we have a class to create an object using that class or that blueprint we need to use the new operator now we had parentheses and you can see our name parameter so if you ignore the new keyword for a second this expression looks like calling a function and that's exactly our constructor method and the person class so the parameters are we defined there we can set them here so I'm gonna pass maash as an argument now we have a person object you can see it has a name property and the walk method with this person class we have implemented the walk method in a single place if tomorrow we find a bug in this method there's a single place we need to modify so this is the benefit of using classes next we're going to look at inheritance now let's take the example from the last lecture to the next level let's say we want to define a teacher class so class teacher here we add a teach method and simply do a console dot log of teach okay however all teachers should be able to walk because they're all persons we don't want to duplicate this walk method in the person and teacher classes so how can we solve this problem basically there are two solutions here we can use inheritance or composition the explanation of both these approaches is beyond the scope of this course that's something that I have talked about in my other course object-oriented programming in JavaScript but as well as react is concerned you need to understand the concept of inheritance so we can have this teacher class inherit from the person class and this means it will inherit all the methods defined in this person class how can we do it very easy so here we add a keyword extends person so teacher extends person now if we create a teacher object so teacher we set it to a new teacher look at its constructor you see the name parameter right so the teacher class is also inheriting the constructor of the person class okay so let's pass a name here wash now teacher dot look we have the name property which we have inherited from the personal class we have to teach method that we added specifically in the teacher class and walk which we also inherited from the person class so this is inheritance in action now let's take this to the next level let's imagine when creating a teacher apart from the name we need to pass their degree so here in the teacher class we need to add a constructor constructor this constructor should take two parameters one is name which we need to pass to the person class and I will show you that in a second the other parameter is the degree so degree now because we added a custom constructor here we need to call the constructor of the person class if you don't do that we'll get an error let me show you so down the bottom of this file let's remove this line teacher dot save the changes back on the console look at this error missing super call in constructor and you can see it's pointing to line 12 this is where we're defining the teacher class right after that we have the constructor this is where the problem is happening so back in the code whenever we had a constructor in a child class we need to call the constructor of its parent class so here in the constructor we have this special keyword super that references the parent class so we call it just like a method and you can see here we have the name parameter so we pass this name argument that we receive here so this will initialize the name property next we need to initialize the degree property so this that degree will set it to this degree argument now finally on line 22 we need to pass the second argument the degree that is let's say Master of Science so if we type teacher dot now you can see we have two properties degree a name as well as two methods teach and walk so this is inheritance in action as you will see in the next section whenever we create a component we should have that component extend the base component that is defined in react because that base component in react has a bunch of methods that we need in our components so we're done with classes next we'll look at modules so here is the code that we wrote in the last lecture currently this file is getting a little bit bloated because we have multiple classes defined in the same file it would be much nicer if we split this code across multiple files and this is what we call modularity so instead of writing all the code in one file we write our code in multiple files we call each file a module in the old days we didn't have the concept of modules natively in JavaScript so there were many third-party solutions but starting from Egmont script 6 we have the concept of modules natively in JavaScript so let's go ahead and modularize this application I'm gonna move each class in a separate file let's start with the person class so create a new file back in index that is select the person class cut it and put it here now let's save this as person dot J s similarly we need to go back to index that j s and grab the t-shirt class cut it create a new file paste it here and save it as teacher dot J s so now we can see we have less code in each file and our application is more maintainable but we are not done yet when working with modules the objects we define in a module are private by default so that means this teacher class that we have defined here is not visible to any other files or modules in this application in order to make this visible we have to make it public and we do that by exporting this class to the outside so we export it from the teacher class and then we import it wherever we need it so doing that is very easy we simply prefix the class with export ok save the changes similarly we go to the person module so we need to export the person class because we have referenced that and our teacher module here we're using the person class right but currently we have not imported this person class here so on the top we add import curly braces person from in codes you can see intellisense in vs code is suggesting a few libraries like react react Dom and so on these are the libraries that we have specified as dependencies in package.json so let me quickly show you back in the project here the JSON we've got three dependencies here and these dependencies are stored in node modules folder right so currently we don't want to import anything from these modules we want to import from our own modules so let's close this so here we need to pass the relative past or the target file or the target module we start with period slash and that indicates the current folder here are the files in the current folder so we want to import this person class from this person file note that here we don't add the extension just the file name so we don't add dot jas okay and finally we need to terminate this statement with a semicolon so we imported the person class from the person module finally we need to go back to index j s and because here we're using the teacher class we need to import it so once again import curly braces teacher from relative past that is pure slash teacher save the changes now to make sure that everything works let's call the teach method save the changes and here in the console you can see the teach message beautiful so we successfully modularized this an application in the next lecture we'll talk about default and named exports in the last lecture I told you that the objects that we define in a module are private by default so they are not accessible from the outside unless we export them let's explore this topic in a bit more detail so here in our teacher module or teacher that Jas I'm gonna define a function let's call that promote we don't have any code here just a simple function now save the changes back in index j s so at the top you're importing the teacher class from the teacher module temporarily I'm gonna delete this press control space so with the intellisense you can see here we have the teacher class that is exported from the teacher module but we don't see our promote function right so back to teacher that J s if we export this function now we can import it in index AJ s so save the changes back to index J is once again control space look we have the promote function and the teacher class so we can export one or more objects from a given module these are what we call named exports so what is exported has a name like the promote function or the teacher class now apart from named exports we also have the concept of default export and that is the main object that is exported from a module typically we use default exports if there is only a single object that we want to export let me show you what I mean so back to teacher at Jas let me temporarily comment this out so you can see currently we are exporting only a single object that is the teacher class right now you might say what Marsh a class is not an object well in JavaScript technically a class is an object because JavaScript classes are syntactic sugar over constructor functions and functions as I told you before our objects so a class is technically an object in JavaScript now that aside here we're exporting a single object now we can add the default keyword here and that means this teacher object is the main or the default thing that we're exporting from this module now with this back to index is we don't need the curly braces anymore we use these braces only to import the names exports in this case teacher is the default export so we import it like this save the changes you can see our application still working we've got the teach message on the console so let me quickly recap with default exports we import them like this import whatever from this module we named exports we import them like this we put them in curly braces okay now it is also possible that a module has a default export as well as a bunch of named exports react module is an example of that and I'm going to show you that in a second so back to our teacher module here we have a default export but I'm also gonna export this function so we have a named export as well as the default export right save the changes back in index J s so on the top we are importing the default export also we add curly braces control space look we have the pro mode function this is a named export we can import that as well now why does this matter this is a pattern that you see a lot in react applications so as you will see in the following sections on top of almost every file in a react application we have an import statement like this import react comma braces component from react you can see this import statement looks very similar to what we have on line one so let's see what's going on here obviously a react is the module but note that here we don't have period slash because we use them only for our own modules that are part of the project but react is not part of our project it's a third-party library that is stored inside of the node modules folder okay now react is the default export from this module where as component is a named export so if I delete this and press control space you can see all the named exports in the react module 99% of the time we're going to use the component class because we want our custom components to extend this component so they will inherit all the behavior all the methods implemented inside of this class ok so that brings us to the end of this section I hope you enjoyed the material and I will see you in the next section [Music]
Info
Channel: Programming with Mosh
Views: 522,921
Rating: 4.9674339 out of 5
Keywords: es6, es6 tutorial, es6 modules, es6 classes, es6 javascript, web development, programming, javascript tutorial, js tutorial, code with mosh, programming with mosh, mosh hamedani, javascript es6, es6 crash course
Id: NCwa_xi0Uuc
Channel Id: undefined
Length: 50min 5sec (3005 seconds)
Published: Fri Jun 29 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.