Do THIS to Write Clean Code! | JavaScript Pro Tips (2021)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] do you want to write code like a pro in this video i'll give you some examples of code that works but could be written better make sure that you watch through all of the examples so that you can learn how to start writing clean professional code i'm jesse if you're new to the channel i post weekly videos to help you learn web development if you like this video give me a thumbs up and subscribe for more content like this inspiration for this video came from this repo from ryan mcdermott clean code javascript credit where credit is due be sure to check out that repo the link is in the description let's start with something simple variables how do we declare variables so we could say let a for an undefined variable and then let b equal one and that's fine nothing wrong with that but we could make this cleaner instead of doing that we could say let a and then comma b equals one and that is the exact same thing but it's all on one line and what about assigning values so if we have some undefined variables a b and c then we could assign them so later on we could say a equals 1 b equals 2 and c equals three but there is again a much cleaner way of doing this we could just say let an array of a b and c equal an array of one two and three and that is the exact same thing all right now let's talk about naming variables so we want our variable names to make it easy for any developer to quickly understand what's going on from a quick glance at this code can you understand what's going on i have no idea what ca is why it looks like the year okay so that's pretty obvious i don't know what fs is we have a cart and total so that was named well but i have no idea what the rest of this is so let's fix this so ca actually stands for cart active in days so let's say days cart active that makes a lot more sense we know that it's been five days since the cart has been active and then for a year we could say year to spell it out but what year is this so let's actually make that even clearer by saying current year so fs actually stands for free shipping so if the cart total is over 50 then we're going to set free shipping to true and this part of the code can actually be cleaned up even more so instead of declaring fs and then doing our check we're going to do all of that in one line so let's create a const of is shipping free we're going to make that equal to heart dot total if it's greater than 50. so this one line is the exact same thing as these four lines now to make this even better what if down the road we want to change the 50 to maybe 30 maybe it's in our code multiple times so instead of finding all of those places where we have the 50 we can have its own variable just for that all right so let's go up here and let's create a constant we're going to call it free shipping min price we'll make that equal to 50. and now we can just put that here now this is much cleaner and any developer can understand what's going on all right let's take a look at this next example we have a const of books and we have an array of books and then we're looping through these books we have books.4 each and then b and an arrow function and then we're going to do stuff we're going to do some more stuff do some more stuff do some more stuff and then we're going to read b i've already read through all of this other stuff and now i've forgotten i have a terrible memory what is b so let's just spell it out it makes it much better so books for each and then we have each book that makes it so much clearer don't rely on the developer's memory to know what b is all right let's look at this next example here we have a book and it's an object we have a book id a book title a book price and book pages looks pretty good right now when i go to actually use this i'm going to have to say book dot book id book dot book title book dot book you see book dot there's unnecessary context here so let's remove this redundant book so let's take that remove those and now i can just say book dot id or book.title price whatever that is and that's very apparent here that this is the book price right now let's say we have an imaginary object of address and the address has our street city state all of the information in it and we want to extract those into variables so we could say const street equals address dot street and now we also want to get the city so we'll say city equals address dot city and then state equals address dot state and then zip code equals address.zip code and we have all of these lines to get this information that we need we can do this much easier with something called destructuring so instead of these four lines we can create a const that is an object equaling the address and then within that we're going to pull out those pieces of information that we need so we need the street the city the state and the zip code and that is all that we need to do so this one line is the equivalent of the four lines above it we can now use street city state and zip code as variables in our code all right let's take a look at this next example here we have a function send email it's going to accept three arguments two which is the recipient subject and the body all right so that looks okay and then we're going to check that if we have a recipient then we're going to send the mail else we're going to return please enter a recipient all right so this code works but it could be much cleaner so when i actually go to use this watch we'll say send email and then i need to enter a recipient so i'll just say abc at bc.com and then i have to know that the next part of the function is the subject so let's type in that subject and then i have to know that the next part has to be the body so here's the body i get these mixed up then it's not going to work there's a much better way of doing this let's pass an object as the function argument all right so instead of doing this let's wrap this in curly braces this is going to be the start of our object so this first one is r2 we'll have our subject and then we'll have our body and now we just learned about destructuring so right up here in the function all we have to do is wrap that in curly braces and now we're extracting our to our subject and our body from this object and these can be in any order and they'll work just fine now there's another issue with this function so first we're checking and then we're doing something and then else we're returning so we could change this up by using something called a guard clause so instead of saying if to do this let's say if not 2 so if 2 is not there then let's just return please enter a recipient and then we can get rid of this else and this is the exact same thing just much clearer and easier to read so the first thing we're doing is checking and if it's not there then we're returning and the code execution will stop if we don't return then we'll send the email let's take a look at this next one we have favorite color function where we're passing a color and then we're saying let selected color equal color or blue so if for some reason a color is not passed or this is undefined then we're going to set the default to blue and then we're returning that selected color all right so then i'm console logging favorite color and i'm passing in red and i'm getting red as the console log and by the way i'm using an extension called quoca to do this this extension allows you to easily see values and variables within vs code and also jamesquick has a great video on quoca so again i'm passing red and i'm getting red now if i were to delete this and not pass anything something undefined then it would be blue now all of this is redundant we don't need to check this we can set a default argument so right here in our color all we have to do is say equals blue if we want blue to be the default so let's just get rid of that line there and instead of selected color let's return color and now if we pass something undefined we're getting blue if we pass something else we'll get the color that we passed really quick like this video it helps me out all right let's look at this example we have if is admin triple equals true then do something all right that's fine that works just fine if is admin equals false then do something that's fine as well but there is a conditional shorthand we actually don't need this triple equals true we just delete that then it's if is admin so if this is true then do something and then for the false we can again delete the false and then we can just at the beginning add a bang or an exclamation point and that is the opposite so if is admin is false then do something all right let's take a look at this code so we've got some variables first name is billy last name is bob and then we have a greeting that is hello first name and last name and then we're console logging and again we're using quoca here so we have hello billy bob all right so if you are using concatenation like this still that's so 2020 you need to switch to template literals so we're basically just going to wrap this in backticks all right so backtick is generally the key to the left of the number one on your keyboard and then we can just get rid of these quotes get rid of that quote get rid of these pluses and then we just have to wrap these in dollar sign curly braces and we're getting the exact same thing hello billy bob and the cool thing about this is we can separate these on different lines and make it easier to read if we needed and now we're getting the exact same thing still let me show you something even cooler let's go back to the original example if we just select anything in this line here we'll get this little light bulb so if we click on the light bulb convert to template string one click that's it that's amazing alternatively if again you're in the string and you just press ctrl period you'll get this pop up here convert to template string boom how easy is that and even better there's an extension that can help you out it's called template string converter so as you're typing if you use normal quotation marks and then you decide i need this to be a template string and you type dollar sign curly braces it automatically converts the quotes to backticks if you want to learn more about vs code tips and tricks check out my vs code hero course to become a vs code superhero the link is in the description all right let's take a look at this function this is hurting my head already so sharepost is an arrow function and we're going to get post it looks like this is a promise so then we'll have our post and then once we have our post we're going to send a tweet okay so this is like when you're reading an article and you want to share this article as a tweet we're sharing the post all right so send tweet and we're going to pass our post url we're going to pass in this message this is an awesome article the post title this is another promise so then we're going to console.log tweet tweeted of course all right there is a much cleaner way of writing this that is easier to understand all right so let's rewrite this so we're gonna have our const of sharepost and that is going to be an async function now within an async function we can have our post so get post we're going to have that be the post here but we're going to await get post all right now after we have awaited that then we'll have our tweet so send tweet that is going to await send tweet so within the sin tweet we still have our post because we've awaited that up here we can use it so we have our post url we have our post title and we're sending that in our tweet we're waiting for that tweet to come back and then we're going to console log tweet tweeted you can see this is much cleaner and easier to read now async await is really just syntactic sugar on top of promises so it's really it's using the exact same thing on the back end but it's just easier to write and read on the front so this is called linear code as opposed to nested code next we're going to talk about the single responsibility principle okay so a function ideally should only perform one action so let's take a look at this function we have email users and we're passing in our users and then users for each user and then we have a user record which is some database that we're pulling from and we're looking up the user and then if the user record dot is email notification so if the user accepts email notifications then we're sending the email all right so email users is not just sending an email it's also checking to see if the user has notifications turned on so we need to extract that check to a different function all right so let's create that function we'll create a function is user email notification that's going to accept a user and then we are going to get a user record which again is just a fictional database lookup on the user and then we'll use that user record to return is email notification okay so this is going to return a true or false value whether they have notifications turned on or not so now up here we don't need to do that check in fact we can rewrite all of this we just say users dot filter so we're going to filter out using this check function that we created so anything that has a true value will then be passed to a for each and we're just going to send the email so much simpler and now if we need to check for email notifications in any other function we can then reuse this function let's take a look at this example now so we have a save image function that's being passed a name and a type okay so then we're doing a switch over the type so if the type is jpeg then we're going to create the file in a jpeg directory okay with using the name if it's a ping it's a ping directory and then the default is just create with the name no directory okay so this is one function doing multiple things or deciding things based on a flag so again a function should only have one function let's try to avoid using flags as arguments we're going to separate these into multiple functions okay so what are the things that we need so we're not going to be switching over we're not going to have these cases or these breaks get rid of all of this and now this is the essence of what we need okay so we're not going to have the type we just need the name we have save image and the default is this fs create with the name so let's move that up here so this is going to be our default function here so let's go ahead and close that out now let's create a new function and we're going to call this one save jpeg image again it's going to be passed a name and then let's just bring this up right there okay so now we have a save image a default save image and we have a save jpeg image now of course we need a save ping image with a name and then again let's bring this up now that is much cleaner and easier to understand if you want to save a jpeg image just use the jpeg function all right let's take a look at this next example we have a name billy bob and we have a function split into names all right so name is going to equal name.split and then split into names we're calling that and then we're in a console log name so we started this with name being string billy bob and we ended this with name being an array of billy and bob now this is what's called a side effect and we want to avoid side effects side effects are when actions inadvertently change mutate or create an unintended outcome so what if we were using name somewhere else in our code and we needed it to be a string well we've mutated name here when we called split into names so we don't want to do that so instead of doing that let's create a new variable we'll say let name split equal split into names name and now we do need to pass into here our name and then instead of setting it equal to name we just return the name split and then we'll get rid of this one and now name is still a string of billy bob and then if we console log name split we'll get our array of billy and bob let's look at another example here of ways to avoid side effects now there's something called immutability we want our variables to be immutable that means not able to be mutated so in this example we have add user where we're passing it a user's array and a new user and then we're pushing onto the user's array our new user so that is directly modifying or mutating our users array that's not good so instead of doing this we're going to return a new array we're going to spread our users and then add our new user so the three dots is a spread and basically it takes the existing user's array and it spreads it out first and then at the end of that you can tack on whatever you need all right let's look at another example of using the spread operator so here we have some objects we have a name object with a first name and a last name we have some hobbies so basketball golf video games and then let's say we want to take those and we want to combine those into a person object so we have a person here so we want to get the person's first name right so that would be name.firstname and then the lastname is last name and then their hobbies so basketball would be hobbies basketball golf hobbies golf and video games hobby video games all right pretty straight forward this works just fine and then we go down here we see our console log and we're console logging our person we have our first name last name and all of our hobbies so there's a much easier way of doing this instead of all of this we can delete all of this here and just spread out our name and then spread our hobbies that's it again we're console logging person and we look here it's the exact same thing we have our first name last name and all of our hobbies all right let's take a look at our next example so theoretically we have a person object and we want to get the street of that person so generally this is how we would do it we have to first check to make sure that we have a person and if we have a person then we want to make sure that we have the person's address and if we do have the address then we'll get the address dot street there's a much simpler and easier way to do this now we can eliminate all of these checks go back to here and then simply before the period add a question mark so now if person is undefined we won't get an error and street will just be undefined again same thing with address if it's not there street will be undefined and again if street is not there street will be undefined if it is there then it will be defined all right let's take a look at this next example we have a number that equals 10 and then we're declaring a variable of result and then we're doing some checks so number if it's less than zero then the result is going to be negative else the result will be positive all right so we're going through all these checks and then we're setting result and then we're going to console log result and we see that it's positive and if we change this to a negative number here then it would be negative right so there's a much easier way of doing this we don't need to declare and then check and then set we can do all of this in one line so let's just remove all of this up to this point so we're going to say let result equal and then we're going to do a check number less than zero question mark so that's a check so if it's true then we'll say negative and if it's false we use a colon to separate that so if it's false then it would be positive all right so now again we're getting console log of negative so it's working just fine this is called a ternary operator okay so this first part here is our check this basically our if statement and if it is true after the question mark is what will run and if it is false after the colon we'll get positive so let's change this back to a positive number and there we see our result is positive all right another example here we have let color scheme and then we're saying scheme is going to get color scheme then we're going to do a check on the color scheme if we have a color scheme then color scheme will be scheme else color scheme is dark so this is a very long way of saying if there's a color scheme set it and if there's not set the default to dark this works just fine but there's a much easier way all we have to do is say let color scheme equal get color scheme and then if this is undefined then we'll just set it to dark by using two pipe symbols and then let's get rid of this last curly brace here this is all that we need so if this is undefined this is an or operator and then we'll set it to dark if this is defined then whatever value comes from this will be assigned to color scheme pretty simple so dark will be our default value all right so in this next example i've never actually had to do this but let's take a look at it so we have a equals 10 and b equals 20. and we want to swap those values so in order to do that we have to set a temporary variable so we're going to create this variable of temp we're going to make it equal to a because next we're going to set a equal to b we couldn't then set b equal to a because a already equals b and if you're confused then that's good because i am 2. so we have to have our temp variable here so a equals b and then b equals temp and now with console log a and b and now they're the opposite a is 20 and b is 10. all right so there's a much easier way to do this as well so instead of doing all of this we just delete that and let's say a b equals b a that's it super simple we're done all right let's look at the next example here so we have a very simple function that adds two numbers so we have add we have our numbers and then we're going to return the sum of the two numbers all right so we're console logging add 2 and 2 and we're getting 4. perfect all right nothing wrong with this there's just a much easier way to do it so instead of this way we can turn this into an arrow function so let's change this function into a const and then add is going to equal an arrow function all right so let's just change this up a little bit and now we could actually just stop here if we wanted but we can make this even simpler so we have our numbers and then we're returning the sum of the two numbers all right so we can implicitly return these let's just get rid of this return in this curly brace and then the ending curly brace and that's it so by not adding curly braces whatever is after this arrow here will be implicitly returned all right let's look at this next example we have a quantity and we're going to parse a string percent the string of 4 5 3 and then we have a total and we're going to parse float because this is a decimal value so for 42.6 right so then we're just going to console log these and we see these are now numbers of 453 and 42.6 there's an easier way to do this so instead of using percent we can just delete that and then at the beginning of this just add a plus and same thing with parse float we can delete that and then now you can see here that this is a string of 42.6 but as soon as we add that plus to it it's now a number 42.6 pretty cool i hope this video was helpful like this video to help me out and subscribe if you haven't already for more videos like this [Music] you
Info
Channel: codeSTACKr
Views: 32,534
Rating: undefined out of 5
Keywords: clean code js, clean code javascript, write clean code, how to write clean code, javascript, js, javascript tutorial, try javascript, code this not that, junior vs senior dev, noob vs pro code, beginner code, how to write better code, how to programmer better, clean code, how to write code, how to program better, senior developer vs junior developer, senior dev vs junior dev, junior dev mistakes, junior developer javascript, junior vs senior developer, Javascript clean code
Id: ZI3q-_vjSZE
Channel Id: undefined
Length: 26min 13sec (1573 seconds)
Published: Fri Feb 26 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.