Rediscovering JavaScript by Venkat Subramaniam

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
all right good morning welcome to the session on rediscovering JavaScript my name is Venkat Subramanyam we're going to talk about a lot of stuff related to what I would like to call as modern JavaScript we're gonna talk about features from es6 predominantly and a few other things this topic is based on the content I wrote recently in a book which is with the same title called rediscovering JavaScript so we can talk about a lot of different things that JavaScript has evolved into into a respectable language in my opinion for a lot of things we can do if you really think about it I wanted to you know start by describing what JavaScript is and and it's kind of interesting to think about we are you know the ear is 2018 and we are here excited about JavaScript so I was thinking how do I describe what JavaScript is and my description is JavaScript is like that villain in a bad movie they keep killing him but he keeps coming back to life that's the way I feel about it isn't it but but it's a language that's evolved quite a bit powerful every time around and there's a lot of different exciting features in the language that I'm gonna talk about today things that I've really enjoyed so I came across JavaScript several years ago maybe a few decades ago actually and and and like everybody else I would have to admit I was pretty scared about JavaScript but a lot of things have changed both in me and in the language I've kind of become a little bit more mature along the way not too much though but that language has become a lot better over the years relatively speaking and so it's a lot more approachable to me than it was once upon a time so that's what I want to focus on here today talking about what we can do with the language well we're going to talk about this modern JavaScript we're gonna look at several beautiful features the language contains and the very very first thing to really think about is out with the VAR well what does that really mean let's talk about that with a little example here for a minute we all have used javascript in the past and we used var to define variables so for example I could say var let's go ahead and say a number equal - and then I want to display the value of the number right after that well this is a definition of a variable you typically use a bar to define variables but unfortunately there are some real big problems with var and we should really not use it moving forward for example let's say I have a function called foo and in programming we always have to start with a function called foo so I took care of that right here and in this case I'm gonna define a local variable I'll go ahead and say var local is a 1 is equal to 2 and I want to print the local variable now clearly when I go ahead and call the function foo here if you will you will notice that I'm able to print the local variable one that's not really a problem on the other hand if I try to print the local variable right here I'll get an error as you would expect and that's exactly what you want to see because local variable is local but unfortunately though there are a few problems with var in the past and that is if you were to define a block scope and within this I'm gonna say local 2 is equal to 3 I don't want to print local to writing here that worked really well but unfortunately though JavaScript did not have a block scope for var in the past so when JavaScript sees this little curly it looks at the curly and says what am i is curly and throws it out and it doesn't do anything with it and as a result if you notice over here when I access local two I'm able to access it which is really a bad news well the reason for that is JavaScript is hoisting this variable all the way to the top so this variable is defined up here and then of course is given a value down here and unfortunately that's not what we really want another problem with this approach is if you were to define a var again but by mistake you define local one one more time notice that you don't get any errors and JavaScript doesn't care to tell you hey are you serious now you're ready to find this variable do you mean to really redefine it so what do you do to fix this problem well one of the problems is JavaScript doesn't have the luxury of a lot of other languages what i mean by that is javascript cannot so easily deprecated things now why can't javascript deprecated things the reason you cannot deprecated things in javascript is you are going to have a very old code legacy code written by people over time and and if you were to throw in a new JavaScript engine into a browser and the new JavaScript engine changes the meaning of var you can have a lot of trouble with legacy code that's already there so as a result you don't have the ability to just deprecated things in JavaScript so what they did was they kind of left the old stuff the way it was and pored over the new stuff on top of it the good news is you can use the new stuff the bad news is the old stuff is still there and you have to be sure not to use the old stuff so this is where tools like es lint can be very helpful tools like es lint can help you to verify that you're also using old stuff you're not supposed to use I'm thinking give you error or warnings and you can deal with it pretty nicely but moving forward my recommendation is quit using var that's really not a good idea so what should we really do instant well as much as possible we want to use Const and if we cannot use a Const then and only then we should really use elect so let's take a look at how we're going to change this code to use those two ideas so what I'm gonna do here is first of all I'm gonna change this to a Const over here and you can see the code still works and we are using a cons to define because I don't intend to really modify foo once I create this variable then of course I'm gonna go back over here and define this as elect for now and notice immediately I get an error and the error is on line number 12 because let will not allow me to redefine variables once it's been defined so as a result you can see line number 12 doesn't work because I've defined the variable local one using let select protects us from redefining variables that's been defined already you can reassign values if you really want to do because let is mutable but you're not allowed to read find a variable wants you to find them secondly of course one nice thing about letters are constants you can see that in this particular case if I use a letter accounts doesn't matter I cannot access local to outside of the block so I get an error on line number 10 as you can see line number 10 is not happy with me because the scope of the variable defined using a letter or a constant is a block scope and you cannot access it outside the block so I cannot access that local 2 over here so of course the question then is we shouldn't be using bar but should we use a let or should we use a Const and my general recommendation is use Const where possible and and and and of course and only where not possible use let so in other words let should be the the bar should be avoided let should be the least preferred cons should be the most preferred now why is a Const a better idea well the reason why cons is a better idea is so let's talk a little bit about constant and how we can benefit from that so if I say let let's say n is equal to 4 and I want to print the value of n which is a value of 4 if I say n equal to 7 I can modify the value of n as you can see on the other hand if I were to define a constant you will notice I get an error on line number 5 because a constant will not allow us to modify it now why am I so excited about this and the reason for this is actually pretty simple let's say over here factor equal to 2 for a minute now I'm going to write a function called printed and the printed function here says give me an element e and what I'm going to do is print out the element x factor now I want to call printed and I'm gonna call printed with let's say the value of 4 if you will so when I run this code you can see that in this particular case a printed of course so in this case when I run the code you will notice it printed a value of 8 so there's no confusion so far but I'm gonna change it to a factor equal to 0 and I'm gonna ask the question what's the output now let's think about this for a minute when I didn't have that code the output was 8 now of course I set the value to zero so let's kind of scratch overhead a little bit how many of us think the output is going to be at 8 just to show off hand don't worry about being wrong I'm wrong most of the time so one person raises the hand saying that it's gonna be eight how many of us think it is zero okay a few more people raise their hand a lot of not more people how many of you have no clue they are that's the camp I belong to right I look at this code I'm like I don't have a clue yet and usually before I have coffee I don't have a clue after hack off you have no more clue anymore I still write coffee didn't help me in this case well it's going to run the code and see what happened it gave us a value of zero as you can see but it doesn't matter what the output is do we really want to write code like this that's the question I usually use this code as an interview question honestly I will put this question for the interview and as the candidate what's the output if they're trying to answer the question I tell them they are fired already because the right answer they want I want them to give is are you all stupid because you don't want to write code like this because we want to release production code this is horrible so what do we want to do to avoid problems like this well the way to write problem like this is just simply say constant if I define as a constant then clearly line number five is not working and I will not be able to write code like this and it's absolutely clear what the result is and you want to write code that's easy to understand easy to maintain and and and has fewer errors and so as a result you really want to be able to write maintainable code but of course be a little bit careful about what constant really means in general because you want to know constant is like final in Java meaning it's going to protect the reference it's not gonna protect the object that is being referred to so to understand this let's take a look at a little bit of a further example in here so we defined a constant let's say n equal to four and clearly n equal to five will not work you're not allowed to modify a constant so that was not a problem on the other hand I'm gonna say constant Sam is equal to I'm gonna say name is equal to Sam and of course I'm gonna provide an age is going to be let's say the value of two now of course because it defined as a constant if I were to go ahead and say Sam is equal to Sam I'll get an error on line number five because I'm not allowed to mutate the variable Sam so there was not a problem on the other hand if I say Sam that age is equal to three notice I did not get an error now you're thinking my goodness what just happened over here well if you actually display the value of Sam right now notice the value did modify because a constant only protects the reference the constant doesn't protect the object itself now the question is of course how do you really protect the object they're two inserts to that question the first is that's none of constants business current stays I'm not really going to tell you you know about it I'm not gonna protect the object so it's done it only protects the reference but if you really want to protect the object what you can do though is you can go up here and you can take this object and you can use object dot freeze and then you can actually freeze the object upon creation like that so this is nothing new what constant this gives you an ability to a freeze an object now when you do this of course the object Sam is frozen and of course the reference is constant as well so you know that you cannot do Sam equal to Sam that will not work line number five is failing but of course you know line number five is failing because of the cons over here on the other hand if I say constant is equal to three well wait a minute it did not give us an error at this point so what's the point of asking you to freeze you may wonder let's go back to this code and display this right now and when you run it notice it didn't change it so what's really going on well JavaScript it's like a guest in its house it doesn't yell at you and say are you stupid why are you changing it kind of smiles and quietly ignores you so that's basically what happened here but I'm a big fan of being yelled at and honestly because I would like to programs to fail loudly in front of me then quietly misbehaving so how do we tell JavaScript don't be such a great friend yell at me if I'm doing something stupid well you can do that by using you strength and use trick we'll turn that into a yell as you can see line number six is failing right now saying cannot assign property that is read-only and so as a result it doesn't want you to modify it my recommendation is always use use strict in code because it comes to your defense and fails fast and makes the code a lot more safer in that regard so you don't want the code to quietly misbehave an ignore your call you want that to fail at runtime to immediately trigger this this can be very useful now clearly one other thing to keep in mind as much as I showed you a constant object dot freeze object dot freeze is a shallow freeze it's not a deep freeze so if you have an object that's nested one more level it's not gonna beep go deeper and freeze it of course there are libraries in JavaScript of course there's no surprise that libraries in JavaScript but there's libraries in JavaScript to perform their deep freeze for you and you can use one of those libraries if you want to go further and decrease this object well let's move a little for what we talked about using lick as much as possible use constant when you cannot use constant use let and quit using bar let's move a little forward let's talk about arguments while arguments was a way in JavaScript that provided VAR args which is really an interesting feature I just absolutely loved this when I saw this you know a long time ago so let's look at an example of this let's say we have a max function I want to write and the max function takes a and B as an argument and I say if a is greater than B return the value of a otherwise simply return the value of B I want to call max with a 1 and 7 and you can see the result is a 7 I want to call max again the value of let's say three and or two and the result is a three but what if I call max with a 1 & 8 & a 3 well gosh how did that work I passed three arguments when only two were expected well the reason for this is first of all the word works is a very loaded word in programming right so it doesn't actually work so if I said 31 it gives us a wrong result obviously so I didn't quite actually work but it did something so these days I don't say the code works I simply say code behaves right that's all it did but in this case of course what's going on well it turns out that every function in JavaScript is a var arc function in the case of languages like Java and c-sharp when you define a function to take a certain number of parameters you can only pass that many arguments to that function not so in JavaScript in JavaScript every function can take variable number of arguments without you saying anything so it turns out in this case those arguments can be obtained by using a special keyword which is called arguments if you will so when I run this code you can see the arguments is loaded with all the values in that particular parameter list our argument list but of course this has been around for a very long time but what I'm trying to say here is quit using arguments now why should we not use arguments there are some really big problems with arguments let's talk about what those are the very first thing I want to talk about here is to output type of arguments I want to say arguments so arguments is an instance of array and notice it says false for every single one of them because arguments is not an array arguments is a very sad story it wanted to be an array but it never matured to be an array so it's an array wannabe but more important if I want to really make use of this one in this example here I'm gonna say a large is equal to 0 I want to return large in the very end but within here I'm gonna say far and what am I gonna say here I'm gonna say in this a constant let's actually elect I equal to zero and then I'm gonna say I less than arguments dot length and I plus plus and then of course I'm gonna say if large is well if the arguments at position I is greater than large then I want to say largest equal to arguments at position I and we could write the code like this but of course this is the imperative style of programming and the code is not very elegant unfortunately though because arguments is not an array you cannot call methods of array on an argument what I would really like to do here is the following I want to say argument start reduce but notice how reduces undefined it doesn't have a clue what reduces that's why it says undefined so as a result if I were to call reduce over here that's not gonna go really well because it blows up so in other words if I want to use methods of array on an argument I have to first convert an argument into an array so typically what programmers do is they write two more lines of code in here to convert arguments to Narae and that's a bloated code you have to copy and paste everywhere that becomes verbose it becomes error-prone and the code begins to really smell so but why are we doing all of this the reason we are doing all of this is while the arguments was a really great idea it was very poorly done so what's the answer to solve that particular problem the first answer is quit using arguments there should be no arguments about it and then of course we'll start using rest instead and rest is a much better replacement moving forward I'm going to refactor this code right here to start using let if you will notice when I've run the code it gives us the result which is the correct result as you can see it gives us a 7 3 and 31 and and that's the right response for this particular code but I want to refactor this to a better code so how do we do that the first thing I'm gonna do here is to use values and our numbers whatever you want to call it but I want to put make this a bar org out of list arguments like the rest of it and you put three darts for that so oh one other reason why I'm a big fan of this if I look at this code as it is right now if I ask you the question how many arguments does max take the answer is I don't have a clue because this is like the opposite day right if it doesn't take anything you can send anything you want to it which doesn't make any sense so the only way to document this code is by writing a documentation or a comment but I'm a big fan of self-documenting code so when you look at the code it's very obvious now if you look at this right now if I say numbers it's pretty darn clear what we are saying here we are saying that the function max can take any number of arguments zero one two or more so as a result it becomes a lot easier to convey that in 10 very clearly now of course the code is still running but right below this I'm gonna ask the question is numbers over here an array and if I run this code notice well the first one is a false a second is our true because a rest parameter is actually an array type unlike arguments which are really not an array type so this is already a lot better as you can see here now that we know that numbers is an array notice what I'm gonna do here I'm gonna just do a in-place replacement wherever arguments is being used I'm gonna change it to numbers and you can see the code is still working that is another nice things about respirometer is that anywhere you're using arguments already you can very easily certain replace that with a respirometer but as a bonus though because we are able to do this notice what I'm gonna do now we can take all that fluff out of here from the imperative style code and we can write a functional style code really nicely we can say numbers dot reduce right here and then we can say large comma element and I can then say if large if element is greater than large then return the element for me otherwise return a large and as a result you can write the code a lot more elegantly as you can see so without having to write that many lines of code you can use a functional style code to write it of course you have to debug this a little bit more and make sure it works for various arguments you provide but it kind of takes you in the right direction to show you what you can do with it so this becomes a light nice elegant way and as a result rather than writing so much fluffy code you are able to write a lot less code and that becomes a lot better as well so moving forward start using rest arguments rather than using arguments rest parameters rather than using arguments that's a lot better way to do this so we saw what a rest is but let's talk about what a spread is a spread is the other side of this now it turns out two things two operators in JavaScript use the same symbol the three dots is used for rest on the receiving side but the three dots are also used on the sending side for a spread operator to understand this let's take a slightly different example suppose we have a constant let's say values equal to and I say one two and one twelve and seven but I want to go ahead and call max with this and get the result so if I set values over here notice that did not quite work and the reason is because the numbers is an array it is expecting however because it's a rest parameter it's expecting discrete values to be passed in in this case we passed one array so that entire array was sent as the first element of this other array and so as a result that did not quite go well but what can I do instead of this well here's an idea I can take this code right now and I can say 0 comma 1 comma 2 I can pass it like this but if I write code like this the good comment is I need another job isn't it because that's not a very pleasant code to write that's very boring so what can we do to minimize that I've heard well you can call max but you can use a triple dot right there and you can say values right there and that the spread operator so the same three dots you can see on the receiving site is the rest parameter on the sending side it becomes the spread operator because you're taking the collection of data and you are spreading it make no mistake the spread is not tied to the rest in any way they are completely independent of each other so for example not only can you use the spread when you have a rest on the other side but you can also use it when you don't have spread a rest on the other side so to understand this let's take an example of a greet function and I'm gonna say in the greet function I'm gonna take a name one comma name - if you will and I'm going to go ahead and print out right here we'll go and say hello dollar name one and then we will say dollar name two I'm using the string literal right here I can call greet and I can send Jack comma Jill and you can see that in this case I've sent two arguments to the two parameters that I have name one and name two but on the other hand if I said names is equal to and I have Tom comma Jerry let's say over here but I want to be able to pass this to the greet function now clearly you know this is not gonna work because it says Tom Jerry and undefined and that's not really what we wanted so what can we do about it we also know this is not gonna really make new friends if we write code like this that's really boring what you can do instead is you can call greet and you can spread it and notice even though there is no rest on this side you are able to use a spread on this side and that's one of the powerful ways of using spread you can pretty much ask it to take a collection of data and spread it across and that works really well as you can see so that gives you an idea about how you are able to use a spread on the site but what is really cool about spread is it's absolutely versatile so I'm gonna give you a few more examples of how we can use spread so I'm gonna say names one equal to and cons names two equals two let's go ahead and say tyke over here so I want to now take this over and I want to write a code like this I can say a dot dot dot name one this literally gives you back the same thing but you're exploding or spreading the content of that array into this other array but I can then say common and I can then say spike over here and I just created a new collection with the old collection Tom and Jerry but with the value spike in it but I can then say , and I can say named Stu over here and now we are able to add a tyke to it as well so this gives a really nice power to manipulate these arrays with exploding these erasers threading these arrays internally and that gives you an enormous power on your hand but not only can you use a spread like this but it can be even more powerful if you used something like Redux you probably have seen the syntax I'm gonna show you next and it's a really powerful way to make copies of objects so don't understand this let's take a look at a slightly different example we looked at how we can combine arrays but you can also go a little further with this let's say for a minute we have a constant Sam is equal to name that's going to be Sam and I'm gonna say over here age is going to be let's say two let's go ahead and make this a freeze object dot freeze so I cannot modify Sam which is what I normally like to do when a program in tools like libraries like redux I don't want to be mutating my object but I want to make a copy of Sam maybe I want to alter Sam how do I do that so constant Sam we call it as older Sam is equal to how do I do this so named Sam dot name right here and then I can say age is gonna be Sam dot H plus one and of course if I were to go ahead and output let's say Sam but I also want to output older Sam you can see that the Sam's age is two but older Sam's age is three but I get something absolutely terrible right now why the reason why this code is really a bad code is let's say a few weeks goes by in a large application it's not like it's right there in front of it you could have created this objects in some place of your code you might be making a copy in completely a different place in your code if you're doing that what's going to happen maybe a few weeks goes by and you decide to change this particular object and now same here even those time is two years old you know how kids these days are this Sam already has a Twitter ID and so this Sam contains a twitter ID so I'll say example an example I don't have a clue whose Twitter ID that is this is purely a fictitious I'm not talking about any specific person just for the sake of argument we'll just say examples Sam saying Sam here and now of course when I run the code unfortunately how sad our new Sam doesn't have a Twitter ID maybe Sam tweeted like my president they will drew the Twitter permission the parents did but the point really is that we don't want to make a copy like that we want the Twitter ID to be available for Sam what do I do right now well if I were to come in here one way to fix it is I can come here and say Twitter : and then I can say Sam dot Witter now the only good part about this is job security isn't it because you can keep maintain discord over and over and over but at some point will begin to hate this job eventually because that's not very extensible code gosh that's really smelly because a few weeks later we add a Facebook ID for Sam and the whole code is broken again what can we do about it let's withdraw from that code for a minute let's go back all the way without really bringing in the Twitter ID at the moment so what am I going to do now let's go ahead and remove the twitter ID for a second let's go ahead and run this code you can see that working but I'm gonna come in here and say alright I want to modify the age fine but the rest of it I want to just spread it and I'm gonna ask it to be spreading the Sam right there look at how powerful that really is what is the benefit of this notice from this output if I go back here and add a twitter ID to Sam right now I don't have to babysit this code because the older Sam contains the same Twitter ID without me having to really modify the code so that is one of the biggest benefits you get out of this the spread operator can be used to spread your object as well when you are making copies of this like I mentioned you probably have seen this if you have used tools like libraries like redux because we want to treat objects as immutable so when you make a copy of the object obviously you don't want to be really you know making copies of every single field that's not a very extensible code the spread really saves you a lot of effort to do that a very powerful idea as you can see here so that is about spread well I'm gonna talk a little bit more about some of these ideas later on we got a lot more other features beautiful features but I do have to admit that spread is probably the second feature in JavaScript that I really like I've saved the first favorite feature of mine for a later time we'll talk about that a little bit further let's now move a little forward let's talk about default parameters now let's say for a minute we have a function called greet and the function greet is taking a name as an argument and here I'm gonna print hello followed by the name itself now I'm gonna go ahead and call greet if you will but I'm gonna call greet and pass let's say a Jain over here now when I run this code you can see it says hello Jane but maybe tomorrow I decide to customize this I want to pass a message to the greet function because sometimes I want to say hello sometimes I want to say if I whatever it is I want to keep changing what can I do about it well here's a nice feature to fix it if I were to check I had a new parameter over here like a message that may end up breaking existing code which is not fun I don't want to break existing code so I want to take this object a greet and pass Jane but I want to say hi to it but if I don't pass anything I want it to be some value after all as you can see here you don't want it to say undefined Jane Jane just unfriended you on Facebook right you don't want to be relieved that rude you want to say nice greeting messages so what can you do to evolve this code well what can do here is to go to this method and you can add the parameter you can specify something to replace it so you can see that it says howdy Jane right there and you're able to pass a default argument to it so that becomes a nice way to pass default parameters so the default parameters are a nice way for us to really extend existing functions to really add a new parameter if you really want to do let's look at one other feature in JavaScript you will see this feature is pretty darn powerful you will see this feature in other languages like Carlin as well so a lot of these languages are beginning to really use some of these nice features so for example if I were to go back to this code and I'm gonna say Jerry right here and when I run this code you can see that it says you know Jerry well I want to print out the grid for this and you can see that it is high Jerry but one of the nice features in JavaScript is the default parameters can actually use values of parameters to its left so the message parameter there's a parameter to its left which is the name so what I can do here is I can say name dot length if you will and and as a result this is a nice geeky way of saying high-five - Jerry so you can do that as well in simply saying I want one default argument to use another default argument and obviously if you were to give a value to this one if you say for example over here Jerry and I'm gonna say hello well obviously it says hello Jerry at that point whereas on the first one because it has any argument it can only take the default value but the default value is not a default value it's a default expression so that expression is evaluated and that expression can use any parameters to its left or any parameter in its lexical scope for that matter can become very handy as well so this gives you a little nice feature for you to use as you can see so that's about default parameters couple of things to keep in mind when it comes to default parameters you are able to define a default parameter you saw to send a value you saw how it value was used however be a little careful about it now suppose you were to call this one and don't pass anything it says hi Phi Jerry but if I were to call this and pass a null I know none as a smell we should not really do this but it says null Jerry that didn't go really well however if you were called this and say Jerry , undefined notice that's a little weird isn't it null is a null but undefined actually is replaced by the default value now for there two things I want to say first of all a first is don't do this right so it really is smelly don't do this however you may be curious why did they treat undefined different than an O and the reason is if you are receiving an object from let's say another function that object may or may not have a property well here's the beauty when you receive an object from another function if a property doesn't exist that property is considered to be undefined well if a property is undefined you can substitute a default value for it very easily because of this feature and that is why they treat undefined differently than the other it null and as a result that's a little bonus that you can get out of this which is really nice well now that's more a little forward let's talk about enhanced for loops and enhanced for loops are a very elegant way to iterate over a collection of data I'm gonna go through a few different refactoring of this code to understand a few little nice things we can do with this so let's go ahead and start with a little example here if you will off a constant let's go ahead and say constant names is equal to let's go ahead and say we have Tom and Jerry right here in this example but I want to loop through these values how do I do this so I can say over here let a equal to zero I less than names dart lint and then of course I plus plus and then I can print out the value of I and then maybe two dashes and then I can print the value of name square bracket I well that but we know this is a very boring code it's an imperative style code it's noisy and and it's not very elegant and fun to write code like this well but you can actually write a much better code in JavaScript now so you can say far and in this case I'm gonna say constant that's already a bonus isn't it rather than using the let I'm able to use a constant so I'm saying a constant name of names over here and then I'm going to output the name that's given to me so this becomes a nice elegant way to write a for loop so for constant name of names and then you're able to iterate over the names and print the value now clearly that's elegant it's a fewer moving parts it's it's easier to write as well and as a bonus the name is a constant if you try to modify the name you will get an error which makes the code a lot more safer but of course there is one disadvantage in the code we just wrote the top one as verbose and ugly it was it did have one advantage it gave us the index value if I don't have a need for the index value then this is a better option to use but if I do need the index value what gives what should I really do well for that purpose what you could do is you could write a for loop again constant and you could say n 3 off names dot and trees and you could write a piece of code which users and trees and then I can print out the entry right there now when you look at this code you can see that I'm able to get the entry values and the entry values gives me the index and the value at that index as an array well yeah that's great we are able to use it but wait a minute I really wanted the index value and the entry value at the index separately but how do I really get those values alright fair enough let's try this one more time I could write code like this and say over here I'll put the value for the entry I squared back at 0 and then a two dashes and then three and then a square bracket one well that work to produce the same result as line number four but I know this is not making you happy right you look at this code and say that's Mele code banquette come on we want something better than that it shouldn't be really that ugly well I agree with you so this is a good step but it's got to be a lot more cleaner than this let's try to do this one more time let's get back here and say a constant eye is equal to entry square bracket zero and then I'm going to say constant name is equal to entry square bracket one then this line number four can readily be used over here and of course I can use the eye and I can use the name not names of course so it's a little bit better than even that line I can write code like this but of course you look at this code and say all right you took one line of ugly code and made it three lines of ugly code now I know that's not making you happy either all right fines a very hard crowd to please but let me try again let's go a step further and I'm going to show you a feature which is my most favorite feature in JavaScript which is D structuring now these structuring is a weird name so D structuring now take the word structuring for a minute what a structuring really mean structuring is construction so construction and B construction or D structuring is the opposite of construction so construction is where you take different pieces of data and put the put a structure or a class together D structuring is the opposite you take what is structured and you tear it apart to create different pieces of data so it's the opposite of structuring that's what you're trying to really do here so what I'm gonna do in this case is in one shot I'm going to be structure this so I'm gonna put a little curly right there actually a rein right there because there's an array and I'm gonna say name and put entry right there and I can do the D structuring in one shot as you can see right there well that was a little the better I'm not saying it's excellent but it's a little bit better than the previous one because we are using be structuring off an array at this point well yeah that's great but why can't we just go a little bit further so I'm gonna take this one this time around and I'm going to simply say take that part right in there and replace the entry with it and get rid of this now and now you can see how you're able to use that pretty elegantly so you can see how we kind of arrived at that this is de structuring happening while you are actually iterating over the entries so it's a very common piece of code to see in modern JavaScript but knowing why it works actually makes it easier because the first time I came across that code on line 30 I was pretty confused I'm like my goodness what's going on here so I had to really walk my way through each of these steps and that made a lot more sense for me and I hope it does for you too so in a sense what we are doing is line number 26 is doing these structuring line number 25 is just iterating we combine the two together we are iterating and destructuring at the same time on line number 30 that's what we are doing so that's really destructuring the entries that it's pulling out and as a result we are able to write the code like that so as so now we can go back to the code we had originally to the code we have here and both of them produce the same result as you can see but we are able to take a traditional loop or we can use an enhanced for loop like you see right in here so that gives you an idea about how elegantly you're able to write this looping well having said that though but what about our own user-defined types wouldn't it be nice to do this for our own code as well well that would be really awesome now before I jump into this example I've got a little warning I'm gonna turn on the seatbelt and do play a where your seatbelt if the oxygen mask comes from the ceiling please put it on yourself first before you help the person next to you it's gonna be a little bumpy right for the next 10 minutes or so I'm gonna show you a really nasty way to write an iterator and when you are done with I'm gonna show you a much better way to write it and you'll be so happy to see the better way because you don't have to write the nasty way then why do I want to show you the nasty way or because it's a lot of fun to see it and it's also knowing how it works under the hood it gives me the pleasure of doing two things I know how it works and I have the wisdom not to ever try it at home so let's get ready so here you go I turn on the seatbelt now so let's talk about how this is going to work so let's go ahead and create our own class for a minute so the class I'm going to create is called a car class but I'm also gonna create a class called wheel and I'm gonna obviously use wheels in my car we'll come to that in just a few minutes so what is the car class contain that constructor says over here this dot wheels is equal to and I'm gonna define an array of wheels so the first entry here is new wheel but I'm gonna provide three more of these objects for four wheels of the car let's stop for just one minute and celebrate something which is just absolutely amazing notice when I ran the code it ran with no errors but did you notice I ended the array with a comma now only programmers will understand what this means isn't it because the first day I saw that I literally screamed and the people around me said why are you so excited about a stupid comma in the end I'm like you don't understand this stuff this is amazing so the next time I want to write something I can just add stuff and leave a comma and then I can add a stuff and leave a that's amazing isn't it so you can end any structure in JavaScript with a comma if it's a collection this is reducing a lot of noise in the coding general when I do this in job I usually I I'm sure you've all seen people do this right they put a comma here instead of here why because they want to continue writing the next line when they come in we kind of write ugly code to work the language limitations JavaScript says why not just end with a comma you can just continue with it so that's right there you can just end it with a comma now what I want to do is I want to iterate over this so I'm gonna say far I will say constant wheel and and in this case off car and I want to go ahead and print out the wheel where car of course is an object so I'm gonna say constant car equal to new car and I want to run this and that didn't go really well if you notice it says code is not eatable well we'll come back and talk about this in a few minutes we got some work to do but before we do this let's step back and talk about javascript in general javascript does not have a concept of interfaces so in languages like Java we have interfaces so remember the code error I got it set that card is not iterable so what would you do in Java or C sharp at this point you will immediately implement an interface called an iterable right that's what you're gonna do you're gonna implement iterable interface well but javascript doesn't have a concept of interface let's begin what gives how do you really do this if there is no concept of interfaces well the problem with not having an interface really is not that interfaces are absolutely essential but one thing that interfaces do give you well there are two things interfaces give you write one thing an interface gives you is a collection of methods and if you know that if you are implemented an interface you got on all the bunch of methods but the other thing that interfaces give you really well is a avoiding a method named coalition if I have an interface implemented I know for sure that's the method I'm implementing but because JavaScript doesn't have interfaces if you if I want you to implement a method called foo we got a few problems you implement a method called foo which is wrong because the case is different that's one problem even worse you come across my library and I tell you to implement a method called foo and you protest saying I already have a method called foo in my class for an entirely different purpose what do I do now and the short answer is good luck you cannot use my library with your code unless you put a wrapper around it and it really turns into a mess in other words you want something unique and interfaces give you that uniqueness of methods and JavaScript doesn't have that concept well how do you fix it one way to fix it is to have interfaces but JavaScript said no we can't have interfaces because javascript is dynamically typed it becomes a lot messy to really deal with interfaces so they did us something a little different in JavaScript you have five primitive types so far isn't it so what are the five permitting types you have you have a boolean you have a number a string a null and you have undefined well now you have a sixth primitive type in JavaScript and that primitive type is called a symbol and a symbol is special because a symbol is unique and because a symbol is unique if you create a symbol as a method as a symbol then you can infer and force that somebody implementing your method there's a guarantee of what they implement if they implement method with your own symbol because symbols give you uniqueness let's do look at one example of this so I'm gonna say s1 equal to a symbol dart for I'm gonna say hi and I'm gonna print s1 notice it's a high no no surprise there but I'm gonna create one more symbol right here and the symbol s 2 and this is going to become let's say hello and of course I want to print what is an s2 and that's a hello but if I print s3 notice that it's a high but what's really interesting about this though is if I ask if s1 is equal to s2 notice that's a false they're not equal but if I ask is s1 equal to s 3 notice it is a true because the symbols are unique when you create them and because the symbol value is the same for both one three that true actually and a comparison in a being or true in the very end as you can see right in here so that gives you an idea of what a symbol can do where am I going with this what I'm going with this is I could say class let's say let's go ahead and create a little object or in this case and I'm gonna say a class person and and with this person I'm gonna say a constant Sam equal to new person but I'm gonna say Sam dot play or to call a play method now of course I can write a play method right here and I can say of playing if you will but when I run this code it says playing but the problem with this what I just did is the method play is an arbitrary name I created but what if you are having an interface called you know a player and that interface has a method called play now we are in trouble isn't it because your interface wants me to implement a play method but I already have a play method what gives how do we prevent this coalition oh here's an idea your interface I'm saying interface your loosely your interface contains a method not called as play but a symbol dot for play huh what does that mean then so I can go back over here and say a simple over here a symbol a dot for play and and so as a result notice the name of the method is a symbol itself then how do we call this method I can simply come in here and I can put a square bracket well actually let's go ahead and say a play method is equal to symbol dart for and I'm gonna say play right there and then I can come in here and I can call the play method as a method name in here if you will and so that becomes a very easy way for me to invoke the method so a symbol can become a method name and and the reason to do this is it gives us uniqueness of a method name and it avoids method name coalition now let's get back to the example we were working with and see how this is going to benefit so when I run Scot notice it says that a constant wheel of car car is not a horrible make sure to tighten your seatbelt we're gonna look at how to make this work so it says the car is not eatable so what am I going to do I'm gonna implement a generator for this purpose how do I write an iterator so I'm gonna say square bracket simple dart iterator and that becomes a special name of a method so JavaScript has a bunch of these symbols predefined there's a simple dot iterator symbol dot match and so on so these are well-known method names well-known symbols that JavaScript relies upon so in this case I'm gonna go ahead and implement the method symbol dot iterator and all I'm gonna do here simply is say called so we're gonna take baby steps one step at a time and make this Court to work now when I run this code good news the error is different as you can see what was the error a minute ago a minute ago the error was car is not a terrible now the error is different as you can see now the error says a result of symbol iterator method is not an object there is hope here isn't it now JavaScript says you're a good friend now you have implemented an iterator but one more problem you need to return an object for me oh no worries return an object hug how does that go JavaScript now the error is different it says undefined is not a function that's a very helpful error message isn't it so so what are we gonna do well undefined is not a function well okay it's expecting a function to be present in this object what kind of function does it want in this object so I'm gonna go to this object and I'm gonna provide a function that it wants to return so undefined is not a function that what it said so I'm gonna return a next over here which is going to be a function I'm gonna implement within this object so I'm gonna say function and and let's start with that now let's see what it says iterator result undefined is not an object hey that's great we moved on from one error to the next one it wants to see an object so what am I going to do return and I'm gonna return an object right there so let's go ahead and run this code now and what does it say well I shouldn't have done that actually sorry so that kind of went into a beach ball as you can see now this kind of gives you a clue what's happening so while I restart this what I'm going to show you though is that it is going to here's what javascript is actually doing before we go further and and fix it let's go over here and try to find and kill this first of all so I'm gonna go ahead and do a grep on nord over here which is what I'm running and let's go ahead and kill this I'm usually a very polite person but sometimes you do have to do this kind of killing of the process so let's see if that actually works so a no such process let's see no that's still running so let's go ahead and find out what I'm doing right along here that actually disappeared let's see why okay there you go all right now it took a little while to die but let's see what I'm doing wrong here well what happened here is the following scenario I know this is a little weird but this is how the iterator actually works when you take an object and use an enhanced for-loop javascript first looks for an iterator if the iterator is not present it gives you an error hey the iterator is present hey are you returning an object if not an error oh yes I'm returning an object awesome does your object have a method called next no it's an error oh yes I do have a method call next good are you returning an object to me yes well does that object have our done as a field and true as a result and a value let's just throw in a value of one for now arbitrarily now notice my done is true I go to the command prompt right now and I'm gonna say no the sampled rjs and it quit immediately and the reason is we said done is true on the other if I said falls over here what's gonna happen it calls the next function it gets an object the done is false it calls the next again the done is false it calls the next again and that's going to keep going for like ever so when I run this code that's never gonna terminate just to illustrate the point if I go back to this example one more time and in here I'm gonna say let count is equal to zero and I'm going to return a value of count plus plus just to entertain this thought now if I go back and run this code you can see that count increasing constantly so hopefully that gives you an idea how this works but of course I want to iterate over the wheels of the car so what am I gonna do oh this is not that hard then let self is equal to this and now I can come in here and say actually let's do it this way let index is equal to minus one and I can come in here and say this is going to become the self square bracket well self dot wheels square bracket index plus plus and let's go ahead and say constant self is equal to this I'm not usually a good good at getting off by one errors so let's see if that actually makes sense so I start with the zero to begin with and now I've incremented it one two and so on and I'm going to simply say index is equal to four then I am done otherwise keep returning a false and let's see if that actually does anything good let's go ahead and fire this up and there are your four wheels that it printed so this is an example of using an iterator to implement the iterator on your own class raise your hand if you want to write that code not a single volunteer no okay I kind of understand why right that's error-prone tedious and very few people will survive that right so that's not fun so but you know exactly how it works now you want to say alright I understand how this works get me out of here right so let me turn off the seat-belt now relax it's going to be just fine now we're gonna use what is called a generator for this purpose so how does a generator look like let's get rid of all that code and all we can do is simply put a little star how beautiful that is so that becomes a generator this gives a flue to the JavaScript engine to say hey why don't you implement a generator for me so I don't have to work this hard so yield and I'm gonna say this dart wields square brackets 0 and I can ask it to provide me four different values at this point so I could say give me one two and three and it gives you the four wheels isn't that so much better well internally it's doing a lot of stuff we did already but we don't have to work that hard but the nice thing about this is you can use the yield in a very better way than this so for example you can do this way you could say far and in this case you can say constant wheel of this dart wheels and why not simply say over here yield a wheel so you could write code like that as well we're through the iteration you can start yielding a value out alternatively what you could also do is something even better this is where the power of the language shines you can say yield and you can simply say this is going to be this dart wheels and I want to return all the wheels and do the expansion right there and generator results in another generator so you can write all this code very elegantly one of the things is to really understand how things work and then you can of course leverage some of these things very nicely without having to do a lot of extra work and that saves you a lot of effort as well so that gives you an idea about how to use that special iterators and you can use a generator as well so we talked about quite a number of things already we talked about the use of var versus let and constant we talked about the rest and spread we talked about the default parameters and then of course we talked about enhanced for and we talked about generators the next thing I'm going to talk about is something that is nice but we have to be very careful and that is the use of arrow functions so let's start with a little example of an arrow function and then we'll talk about why this is something that we have to be very careful about so the first thing I want to show you here is a greet function and this is a regular function as you can see takes a name and and it simply prints out let's say hello and then it prints a name right there so I call greet with let's say a same here and it says hello same well we can write this as an arrow function rather than using it as a regular function so what I could do here is I can grab this code right there and rather than doing it this way we could simply write it as such we could remove this word function we could remove the parentheses if we don't care about it but a little arrow and you can remove this ending curly so what is the arrow function well the arrow function is nothing but a lambda right so a lambda but it's actually an anonymous function as much as it is but the the formative data is parameter list and then a arrow and then of course the body a single line party if you want a multi line body I usually discourage that but you can put a curly and put a multi line party in there but in this case as you can see here you have a parameter list an arrow and a body a bit of a sad news if you're writing Java code you know the syntax is parameter list a single arrow and a body well in JavaScript it's not a single - it's a double - those of you program Java and JavaScript you are forever cursed right because this is going to be painful when you're typing your code your mind doesn't flip so quickly you'll put a single arrow in JavaScript and then you code for a few hours you go back to job you put a double arrow on that and it gets really really vexing there is no real good way to well almost no good way to handle what you can do is you can create a macro on your machine and then you can use one symbol and it will expand based on the language you're using that way when you go to somebody's machine else's machine you'll have no clue how to program anymore right so the point really is you just have to go through that mental shift when you use multiple languages so that's a little arrow function you are defining now clearly when you look at this code it's pretty darn tempting isn't it hey look the arrow function is so concise why shouldn't I use a arrow function all the time rather than using a regular function and the short answer to that question is you have to be very careful about the semantical differences between those two so we looked at the structure of the arrow function but there is a huge semantical difference between a regular function and an arrow function now when they introduced arrow functions arrow functions are not a stand-in replacement for regular functions and if we don't remember this we're gonna be in real trouble and we could be inviting some bugs in the code if you have a lot of really good automated testing maybe those will catch you early on if you don't or if the situation where it escapes through you have to be very careful about it so let's understand what that means with an example now before we go further let's talk about scoping so what what is what what are the two kinds of scoping that we will that we need to be concerned about so there are two kinds of scoping the first is called lexical a lexical scoping so what is lexical scoping lexical scoping is where a an unbounded and bounded variable is bounded to definition in the defining scope in other words you can eyeball eyeball the code and find the variable to bind it to so this is basically what a lexical scope really is so when you have an unbounded variable that variable is bound to a variable in in the defining scope and in other words you have a variable which is undefined unbounded and you're like gosh what is this variable I don't see it you quickly eyeball the code and say oh look it's over there I can bind to it and that is a very easy way to do this so as an example you know Here I am but I'm thirsty I want some water or good news I didn't have to bring the water with me I can reach over and get the water that's on their desk over here well the desk is a defining scope I want a bottle of water I don't have a bottle of water but I can eyeball hey there's a what bottled water here I can reach and grab it so this is really what a lexical scoping is that it's in the context of defining scope wherever it is but on the other hand you can also look for what is called a dynamic scope so what is dynamic scope dynamic scoping is where an unbounded variable is bound to Val a variable passed in passed in by the caller of the function so in other words when a variables unbounded you're like gosh I don't know where this variable is coming from you cannot eyeball the code to find it whoever called you is going to pass that to you and and so if you have a lexical scoping it doesn't matter who is calling you it's the same value gonna bind to in the case of a dynamic scoping on the other hand if there are three colors the value may be three different values to that variable depending on who is calling it and so Diana scoping gives you a lot more flexibility but it can be really hard as well now let's think about this for a minute there are three kinds of languages out there what are you call as kind languages what are kind languages kind of languages care about you the programmer they don't want to hurt you and what a kind languages do I use lexical scoping why is that because lexical scoping is easier on us you can eyeball the code and say e that variable I got this the code is easier to reason the code is easier to understand so that's basically what a lexical scoping really is so kind languages use lexical scoping on the other hand unkind languages use dynamic scoping they want to mess with you they were a little unkind to you and you look at this code hey where's this variable coming from usually a shrug I don't know and you have to go back and look at it but then there are third kind evil languages use both and why because they are so much more fun to work with so what language which is kind of this almost all the languages that we use isn't it Java C sharp Ruby Python small talk keep going every single one of them use dynamics lexical scoping very few languages do this Perl may be one example but can you think of a language which is that evil yeah you know right you're looking at one and and JavaScript is one of those languages that does both and this is why you see people do often for that equal to this or Usami youself early on there's a reason for that because that's less dynamic scoping too kicking in to understand this a little bit better let's look at these two scoping first of all so first of all I'm gonna create a foo equal to function I take a variable here and I'm going to simply print the variable that I am receiving at this point this is just a local variable a parameter so I'm gonna call foo with the 7 no surprise it printed a value of 7 over there however I'm gonna define constant stuff equal to 4 and I'm gonna go ahead and go ahead and print stuff over here I wanted to watch this carefully we if you look at this function it's very clear what NS an is a local parameter local variable parameter in this case and so it's very clear what and on line number forests and on line number 4 is the parameter on line number 3 pig but what is tough on line number five gosh I don't know what stuff is on line number five its unbounded in the highlighted code stuff is not defined so I'm gonna eyeball the code oh look line number one has a stuff that is lexical scoping isn't it so that is lexical scoping and as there is some when I run the code it's bound to four so there's no surprise over there however what I want to do next is to say this start something is equal to twelve and I come in here and say output dis dart something what I've run the code though notice it did not say twelve it said undefined and the reason is that in a regular function so let's go ahead and write this in a regular function when you're define using the word function of all variables are lexically scoped except there's always a special right except this and arguments so this and arguments are dynamically scoped which are dynamically scoped so all variables are lexically scoped except this and arguments are dynamically scoped obvious the question is how do I get this dynamic scoping to get the this very simple when I run the code notice it said undefined on the other hand I can call foo with a call and here I can say something : 42 comma 7 and when I run this code you can see the value is 42 and the reason the value is 42 is because that this is dynamically scoped to the point I made earlier if the caller were to be different notice in this case I'm gonna say 77 the value is different every time you call this and and that becomes a lot easier to see how this is actually dynamically scoped so dynamic scoping really is where the dis end arguments and and we agreed earlier we shouldn't use arguments anymore but we still have to use this unfortunately isn't it so this an arguments are dynamically scoped everything else is lexically scoped and so this is the behavior author regular function but obvious question is how does this work for a aro function well let's talk about that real quick in in an arrow function all variables including this end arguments so this end arguments arguments are lexically scoped so this is one of the things you have to be very careful about so when it comes to regular functions versus arrow functions the behavior is very different to illustrate this let's go back and run this code one more time so if I go back over here and execute this notice the last line in both of those 42 and 77 but the change I'm gonna make here is I'm gonna take this line right here and only this line I am going to replace this with a function two and arrow function that's all I did that change I did now when I run the code this time notice is 12 and 12 in the end it's no longer that 42 and 77 and that is because this one is dynamic scoping dynamic for function on the other hand lexical for arrow function so it in other words that this binding is different based on what you are using so this is something can be extremely careful if you just do a in in-place replacement you're in for really big surprise because a semantic meaning is different between those two you can extend this as a corollary it makes zero sense to write a arrow function for a method of a class because a method of a class requires dynamic binding of this so if you use an air of function for a method of a class it's a disaster waiting to happen so you can use an arrow function where it makes sense so saying that we can use an arrow function for everything is really a dangerous situation to be and we have to know what we are doing because semantics is different it's not an in-place replacement so that's something you have to be very careful about so we're about the halfway point right now so let's go ahead and take a 15 minute break just to give an opportunity for you to stretch and and go around and then when we come back we will continue for the next half of this presentation thank you alright welcome back let's talk about what we gonna do in the remainder of the session we are we talked about a number of things so far we talked about the elect forces constant instead of war we talked about using rest and spread default parameters we talked about writing of our own iterators and how painful that can become we look at generators but then we wrapped up the last part by talking about arrow functions and we talked about the semantical difference between regular functions and arrow functions what we're going to do for the remainder of the part is talk a few more things about working with template literals object literals and then spend a little bit of time on D structuring which is a pretty amazing feature and after that we'll talk about classes and we'll talk about using writing classes using inheritance but we'll also talk about some of the semantical differences again and then things that we have to be a bit careful about when it comes to using the modern syntax and then we'll wrap up with that after talking about that in the towards the end so we got quite a number of fun things ahead so let's get moving so I want to talk about template literals you saw me use this quite a bit already but let's take a look at a quick example here just to see how this works so if I were to provide let's say a price is equal to let's say 12.25 and we'll say it's a constant price but I want to be able to print the price so I could say the price S and then I could put a little dollar and then we could put a price like this we in code like this before but that's not a lot of fun to write so we want a much elegant syntax I mentioned in the beginning of the last part that JavaScript doesn't have the ability to deprecate things javascript doesn't have the ability to change the meaning of what is already there because old code is gonna still be there like a zip code that's being sent to modern browsers and and newer engines and they still have to work the way they once did so in order to do this what they did is they decided to introduce a new syntax for template literals are our template literals so so how does this really work let's put a little single quote for a minute and write in here let's go ahead and put a little single chord again but I'm gonna put a dollar right there and end with a single quote single quotes already exists in JavaScript and as you can see that's the output it produces or take the same thing again but this time use a double quote right there and double quote also already was there they can't change the meaning of it so that's what it really did but on the other hand let's take this one but instead of a single quote or a double quote we use a backtick so when you use the back take a back pick is used for a template literal so this is the newer syntax introduced so it's sometimes easy to not be able to see it properly sometimes people think it's a single quote but it's not a single code it's literally a back take that you're using to begin and end this and that becomes a template literal that you can use to specify expression that you want to expand and evaluate at that point so that becomes a lot easier to work with as you can see I'm able to use a dollar inside of that but a dollar with a curly signifies a expression if you will whereas a dollar without the curly is just a literal dollar you don't have to worry about doing any escaping the next thing I want to show you here is a feature called object literal but when I show you the way that I'm gonna show you you probably will get a little angry at this feature because when I looked at it I said gosh this is nasty but in a different kind this is really a useful feature but let's look at the object literal real quick so what create a class an object called same but I want to say a name of this object so we can say Sam over here for a minute now in this case I'm gonna just go ahead and print out Sam and you will notice that name of the name is Sam and that that's a value that we have I can also go back here and say comma age and let's say the ages too and you can see the value of ages too so far so good but what if I have a constant the name is equal to and I'm gonna specify Sam over here but I'm also going to specify constant the age is equal to let's say 2 now of course I can use the name right here and I can also use the age right here as well now we know what these things are we know these things are lexical scoping so the name actually comes from the lexical scope and similarly the age comes from the lexical scope and so we are able to use that from that particular context so that's pretty easy now of course but we can reduce the syntax the noise here a little bit so what if we can go a little further what if this is not called the name what if this is called name like this and what if this is not called the age what if it's called age then before we change this keep this in mind the structure within this of course there is a property name : value property name : value well in this case I'm gonna change it to a name and I'm gonna change it to a age so that worked really nicely but now that we have a name and age value given that way we can now reduce a little bit by removing this entirely from there so you can see I simply put a curly name and because there's a name in the lexical scope the property call name takes on the value of the variable from the lexical scope called name and similarly I can remove this part as well and as a result you can see how we can simply minimize the code we are writing to initialize this object with those values now given this temple I'm not a big fan of what I'm seeing here and the reason is it's not that convincing why this would be a useful feature but we'll look at this in a entirely different context in a few minutes and I hope we'll be able to appreciate that a lot better so but of course object literal has a lot more feature then I showed you here but I want to switch over to D structuring we talked about be structuring just a little bit in the past when I was showing you the enhanced for-loop but I want to go a little deeper into D structuring there are two things you can do with the D structuring array D structuring and object D structuring as well and I'm gonna talk about both of those in here let's talk about array D structuring first and then we will go into object D structuring afterwards so let's start with a little example here let's say we have a get person as a first one and the get person is going to return let's say return an array and the array is going to be let's say over here we'll say John and Quincy and we'll say Adams right here so we have three values I am returning from this particular function as an array well great now I'm gonna say person is equal to get person and and of course I can print the person entirely here that worked but I want to really get the value separately out how do I do this well I could say constant first is equal to first and square brackets 0 constant middle is equal to person square bracket 1 and constant if you will last is equal to a person square bracket 2 and then of course I can print out at this point let's say first and let's go ahead and print out the middle and then finally let's print out the last over here well when I run this code you got those three values while that worked this is a lot of code to do a little thing wouldn't it be nice to reduce the amount of code the verbosity in here well the answer is yes we can do that so we can just delete that for a minute I put a square bracket and say first middle and last right in there and we can get rid of that part entirely so in other words while we are receiving an array of data we can ask it to assign and B structure the contents of the array into these values directly now of course the question is what if I don't care about the middle name I don't want it I don't really care about the second argument well then get rid of the middle from here that way you don't print it but why bother even receiving it you can get rid of that as well I'm not a big fan of this approach because can you imagine looking at a piece of code like that this is this is called cruelty but used very minimally this wouldn't be too bad so use your judgment how far you want to go with that well that's great so far but I want to get everything that I have I don't care about the rest of the stuff so I'm gonna say all else and I want to print all else right in there but you know this is not going to work because all else is Quincy not Quincy and Adams but of course we can fix that very nicely by using the three dots over there so that becomes a greedy fetch so it gets the first and everything else rest of it into it so that becomes a nice way to D structure that code that the data so that's a very effective way as much as this is really nice one of the disadvantages of this is it's working based on an array which means the position matters but a lot of times we don't care about the position we just want property names to work with the nice thing is we can use D structuring with objects as well not just a race so let's rework this example to use our objects rather than array so what I'm gonna do here is to go back to this code and say return but I'm gonna return a first as John and I'll return middle so as you can see I'm returning objects now and finally I'm going to say this is gonna be let's say Adams over here and I'm gonna return those values so now I can say constant person is equal to get person but I can print out right here up or a would start with just a person dot first well you know that would work but that's a little verbose code why don't we do the following we can say constant first is equal to person dot first we can say constant middle is equal to person dark middle and then constant last is equal to person dot last well actually let me do a little different let's say first name and I'll come back to where I'm going with this in a little bit later so we have this first name last name and middle name now what I can do here though is we can simply say first name and then we can provide the middle name and then finally we can provide the last name right here to print so that works as well as we can see in here but of course looking at this code it's a little verbose and noisy why can't we just use these structuring to reduce the noise and the answer is yes we can so going back over here we can say first is first name before we go further let's stop and look at it now the syntax is a little hard to remember but this is the property name and this is the local variable you are defining so in other words this is really from the target object this is the local variable now still that doesn't quite convince me to remember this so how do I really remember this here's a way to remember it think of it this way I'm gonna say drop and I'll say local is equal to now go back to how you will define the value prop : value this part is easy for us right because this is how we define a javascript object by putting a property name : value well you keep the same structure on the left side so this is more like a pattern matching you are simply saying prop is prop local variable is value so think of it as a pattern matching then it becomes a lot easier to remember that syntax so using the same syntax as defining an object rather than giving a value you are providing the variable to bind that value to so as a result first name first and middle and I'm gonna say middle name and then I can say last over here is going to be last name and and then I can remove those three lines from there so that becomes a lot easier to write as you can see going on any further though what I can do is I could say this is first and this is first as well and that way I can say this is middle and this becomes a middle as well oops middle as well and then finally I could say this is last and this is last also if I decide to keep the same names on both sides which means we can then remove that part and we can remove that part and finally we can remove that part as well and as a result we can do a little bit of restructure D structuring to minimize the verbosity in there so when you look at this code your eyes have to kind of scan through to figure out what you are using the little curly there says that you are actually defining a object but in this case because an object on the right side your D structuring into an object and the variable name first maps to a local variable and the property at the same time so that becomes a nice way to D structure this okay so this is useful to receive a data but what about sending this to our particular object to understand this let's take a look at a slightly different example let's say Sam name is going to be Sam let's say age is going to be two and let's say Street is going to be oh let's go ahead and say address we'll say address rather so address is going to be let's say Street and this is going to be 101 let's say Main Street and don't worry about other arguments for that but let's also say mailing and this is going to be a mailing address and this is going to be straight colon will say 1 0 5 Smith Street so we have this data and I want to use this information how do I you know work with it so let's and say a function over here and this is gonna be printed and that takes a object person and within this function I'm gonna say we'll go ahead and say a person well named first of all so we'll say name well person dot name right so person dot name and I'm gonna say is how old is this person we'll go ahead and say person dot age years old we'll start with this little example so we are printing person named Sam as two years old so I could call printed I can pass Sam to it now and of course in that case let's actually move this up here so in this case it says Sam is two years old well but how about reducing noise a little bit let's try this again constant name is equal to person dot name and constant age is equal to person dot age so then we can simply say name over here and we can say age over here that worked as well but going a little further how about reducing the noise a little bit more so let's put a curly here and say name comma age and I can assign and B structure right in place so as a result groups almost there so this is gonna be person so you can see Sam is two years old okay so far so good but grab this part right in there remove this and replace person with that so when you run that code now you have D structuring in the parameter list itself so as a result when you're passing this person you're saying think of this like filtering you're saying this person has these properties but I don't care about most of them I only care about these two properties I don't care about the remaining properties and you can filter it out so this becomes a really nice way to extract only the content you care about now in this case of course the name is a local variable that maps to the property called name at this point hey how about getting the address from the well here's the deal you can say comma and Street : address you can give a different name over here if you want to do but I'm gonna just get the address right now from the street so I'm gonna say Street : and then address that's coming from within here I'm gonna specify the address as a value that I wanted to see from within that so this gives an opportunity for us to go to this sorry this is addresses in that part of me this is address and then from that I'm gonna get the street so when I run this code we want to know what address Sam is so I can print the street right there which is 101 Main Street like okay that's awesome but what if I really want to get the mailing address as well so unfortunately we cannot do this right so if you say comment and I say address : and I sorry this is mailing right : and then I'm gonna say Street we're in trouble because this is the street and this is a street but this is an address but this is mailing so this address Oh first of all before we go any further sorry one more thing to emphasize here going back to this code notice we got the street address is not defined only the street is defined so if I were to try to print address that use an error because this is only defining name age and Street but I want to get the mailing address what do I do for that so common and we will say mailing and this becomes a street and that won't work what is the problem on line number three duplicate parameter name is not allowed you already defined the street you cannot define one more street so what gives you say : we can say mailings M Street whatever you want to call it our mailing street and then of course you can come down here and you can print out M Street at this point and get the value 1 of 105 Smith Street so this gives you an idea about how we extract the content we are interested in without having to really deal with getting the entire object and stripping values out of it so your object may have a number of different properties but you can specify what you really care about and extract only those in your code and you can use it as well and you can extract it at the point of call and that becomes a very effective way there are two reasons why you want to be comfortable with these you may want to use these but you're also going to look at code that other people are using this quite often especially when you start using different libraries in JavaScript you're gonna run into this very often and and if you're not comfortable with this it can become really agonizing trying to understand that piece of code so getting comfortable with this can help us quite a bit to deal with it so that's basically about D structuring now let's switch gears talk about object oriented programming in JavaScript so we all have used o in a lot of different languages it turns out javascript has been supporting object hundred concepts for a very long time except it's been a mess to deal with in the past I'm really happy they cleaned up a lot of stuff so moving forward it's a lot better pleasant experience but we still have to be very careful using these and that's what we want to spend the time on looking at some of these ideas and concepts first of all what about creating objects well let's take a look at one example here suppose I want to write a function so I say function foo and I'm going to simply say foo called so we can display that little message and I'm gonna call the function called foo but like hey create an object for me please okay sure I'll create an object so what am I gonna do well we could have written it like the way I did before we could have said function right here as well it doesn't change anything much in this context for what we are discussing so when we run this it said food called but constant car equal to function and in this case I'm gonna simply say output we'll just say call for a minute now let's get rid of the well that's not called foo but let's call new ooh car now look at this for a second what are we doing I want you to find a class called car well I did and you protest you say wait a minute wanker that's not a class it's a function no trust me it's a class how do I say did you notice the uppercase C so this is the sad part isn't it it was a purely a convention in JavaScript and you had to know it's a lowercase was this uppercase now clearly there are a few problems with this if I do a new you call the function but if I call car like that you called the function - now what gives how do you know which one to use in which one not to use this is very confusing actually this is even worse I will go ahead and say step one here and I'll go ahead and say step two here so we can see the difference and and when I run this it's a step one and step two but I go back into this class and I print out over here new dot target and when I run this code notice in the in the step one it says right there step one and it says function car in the second one it says undefined what in the world is happening here well it turns out what's happening here is that it is having a special feature called new dart target where the nude our target is really available when you invoke it as a constructor but when you invoke it as a regular function the new duck target doesn't exist so if you really wanted to you could come in here and check for a new target if the new target doesn't exist you can raise the message for example how about this it's undefined isn't it so you could say something along the lines of if not not new dart target so you can say if new dart target if it is not what can I say I'm going to say hmm so when I run this code in the second one it said hum now what you can do is you can now go to the next to say throw new error and you can say you called constructor as as regular function right how dare we will come burn your village so you can you know port messages like that right so you can't pretty much deal with that and blow up and it says you called constructor as a regular function how dare will come and burn your village but as you can see that's only getting really more nasty right we don't want to be doing that so what can you do this is one of the problems is you had to put all that code to deal with it which is kind of messy not only did we not create a class we could add a function and then we put more patches around it and that's not really elegant wouldn't it be nice to just settle down and write a class for once good news we can write classes now all that is taken care for us nicely how so let's look at an example here so class car and I create a class called car as simple as that now I'm gonna say output new car and create an object hey there you go we create an object of the car but what if I look for output type of car that's still a function right so JavaScript is still holding onto the same semantics as before so don't you know these are questions you don't want to ask like what is your type right don't go there life is very peaceful if you don't have probe around things you don't want to worry about but of course if you go back to this code and say car because it's after all a function it blows up saying class constructor cannot be invoked without new they just don't have the burn your village message but other than that they take care of it for you right so as you can see in this case this really protects you from calling that as a function that's been done pretty elegantly so this gives you an idea about how to really use a creative class and you can simply say class car and you can create it now that we created this how about writing a constructor for this well that's the nice part you can write a constructor very elegantly so say constructor and let's say here and I'm gonna simply say over here this dot ear equal to ear so as a result I can go ahead and say a constant car equal to new car 2018 and then I can simply output the car object and you can see the car here as 2018 so the word constructor is referring to a constructor that you're writing I like this rather than saying the name of the constructor of the name of the class why not just call as a constructor now to be fair languages like Java don't use the word constructor though they could but in the case of JavaScript you don't have function overloading you only have one constructor so you just call it constructor so but that's elegant that's easy to write and that created an object for us but of course what about creating fields within classes what we just did we create a field called ear right there you don't define fields in the top like you do in Java or C sharp you simply assign the values when you want to assign them as simple as that what about defining methods well defining methods is really easy also so for example I want to define a method called drive so this doc mile is equal to 0 and I'm gonna define a method called Drive it takes a distance and what am I gonna do I'm gonna simply say this start miles ok sorry I forgotten where I am kilometers ok so this dot kilometers is equal to the kilometer is equal to let's increase the distance a plus equal to the distance so as a result you can run the code the kilometers is 0 but I can say car drive 10 and I can of course print the car this time and you can see the value has changed to 10 so this gives you an idea about how you can write a method a method is very easy to implement as you can see simply write the method name parentheses a parameter list and the body of the code that sits in there really nicely so that's pretty elegant well what about properties now we know that Java doesn't quite have properties in the sense of properties but c-sharp has properties JavaScript kinda comes right in the middle in the case of JavaScript you can write properties but the way you write property is is by writing methods which are kind of annotated if you will so let's look at an example of how this is going to look like in here so I want to write a property what kind of property do I want to write so I want to write a property for color of the car so I'm gonna say color now I'm writing it like it's a method and I'm gonna return let's say an orange color that's the color for my little car so color is a method that returns orange but clearly that's a method we know that how do I use this stuff so let's go over here get rid of a few things so we can see less code so in this case I'm gonna simply say output card art color and as you would expect the color shows up as orange but I want the property not a method so what do I do ideally I want to be able to call it like this not a field but a property now clearly this is not gonna work the way I want it to work its gonna define a function color but I can go to this code and say get right in front of it that's the annotation I was talking about and notice how it displays orange so you write the method which takes no arguments you cannot put any arguments here right so if I say a it fails it tells you getters must not have any formal parameters don't put any parameter here that's what it says so you're not allowed to put any parameters and you write a getter by putting the word get when you call it you simply call it as as if you call a field but it's a property make no mistake don't put a parenthesis that fails to the it's not happy you calling it as a function because it's a property not a function so this gives you a nice way to define a property and in this case it's a getter well what's gonna happen if I set car dot color equal to a red now when I run this code it did not give us any error but what is it what does it really do at this point if I were to just simply say color is red and I want to print the car after that what is it going to display notice the color is not really there so what's happening at this point well remember we saw this in the previous part JavaScript doesn't give you errors it kind of quietly ignores what you said so at this point if I said use strict again and and when I run the code this time notice color dot color equal to read a car dot color equal to red gives you an error cannot set property of car which has only a getter so in other words if you only have a getter you cannot set a property and if you do it ignores it or if you have a used trick it blows up and and like I mentioned earlier you want to use you strict you know as much as you can so that's basically what you saw here is the getter but of course you can write a setter as well so you can say set color value and in this case what do I want to do I could say this dart you know a stored color if I want to call it as that and value and of course I can say over here this starts stored color is equal to orange to begin with and then of course I can return this dart stored color when I returned that so you can see the color was orange in the beginning but the stored color was red but this gives you an ability to do some testing as well or validation you could say if the value is equal to and you can check for a color you don't want the call to be and then you can say hey I don't want the car to be that color and if it is you can blow up and you know throw an exception so things like that but of course you can still get to the field directly but hopefully you and you have properties your users will use the properties and that becomes a nice way to access that so that becomes the getters and setters that you can write for these what about static stuff good news and bad news going back to this if I create a class called car and in the case of a car I want to create let's say a static method that's pretty easy you just define the word static and then you can write on method here whatever you want to write it I'll call it as tune info lets us call it as info for lack of better things and I'm gonna simply say info called so how do we use this stuff I can say card art info and and call it as a static method what if I try to call this as an object so constant car equal to new car and I say card art info well the info is a static not an instance method line number nine doesn't work you cannot call static stuff on objects you can only call it on classes so that becomes a nice way to write a static method here's the nice news you can also have a get and you can specify a static get will call it as you know something color for example I'm going to write this as you know simply return let's go ahead and say orange again and of course if I call this I can simply output car dot color I can call this property on the class itself if that even makes sense so you can define a property as a static also unfortunately though what if I want a field remember you don't define field within classes when did where did you find the field well within a constructor of course but wait a minute a static doesn't deal with a constructor because it depends to the class not to an object hmm where do we do where do we put that well you put that outside unfortunately so if I say count is equal to zero I can now come here and ask for account which is a field but of course in the constructor I can say constructor and I can increase over here a car dot count plus plus so I can say new car and I can come back and the output car dot count and see that the value has gone to a one so you define fields outside of the class not very elegant right but but that's what you have unfortunately the fields kind of spill out if they are static so that's basically an example of how you can define things that are static so we saw static methods we start static fields and we saw the static properties as well so that is pretty elegant javascript has one more thing which is a little bit weird which is called a class expression now what in the world is a class expression if I were to say class and I'm gonna say car and this one here if you're used to languages like Ruby in language like Ruby everything is an expression you are classes on expressions - and you can use them as expression which is kind of nice we'll enjoy in class the language is like Java and c-sharp classes are not expressions they are statements JavaScript gives you both in JavaScript classes can be statements are classes can be expressions so what am i creating right here well if you look at this here if I output car the car is a class we created but what about this one here that you created that is a statement but what if I said constant you know stuff is equal to and I want to print it out as stuff like that well notice how I'm assigning the class over to a variable called stuff well that tells you that class is like an expression it can be used as a statement as well but when would you want to do one versus the other well this kind of takes us to a little bit of a meta level what if you want to create a class but I don't want to create a class manually in my code maybe I will look at a configuration maybe I'll look at a database schema maybe I'll look at a property file or maybe I will receive a JSON configuration from the request and I want to create an object on the fly based on what I received at that time so to understand this let's look at an example here we'll call it as a constant we'll call it as a class Factory right and the factory is going to take a function and we will define this as properties so we'll take baby steps to see how we're gonna do this so I'm going to create a properties as a factory create classify but I'm gonna say constant book is equal to class factory now I want you to pay close attention to this here look at the syntax of book I put an uppercase B that tells you that the book is a class and not an object right so in other words a class Factory is gonna create a class for me and I can create an object of it so constant over here book is equal to new book and I'm gonna create an object of that book I'm gonna create on the fly and once I created I want to print that book out so how do we dynamically create a class called book but now that we did we could even create two books if I wanted to write so book one but I could also create a book to write in here so this becomes my book two and I want to print book do so of course we're a long way from running this code but we'll take baby steps to make this court work so what is the very first step I'm gonna do here let's comment this out we'll come back and make that code work in a few minutes so let's get started with the class factory first so I'm gonna come in here and say return class and I'm not giving a name for it you're not required to give a name for a class so this is just on the fly I'm gonna create this and I'm gonna simply say ok to see if it's ok with that so far and you can see how we are returning a class at the point which means I can assign it to the book over here and I can come in and display the book and it turns out that's a class we created on the fly right in there but what are the things I want to send to this one properties I want to say my book has a title and my book has a number of pages so I'll say my book has titles and pages okay great but I want to create a book with titles and pages how do I do that well here's an idea I can go back and say this is a rest so I can simply receive order 3 number of parameters so I can create a class and and I can give a property call title and a property called pages well if that is what I'm gonna do what does this do a constructor which takes values after all so I can pass values into my constructor how do we initialize the values then well here's an idea for a constant property of properties and I'm gonna simply output well I'm gonna just save this here so this square bracket and this is going to be the property that I'm interested in saving and oh darn it I need the values index isn't it but we know exactly how to do that so we can say square bracket index comma property and dart entries if you remember from the previous part so we got the entries on our hand so we can say here's the property and the value is property asari values square bracket index and this gives me the same sequence of values I get from the properties and I can stick them into this object well let's see if that took us anywhere at all we got a book on our hand now let's create an object of this book right here so book one we want to specify what the title is let's go ahead and say this is who moved moved my cheese so that's my mood my cheese so a title of a book and let's say 90 pages long and we can create an object of this book and you can see at this point we were able to create an object of book the title is home on my cheese pages 9b let's try this one more time we'll create yet another book will simply say this is title two and let's say 101 pages and right there as title to 101 pages but what does this take us well we can do the following now we could say new about this so we could say new class factory and we could say title come a volume whatever that is and we can create a title and volume and that we can provide an object right so this could be maybe a music volume let me write it this way so we could say music equal to create while class Factory that that is and we could say title and volume of this music and of course we can come down here and say new of music and this is gonna be whatever title one and we'll say volume one and we can create objects of that type so this becomes an easy way to create classes dynamically and you can pretty much synthesize classes on-the-fly rather than sitting and writing these classes over and over based on some configuration data or a database schema or whatever you may receive and that's all because you have an expression that you have on your hand if you want to you can give a name for this as well and the time that you want to give a name here is if you really want to access static properties it becomes easier to give a name otherwise you don't have to give a name for it so that gives you an idea about how you can create and use classes as expressions rather than just ask classes and like I said you can give an internal name if you want to the last thing I want to talk about here is inheritance but before we talk about inheritance I want to take a slight detour because this is a little dangerous the concept of classes is awesome well they also gave us inheritance but it's very important to know that the semantical difference of inheritance in JavaScript it looks in the modern syntax looks like Java but it's far away from Java so we need to understand what that means so for that reason let's go to the past before we look at the current state of what JavaScript provides in in the classic cases like Java and c-sharp and Ruby and Python several other languages what do we use we use what is called class-based inheritance so what is class-based inheritance a class inherits from another class right that's what it is languages like JavaScript and very few languages do this Lua is another example there are few languages that use what are called prototype inheritance what is prototypal inheritance so to understand prototypal inheritance let's take a look at a slightly different example so I say Sam is equal to we'll put name is going to be Sam right here and in this case I'm going to go ahead and call a method on Sam so to understand this let's go ahead and say use and this is going to take a person if you will so this is going to say person and within here I put a try person dot work and I'm going to print a message catch exception and I would simply output not found so let's go ahead and call use and pass Sam to it and you got there not found so far so good but what I'm gonna do then is to create a little constant we will call it as employment is equal to work and this becomes a function and all I'm gonna do here is simply say working just take this example for a second so I have a method called work in employment so far so good now I'm gonna call use and pass Sam again but this time around what I'll do here is go to Sam I say object dot set prototype off Sam c'mon let's go ahead and say employment so I'm taking this object Sam and I'm assigning a prototype so what does this really do here's a way to think about it you could come to me and say hey Bank it can have change for 10 euros please you know what I think I can help you with that I will reach into my pocket give you change for 10 euros not a problem but what if you say can I have change for 10 dollars please there's no real reason for me to call carry dollars on me right now but I'm not gonna say no I'm gonna reach into my backpack and I'm gonna get you change for dollars from my bag so my backpack is an extension of me in that sense so this is exactly what's going to happen in the case of JavaScript so when I run the code notice the first time I call use same on line 11 it said not found but on line number 17 the same Sam object quietly provided the working and the reason it did is because we assigned a prototype to Sam and what object does is if a member doesn't exist it reaches into a prototype now this is called prototypal inheritance what is really cool about it is twofold the first is example here let's go to this example for a second now we will create one more not employment but management and what does this do this is playing golf isn't it well that's how work is done so now got for a bit you say object dot set prototype of Sam to be management and now you use Sam and Sam is happy playing golf I you know when you really call work on it so this gives you the power of taking an object not changing the object but changing its prototype and changing its behavior at that point so in other words inheritance so here's a way to think about it right so class-based inheritance inheritance is static I'm using the word static as that is inflexible right on the other hand proto prototype o inheritance is flexible right is dynamic so what does that mean that is it is flexible right that is flexible so this is one big difference between how these languages do in the case of Java and c-sharp and various other languages once a class inherits from a base class you're stuck with it this is your base class forever right unless you change your code or use other advanced technique likes a o P let's not worry about that right now so once your code is written it's stuck to the parent well in here it's extremely dynamic during runtime you can change what the prototype is that's one interesting feature secondly you can take an object it has a prototype which in turn is a prototype which in turn has a prototype which in turn has a prototype which in turn doesn't have a prototype so eventually you will run out of it and so as a result when you go to an object and ask for something if it doesn't have it goes to the prototype doesn't have it goes to the prototype it keeps walking down the chain until it hits the end or finds what it wants and if it finds what it wants you're done if not it says sorry I don't have it so this gives you a really nice flexibility to build a hierarchy of prototypes let's enter in the start for just a little bit so moving a little forward let's say we have a let's go to the old style for a minute so constant car equal to function and in this case I'm gonna say card art miles equal to zero okay kilometers equal to zero right so in this example I have a value of zero that's I've defined for this notice where this is located it's on the car but I'm gonna put it on a card art prototype dot and every object has a prototype but let's examine this a little bit to understand how this actually works so I'm gonna say constant a car 1 equal to new car and I'm gonna say constant car 2 so a car 2 is equal to new car as well I want to ask the question is car 1 the same as car - well clearly no they're two different objects ok great is the tell me if object get proto type of car one is the same as object dart get prototype of car 2 well guess what the answer that second question is true because multiple objects share their prototype right so I have two objects but both the objects have the same prototype right so if you come from here to the prototype you come from here to the prototype they both are sharing the same exact prototype right that's what you're seeing here great now my next issue here I'm gonna go to this code we know the answer for these two but let's go over here and say drive what is the drive do it takes a distance and says this start miles plus equal to distance or kilometers in this case so great so far let's output car one but what does the car one's miles gonna be in the beginning is the question right so what's going to be the value well we'll come back to that in just a second so I want to ask the question where's the kilometers well that's located in the prototype so I'm gonna ask for the kilometers on car one I'm gonna ask kilometers on car - let's see what the result is in what it returns for us well this is a oldest in taxes isn't it so let me fix this a little bit so this is going to become part of me constructor well okay so this is gonna become the old style this dart drive is equal to function and in this case we'll take a distance and we will say this dart kilometers is plus equal to distance let's try this a little bit so zero and zero hey that's great we know the kilometer values are zero no doubt about it now let's get back here and say car one dart drive 10 and I'm gonna ask for car one dot kilometers and you exactly know what the value is gonna be it is a 10 but I'm gonna ask the question car to Dart kilometers hmm interesting notice the valley was in the prototype right and when we asked for the prototypes value it was zero and when he asked for the value here it was then we call the drive that is ten what in the world would that be the logical mind says it should be zero the emotional mind says damn it this is JavaScript who knows right so we're not sure isn't it oops warned me we're not sure and that's a moment of tension isn't it and you're like gosh and even worse if it does work you're like why does it work that's the next question so to understand this let's take a slightly different example and work through it so let's let's let's think about this a little differently and I need a bunch of wall and tears for this would you be able to volunteer for me you can sit there comfortably what's your name sir Marcel so would you be my prototype so he admitted it in public he's going to be my prototype so he's my prototype which means if I don't have a property I know exactly whom to reach into right and ask for well let's say what's your name sir sorry said again next case is let's say he comes over to me and says could I borrow a euro from you please you know what it's not a big deal it looks like a respectable person I'm gonna trust him here and I give him a Europe and a few minutes goes by he comes back and says I was a great help I just had to get something from the vending machine but now I have the cash with me thank you Venkat and he gives it back to me so we have built a trust between each other now so he gives he takes the euro from me he gives me back the euro everything is fine the next day he comes back to me and says wanker I'm in rush right now I know you I've given you the money back can I get a hundred euros from you you know what we've built a relationship already we have trust with each other so I want to give you 100 euros except for one problem I don't have a hundred euros what should I do that's the prototype right there's a reason why he Wallen teared so hundred euros please so what do they do he gives me 100 euros right I have a hundred euros with me now because I got it from the prototype and I give it to him well a few hours goes by he comes back and say spring kit you've been a great help again thank you so much and give Sweden back the hundred euros does anyone have a suggestion what I should do with this hundred euros I like your idea keep it does anyone have a problem with it I'm not obviously looking at him right so yeah only one person has a problem with it right but democracy rules anybody thinks I should keep it right of course so yeah if you understand how this worked you know exactly how JavaScript works so one of the things to keep in mind is this and when it comes to prototype the JavaScript prototype the way is gets our deep sets or shallow so let's go over this again he came to me and said can I have 100 euros please I don't have it my get is deep I go to my prototype and say could I have hundred euros please you know what if he doesn't have it he's got a rich person behind him and he can go through and eventually I get 100 euros gets our deep on the other hand when he gives me back the euros I keep it because such are shallow I don't go down so to understand this when I run the code this time this is the reason why the value is a zero as you can see but let's go a step further to prove this notice now I'm gonna comment out all of this code for a second and I'm gonna go back here and just print the car when I print the car notice what you saw here the car has a drive no sign of kilometers right now then I go to the second one and I print it also no no sign of kilometres again at this point then I call the drive on that one then I go back to print car one all of a sudden notice car one now has a kilometers now that kind of nails it isn't it when you asked for kilometers on line 12 the car didn't have it so it went to the prototype and got it but on line number 15 when you said car dot Carwin Drive you went to line number three line number three said this dart km equal to that's a set but a set is channel on this where this is a car object and as a result it said it on the object and if you go back and examine car two right now because we did not do any set on car to notice there's no km on car too so this illustrates and thanks for your help this illustrates how the gets are deeper but sets are shallow and this is the magic of prototypal inheritance in JavaScript and it's important to keep this in mind the reason I emphasize this is the syntax here is horrible but the behavior is fantastic I love prototypal inheritance right because it gives you some enormous power on your hand so so the way they have done it behind the scenes is really good the syntax is horrible in the modern JavaScript the semantics is exactly what I showed you here no change whatsoever the syntax is elegant but there's a problem the syntax is so elegant that we tend to forget what it really is under the hood so we have to keep in mind while the syntax is different the semantics is still the same as it was in JavaScript there is something we have to be very careful about so now let's get to the modern syntax so how do we inherit from a class so to understand how this works let's get back to a class called person and I say constructor will say first comma last and I'm going to simply say over here this dart first is equal to first and this dart last is equal to last now let's go ahead and say a constant let's say for example here is Sam equal to new purse we'll say Sam and we'll say Walker here and then let's go ahead and output the value that's the value but let's create a class now called you know a cool person and this extends from person now look at this code for a second if this was JavaScript sorry if this was Java or C sharp you will be now writing a constructor javascript says sit back and relax if you don't want a constructor don't write one they will do the wiring for you so if you don't write a constructor one is written for you already you don't have to put any more effort into this now what am I going to do I'm gonna go back over here and I'm gonna say over to string and what is a to string method do return I'm gonna return this dart so this dart first and space let's say this dot last so I'm gonna return that value to the cool person to the person if I go back over here to this code now and if I say constant and I'm gonna say Allen equal to new cool person will say Allen right here and I'm gonna create over here an output Allen so when I output Allen you can see I can call the two string method right in there without any difficulty and it says Alan Turing but I want to provide a coolness index over here so constructor now I'm writing a constructor because I want to extend this further so constructor and I'm gonna say first last and index and I'm gonna then say over here super and pass the first and last then I say this start index is equal to index this could be a coolness index I want to set so as a result I can go pass a value here into this now just to illustrate this if I move this here it is angry I cannot touch this until I pass the data to super but of course what I can do here though is I can simply say called and that's perfectly fine I just cannot touch that this in this particular case so you can pass the data to the base very nicely well that's awesome we are able to pass that into the base nicely but having said that if I go back over here I can override the two strengths now the syntax was horrible in the past but look at the beauty of this return super dart to strength and then $1 this dot index and I can just pass that value very nicely at this point to the base and then use that information here without having to do extra work so that becomes a very nice way to do the super call to the base class as well while you do all of this it's absolutely critical to keep in mind while this looks like class-based inheritance the syntax is so close to what we do in Java isn't it but but the reality is far from the truth in terms of how Java works this is not class-based inheritance this is object based inheritance that is something we have to be very very very careful about just to illustrate the point if I go back here to Allen and I'm going to output a object dart get prototype prototype off and I'm gonna say Allen notice that's the cool person all right now let's just go one more level object dart get prototype off and ask one more level and that's the person so you can alter the prototype and do things let's same way you did before but you have to be very careful altering it though but these are some of the new methods given to you so methods like get prototype off and set prototype off make your life a lot easier and as a result it gives the ability to reach into the object and and be able to talk to this object in terms of prototype so the inheritance model is very different in JavaScript - what's in Java one of the fears I have about this is they made the syntax so much like Java we tend to forget this and say oh this is inheritance well we got to keep in mind this is not class-based inheritance this is still object based inheritance which is prototypal inheritance and as a result the behavior is very different while class-based inheritance is not flexible the prototypal inheritance is extremely flexible and so you are dealing with the completely different semantics in the language compared to what you're used to in language like Java and JavaScript this is also important to keep in mind when you program in language like typescript right the same thing applies to it because types which compiles to JavaScript so the semantics is JavaScript semantics even though the syntax is Java like syntax and then we have to be very careful about it otherwise we could be in trouble with it so this shows you how you're able to define it you can also have properties overriding as well so you could override a property and call the super on the base as well if you really wanted to do that so if you want to do more energy 'king on your properties in their derived class you can do that as well and then forward it to the base class it works really nicely and like I said one of the nice things about this is if you don't write a constructor it writes a constructor for you so when I write code in you know libraries like react I write a react component which is which is something like this I would say class my component and then extends all from here and I say component but the only method I usually write is the render method where I return something from this and the beauty of this is I can go ahead and say import for example react comma component over here and and then of course from react but I don't bother to write a constructor and the reason I don't bother to write a constructor is I'm not doing anything special in the constructor but if I do want to do something in the constructor then and only then do I write a constructor and then I say probs but then I immediately say super and send the properties to the base class and then I do the code whatever I want to but the beauty is if you don't have this line don't even bother writing the rest of the constructor that's a waste of effort because inheritance automatically forwards things to the constructor for you without you having to write anything so that becomes really easy to work with in terms of inheritance you don't have to put too much effort into writing that so that gives you an idea about how you are able to use inheritance in this case to forward the data to the base class so that becomes a pretty nice way so so that is about writing a constructor and we talked about the default constructors we talked about overriding that that's also there are quite a few other things you can do with JavaScript and one of them is modules modules is not entirely implemented properly but you have to be a bit careful how you implement modules but one of my favorite in JavaScript modern JavaScript is also meta programming and they have introduced a concept of proxies which is pretty amazing and proxies all of you to inject behavior into classes at runtime so that you can synthesize methods while the code is executing and that is something you can do as well which obviously takes us into some advanced features of the language but if you're used to language is like groovy in the past one of the things I enjoyed in language like Ruby and groovy is that you're able to inject methods at one time based on a certain runtime behavior well you can do that now in modern JavaScript thanks to the introduction of proxy and as a result you can inject behavior into the class at runtime much like you do in language like groovy and Ruby and that takes you through the next level as well so to summarize what we talked about here we talked about the capabilities of the language some really nice capabilities in terms of using the code for a day-to-day programming we also saw how the syntax is so much cleaned up in terms of creating classes and then we saw how inheritance works as well and again there the syntax is cleaned up a lot if you are interested further please do take a look at the book rediscovering JavaScript if that is something and I cover a I probably covered about I'm gonna say 70% of what's in the book in the stock and and there are a few other concepts in there in the book as well so that's something you can take a look at if you're interested if you want to download the examples I showed you here you're most welcome to download them from my website as well if you look for examples you will find them there that's all I have hope that was useful thank you [Applause]
Info
Channel: Devoxx
Views: 21,813
Rating: 4.9764242 out of 5
Keywords: Devoxx, Devoxx2018
Id: dxzBZpzzzo8
Channel Id: undefined
Length: 144min 59sec (8699 seconds)
Published: Wed Nov 14 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.