JavaScript Best Practices and Coding Conventions - Write Clean Code

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everyone and welcome to another video in this video we are going to talk about coding conventions coding conventions are a really important part of any programming language they are style guidelines for programming and they typically cover naming and declaration rules for variables and functions rules for the use of white space indentation and comments and programming practices and principles in this video I'm going to cover the most important JavaScript code conventions if you stick to the rules stated in this video people will perceive your work differently your team and your boss will appreciate you for writing clean code but most importantly you will be thankful to yourself coding conventions secure quality improve code readability and make code maintenance easier they can be documented rules for team to follow or just be your individual coding practices Robert C Martin once written clean code reads like well written prose clean code never obscures the designers intent but rather is full of Cris abstractions and straightforward lines of control this one sentence really embodies the importance of clean code let's see what those rules are in JavaScript and how we can implement them in our code let's delete this right here and let's start with our first rule I will write every rule like this in the comment and down below the example of the code so let's start with magic numbers so what are magic numbers imagine if you saw a code like this so we have a loop which starts at 0 and then we have index is smaller than 8 6 4 0 0 and then we have implementation of the eye and we can do something right here do you have any idea what this number stands for this is some random number right here and maybe the person who brought it had in mind what this is for but when someone else is reading the code later they have no idea what this number stands for magic numbers mean that we are assigning a number with no clear meaning so it's better to replace it within constant so we can do something like Const seconds in a day and we can make it equal to eighty six thousand and four hundred this is much easier to read because then we can replace this and it becomes easy and understandable for everyone what we just did here later in this video I'll tell you why did that use upper snake case for this okay now we can move on to our second example or second rule rather and it is deep nesting if your code contains many nested loops or conditional statements then this should probably be extracted into a separate function so let's say we have something like example array and it is equal to an array of an array of an array and it has one value so this is just an example you may come across code like this in your application but let's just take this as an example let's say we want to retrieve this value inside of here so to retrieve the central value right here we could do something like example array that for each and then we can pass in our first element which is going to be this array so we are going to loop through the first item of this array and we can call it array 1 for example then we can do something like this and just call a right to so this time we are getting inside of here and for the third time if we call array that for each so like this but now this needs to be array 1 and this needs to be array 2 now here we have element and we can console that lock this element and we indeed do get this value right here we can test this in the console right here if we copy our code we can get something like value right here and that's okay we indeed are doing what we are supposed to retrieving this value right here but as you can see in here we have many nested values one for each second for each third forage and this code actually breaks more than one rule it breaks two or three rules first one is that we have deep nesting right here the second one is that we have a lot of code repetition so this also needs to be solved to solve this specific example in a correct way we can create a function that will look through old arrays and return a final value so we can do something like Const retrieve final value and we can make that equal to an aryl function and inside of here we are going to have an if statement and that if statement is going to check if our element is indeed an array so we are going to pass an element to that function sometimes that element is going to be an equal of an array like this or this but sometimes that element will be equal to a string so when it is indeed an array we want to call this function again so we're going to call the three final value but this time it is going to have an index of zero so we'll pass element and then zero this will simply return the whole array and then we are checking if it is an array and if it is we are passing the first index so this is it the second time we are passing this array and this element zero is going to be this and the third time we are passing this array now this if statement is not going to work and then we simply want to return element now we can remove this actually pass our example array to our function call copy all of this and get back to our console we can refresh remove the earth and we can run it and we indeed do get a value so you can see that we do get the same thing but this code is much cleaner and much easier to read it is also less repetitive and it is also pre usable third rule may be a personal attack on some of you it is stop writing comments although subjective the use of comments in your code can be helpful but could also be a sign that your code is failing to be self explanatory there is a great quote by Jeff Atwood that sums this up perfectly while comments are neither inherently good or bad they are frequently used as a crutch you should always write your code as if comments didn't exist this forces you to write your code in the simplest plainest most self-documenting way you can humanly come up with so this really sums it nicely comments can be good but your code should be self documenting it should speak for itself if you think that sometimes you cannot write something that could be easily understandable without writing comments beside it this video is exactly what is going to help you so this is one rule it is subjective a bit but you can choose to follow it and many will appreciate the cleanliness of your code without comments so this is the third rule we can also add code must speak for itself make it self documenting now on to the fourth rule which is avoid large functions function or even a class that is large in size suggests that it is doing more than it should so let's create an example our example is going to be quite simple and we are going to call it add multiply and subtract it is going to be a function an error function that is going to accept three parameters a B and C the function needs to find addition multiplication and subtraction of these three numbers and then it needs to return a string where each result is next to one another so result one result two result three and we can even replace this with our pseudo variables just like this so this is what our function is to do let's create that we can first create an addition so we'll call addition equal to a plus B plus C simple as that then we can have multiplication this will be equal but we will just have times and we can create subtraction which is just going to be minus now when we have this set we can return and that return statement is going to return a template literal and inside of here we going to have addition and we should rename this some multiplication and subtraction and we are simply going to return it side by side one next to another like this okay this is all set now our function is going to return a string of first addition of these three numbers multiplication of these three numbers and subtraction of these three numbers it is quite simple but with this simple example I just want to stress the fact that this function is doing more than it should imagine if all of these statements right here so this one is actually another function inside this function that is doing some logic that is extending over 20 or 30 lines right here and then this function is also doing something that is extending even more and we have such a long function doing so much stuff that we forget what we are doing and as you can see at the end we don't even know what we are returning now this is quite simple for this example but imagine if you had larger function now let's solve this in a way that will complement our clean code so we can simply leave this as it is without these long lines let's remove that it's better to create different functions to separate the logic so let's first create a function that is going to add three numbers together we are going to have a B and C and we are simply going to return an addition of these three numbers a plus B plus C since we are using es6 arrow functions we do not need to write curly braces we can simply return the value like this and we can also copy this we can call it multiply and subtract and now simple as that just if we remove just if we exchange this values right here now we simply have three different functions we separated all the logic and now we can use the result of this function anywhere we want in our application now this may seem over simplifying things and separating too much logic there is little logic here but when you have a function that is doing a lot of stuff simply separate it into an function and then call this inside one function and return what you should okay so let's remove these comments right here and we can move on to our next rule okay our next rule is called repetition we mentioned something about code repetition in our second rule but in here we are going to take in a look of how we can solve it so called repetition if you have to copy and paste a block of code it's a sign that the repeated block may need to be extracted into its own function great example of this is our deep nesting example we had at the beginning so we can simply copy that and paste it right here in here as we said we have the same code repeated all over again we have three times repeated the same for each statement we have a lot of repeated code it's much better to extract it to a different function and handle object differently with less repetition we already did that in our first example so this is exactly it we have an example array and we are not repeating any values anymore because we simply created a function that is solving the problem for us another great example of code repetition is retrieving data from parameters so if we have something like cons get user credentials we make it equal to an error function and in here we have a user now we can do something like Const name is equal to user that name and we can also do something like surname may be password email and we can extract many different things like this but as you can see here we are actually reading the values quite a lot so this is not a good practice with es6 objects structuring we can simply do the following we can extract all of this in one line so we can type Const curly braces and we can take anything we want from this user so surname password email and make it equal to user this will actually extract all these values from the user object and it is going to be the same thing that we had here but with less but with much less repeated code so we can remove this and we can get back to our next example camel case is a naming standard we use for identifier names for example variables and function it states that the name needs to begin with a lowercase letter so let's say we have some concerts right here and we need to begin with lowercase so camel for example and then every first letter of the next word is uppercase so for example camel case this is a camel cased variable let's set it to an empty string we can write some more examples so Const this is a random camel case name you can see that anything can be written in camel case we can also write something like example function name we also have for example get user credentials right here also written in camel case and add multiply subtract retrieve final value everything we write in JavaScript should be camel case another important rule regarding variable naming is use meaningful names it is important to use meaningful names to our functions method methods and variables and they need to express their exact meaning so let's say if you are fetching posts from some user we can type get user data for example we can call a method fetching post like that and we can also call get user info for example but what info or data are we actually getting much better way to name it is get user posts with this we know that we are getting exactly that posts nothing more and nothing less also when you're not sure favour descriptive / concise so this should be used only when you are not sure if the concise way is meaningful enough you should always be as concise as possible however if your having difficulty finding a two or three word description for your name it is better to stay on the side of being descriptive for example if you need to find a user from your database find user may be good but find user by name or email is much more descriptive and much better and for example set user logged in true is much more descriptive also than just find user but when there is a shorter version use it so use this long names only when you're not sure if the concise name is descriptive enough but when you're sure use a shorter version while for example get user from database is really descriptive there is a shorter version that means the same thing the key question you should ask yourself is does from database add any meaning to your program the most likely answer is that it doesn't we can assume that we are fetching the user from the database and we can simply call our function get user simple as that the next rule on the list is that we need to use consistent verbs for concept functions we'll usually create read update or delete something you could even be a bit more descriptive and say they create get set add remove reset and laid things a function should be a verb or a verb phrase and must communicate its intent we need to be consistent with our verbs for fetching we can always use get for example rather than get retrieve return and 10,000 different names for example if you're getting some questions we can simply call it get questions if you are getting some users you can call our function return users and we can also call it retrieve users but all of this is incorrect if all of these methods do exactly the same thing if you call them you get this thing so you get questions you get users and in here you also get users so it is much better that you use yet for each single one of them or for example if you are creating something then use create for each one or delete whichever verb you choose make sure you stay consistent so this can be much better if we use simply get for each of them much better another great thing for naming variables is that you need to make your boolean s-- read well in an if-then statements so for example if we are checking the characteristics of a car which naming would you find more convenient in here we have only sedan salt green air bag let's just create a variable named car so I can easily fill it out and now if we are checking if our car is indeed a sedan we can simply call car sedan or car that's old car that green or car that air bag you get a point what does car a OPEC really mean or car green or car Sol it is much better to do it like this so car is sedan and then we can read it like this if our car is sedan or if our car is sold if our car is green or if our car has airbag this is much more descriptive and is much better to use this naming for our boolean variables this sounds more natural and make the program easier to decipher now regarding the class names this could also be a class since it has some properties right here but let's move this to our next room which is use nouns or class names classes don't take things they are things more specifically they are a blueprint for something creating a class is what makes something if this is a bit weird to you let's write it down and you will see that it is actually quite simple we can write something like class car is equal to and then we can put like this capital C because we write all our classes in pass a case opposed to camel case for variables and functions I'll show you that in the next role and now you can see that this is much better than class make car is equal to and then do something because if you are making a new car you wouldn't say make a new make car you would say make a new car this is much simpler and simply use nouns for class names the second rule is to use Pascal case for class names so if you have a class use Pascal case Pascal case is simply like camel case like here but only the first letter is also capitalized so we can have Pascal case right here if you use that everyone who uses Java Script knows that it is indeed a class so we have something like class tasks it is simply much more descriptive than class tasks because then we don't know if this is an object or a class that's it for this rule and the next rule we briefly mentioned it is capitalized constant values we had it right at the beginning when we had seconds in a day remember that we've written our seconds in a day like this Const seconds in a day is 86,400 in here we are using yet another case we are using snake upper case so snake case is simply boards divided by this underscores and upper case because it because it is all upper case there are a few things we need to remember when it comes to this rule a constant value is something that won't change this convention has roots in C and is not always followed in JavaScript keep in mind that Const and the term constant are not the same the Khans declaration simply means that value can be mutated reassignment but a true constant value is a primitive value that won't be changed later also you may consider narrowing the definition to values that are not only primitive but also inherently fixed such as ours in a day the value of pi' or the names of the days in the week for example hours in a day and user age is a primitive value that is not going to change in this case and they should be capitalized but for some other example we have user which is capitalized right here but it shouldn't be so these two examples are wrong this user is equal to a found user and found user can be anything we are fetching it from somewhere so this value is actually changing and this user is not a constant today is equal to a new date which is changing every single day so although we set it as a constant right here this is not a fixed constant so it will be better if we called it like this and the user like this okay another rule which is really important is to avoid one letter variable names are shorted names cause more hassle than the keystrokes you save in the long run a variable initialized in the global scope may end up being used 100 lines later it becomes easy to forget what it was if it is only a single letter so for example let's say we have something like Const Q is equal to an error function and we do something inside of here we can also write it like this what is Q someone who reads the code later has no idea what Q means but if you do something like this Const query this is much more meaningful we know that it is some kind of query and related to the code next to it we could guess what this function does also we can have another example so let's say we have something like Const D is equal to new day this is not descriptive and when you use it later recall and you use it later in code you'll need to scroll up all the way where you initialized it and you'll need to see what it is but if you simply call it new date or something like that you will always know that the new date is equal to a new date so you need to be descriptive with your variables there are only a few situations where you can use a single letter variables names you can limit them to a really small functions where you know exactly what this single at your means and also it is okay to use them as an index in loops you can indeed call this index this is a really small and closed loop or function this is okay you know that this index is actually indexed inside of this small closed loop so this is okay but when you have bigger functions or any other variables you simply use more descriptive names and it is much easier not to get lost 100 lines later when you're looking for what is Q or this D or anything else means so avoid one letter variable names unless it's inside of a loop remember these conventions for your own future sanity we went through it all there are a huge benefits to following this rule in a long run when others take your code you've written a few days or months or even years ago they can immediately see what you were thinking when you're writing it and they you'll be able to continue adding some new features easily clean code makes it easier to start and continue coding it is better for the individual as well as I team and it is much easier to read so always make sure to write code that is elegant and focused we went through all these rules you you need to avoid magic numbers deep nesting you can if you want to stop writing comments avoid large functions never be repeated call your petition is not good in programming also your variable names need to be meaningful they need to favor descriptive or concise to be consistent with your code names so the person who to your whole source code of some application when you use get for every single thing for example get question get users or anything else they don't know that this method simply receives something and get something so always use get but when you're creating something you use create so it is descriptive as that I cannot stress enough the fact that bully ants need to be written correctly if this car is green or if this car has airbags it is really easy to understand that these values indeed are boolean values also we mentioned that we need to use Pascal case for our class names and that we need to make them announce and not verbs because they are something they do not create something also we learned that we need to capitalize constant values with snake uppercase so if something is really set in stone like seconds in a day hours in a day user age or something like that you can make it a constant written in snake uppercase also one of the biggest roles is to avoid one letter variable names be descriptive be concise but also make sure that everyone knows what this variable name indeed is if you have some of the coding conventions for JavaScript that you personally use make sure to let me know in the comments that's it for this video thank you for watching and see you in the next one
Info
Channel: JavaScript Mastery
Views: 52,650
Rating: 4.9376297 out of 5
Keywords: javascript naming conventions, js naming convention, js naming conventions, javascript coding standards, javascript coding standards best practices, javascript style guide, airbnb javascript style guide, javascript clean code, javascript clean code 2019, javascript best practices, how to write clean javascript code, variable name javascript, camel case javascript, clean code, clean javascript, javascript coding conventions, js coding conventions, javascript conventions
Id: RMN_bkZ1KM0
Channel Id: undefined
Length: 28min 6sec (1686 seconds)
Published: Sun Aug 25 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.