21 LIFE CHANGING JavaScript tricks

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what's up guys this is 21 life-changing javascript tricks and i've named it that because these are high leverage yet simple tricks that can save you a lot of time energy and pain in the future now before we get started i just want to mention my 100 free javascript cheat sheet there's no reason not to download it and this is just javascript syntax you definitely don't want to forget so link in the description and you can also get it at don't forget javascript.com finally i'm also releasing a javascript web scripting course very very soon we're going to be doing four different projects that show you how to get awesome data for your web apps and not only that but we're going to be covering how to design a good data model how to insert this data into either a google sheet or a database as well as much more so stay tuned for that but if you definitely want to get updates on that follow me on twitter at underscore aaronjack anyway let's get into these 21 tips right now so let's start off with the browser api which you can't really separate from javascript unless you're writing no js now i've got a console window open because we're going to talk about the different types of storage that you have in the browser the first one is local storage this is an object database that your browser like chrome like the one i'm using uses and when you log that out you can see that you have basically just an object with keys and values this is a custom one i said this is just a random one you can get and set local storage with the get item and set item methods so if i'm getting out that my key value you can see my value as it printed up here and then i can set that to a new value and print it out like so and you can see it changed so no reason to over complicate this it's literally just an object you can use and it will persist across all your sessions so you can close your browser reopen it and it'll always be there unless you manually clear it or open a window in incognito mode so any so you can use your local storage but it is domain specific to read in right so one site can't read your local storage from another url however it's still not very secure because of cross-site scripting so you want to be careful using this if you're a developer almost the same but not exactly we have session storage and i say almost the same because it is the same it's also just an object under a different name but instead of persisting across all your sessions well it'll only be for one session as you might have been able to guess so whether this is the tab or the window this is more ephemeral which makes it a little more secure but it's still subject to the same issues as local storage and finally we have the cookie or cookies which you can access at document.cookie and you can see this is instead of an object just a long string and the way it's separated is key equals then the value and then semicolon and you can see these strings are just concatenated together so they're one after another in a single string instead of five megabytes you only have five kilobytes in the cookie and part of the reason for that is because the cookie gets sent back and forth to and from the server on every single request for that reason the cookie is often used to authenticate or identify a user and store different pieces of state in your app that the server's gonna need while we're still in the browser let's talk logging you know about console log of course but did you know about console error okay you definitely knew about that too but there's also console warn okay and this console table this last one is really useful for objects okay you definitely knew all that but did you know you can make custom colors for your logs and all you have to do is use the percentage c interpolation tag write a message then as the second argument just pass in a color uh colon color name here's another little logging trick and this one might be the most useful let's say you have a variable like favorite food and you want to log this variable out at a point in your application now you could just do it like this right but then there's no indicator what this actually is and if you have a bunch of different console logs you're not going to know where this one is coming from so what a lot of people do is they pass in a second argument and i say something like here look here but even better than that you can actually just make this an object with reverse destructuring that is put the curly brackets around it and it'll log out like that variable name and then the actual variable value there's literally no reason not to do it this way it's less typing and it's very clear what you're logging out so pretty much always do this that's what i would say since we're talking about object destructuring let's talk about another trick that helps you write better function definitions let's say i have a function called get full name and it looks a little something like this so i pass in first name not last name and middle name and then concatenate them together so let's define a few variables so we can pass them into our function okay most of the time when we're calling functions they're not actually near the function definition and they might even be in a different file in fact they usually are so let's just pretend we don't have this function definition in sight and we want to call the getfullname function and here we still have our variables but what order were our arguments in so right here we're lucky enough where uh it actually shows us that arguments come up but let's say we just forgot and we put first name middle name last name and then we got things in the wrong order right so we don't always get that little tool tip now an easy way to solve that is actually just to do this let me show you what i mean now we can just wrap this in curly brackets in the arguments and change our function definition and what this is doing is it'll destructure an object that we pass in so instead of passing in these properties in this order first name middle name last name we can do a reverse destructuring this will create an object with first name key value first name and then we print that out we can actually pass these in in any order so what this destructuring in the arguments allows you to do is pass in variables in any different order and it will always map them to the correct argument so you don't have to remember an arbitrary order like this speaking of objects though and arrays you got to be a little bit careful with them because you might know they get passed by reference not value that is if you pass an object in as an argument to a function well it's going to be the same object no matter how many levels deep you pass that for this reason using methods like array splice is kind of dangerous because it'll change your array in all the different places it is even if you include it in 10 different functions this can create some really terrible bugs that are hard to find trust me so when in doubt what you want to do is just slice your array with the slice keyword in a blank parentheses okay now this will just make you a copy of your given array that you can then use freely and it won't modify the original one another way to do this is actually to do dot dot array that is using the spread syntax to create a new array and this works exactly the same way as slice blank now doing this for objects is actually a little more complicated if you have a simple object like this we can just use object.assign pass in a blank object and then our old object and this will make a copy okay so this copies the same way as array slice but there's one major problem and that is it does not deep copy to show you how to fix this i'm going to switch over to my real code editor vs code okay i've got my code editor open for a more complex example we have a nested object here that is the outer user object and the inner details object so i can make a copy of that object with object assign so this does give me a new object which i can change the id onto two and you can see that did not change the original user object the id is the one you got to be careful though if you change the details object on either object it will change both so here's me changing it on the original user object and then when i log out the object copy well you'll see that new name changed on both the original and the copy now given that this can cause us some pretty big issues what we actually want is a deep copy or a deep clone unfortunately there's nothing built into javascript but there is in what i think is the best javascript library that i use in pretty much every single one of my projects and that library is called lowdash so you can install this with a script tag or with npm in our case let's just do npm then we can install lowdash now with that installed we can import clone deep like so with uh module import and then just replace object assign with clone deep okay and now we can see that actually fixed our problem change the original name to new name and our user copy has maintained our copy name now this library is amazing because it gives you functions that you know are going to be bug free so we're going to talk a little more about lodash aaron you might say are you really wasting multiple tricks on lowdash it's not even really javascript and the answer is yes because if you're not aware of them you can't use them and like i said i use this in pretty much all my projects it's also very hard to stop using these functions once you start all right let's talk about the next lodash function which every front-end developer should be familiar with i'll introduce it with an example so when you're typing in a form like this on google maybe maybe you want to search about the new machine learning algorithm well every time you type you can see that the auto suggestions change you can see all these results down here okay fill in as i change now every single time i press a key that's a new server request returning a list like this now that's great for google they can handle a ton of traffic but not every site can handle an every keystroke request okay so in practice what you have to end up doing is write what's called a debounce function that is wait to send the request until the person is done typing all right so i've written a fake function to take the user input string they type in the box and return a list of suggestions which would populate that little drop down menu now again i don't want this to be sending every time i do a keystroke because that could totally crash my server if i get high traffic so a really good way to do that is to wrap this function with debounce by lowdash so the way i do that is i just pass the entire function in and then i follow that with a amount of time in milliseconds that i want to wait before actually sending that request so let's just make it one second or 1000 milliseconds so just to give a basic example i can call get debounced four times in a row and it will only take the last request that i sent right so it's kind of preventing the server from being hit too often but also one takes the most recent string value only because it doesn't want to miss on the newer state right so this is a really good use case for d-bounce now you'll also notice another function up here called throttle which is the close relative of d-bounds and it actually has a very different use case which is more along the lines of rate limiting so let me just type an example out okay let's say you have a contact form on your website that the user is going to fill out and then it'll do something in your back end what you usually want to happen is you only want to receive that form once but let's say on the front end the user is clicking the submit button you know several different times before it actually has a chance to submit now throttle would be a great use case for this because it's kind of like d bounce but it only takes the first inside the time interval so if i write a get throttled function or rather post throttled and then i called that function three times well it's only gonna take the first one within this one second time interval throttle is better for things that you definitely want delivered one hundred percent so it'll take the first guaranteed but then after that there's a cool off period okay moving on we've got two more functions from lowdash get and set which help us deal with objects and they can also work on arrays but object is the main use case so right here i've got a nested object a user object with a profile object inside of it with a couple properties now every javascript developer is intimately familiar when this happens you try to go deep into an object use your profile full name right a double um property access here and the thing is like most of the time in real life this might not always be defined so having an empty object would be fine right but what if you got null here because maybe the api doesn't perform how you expect it to well you're going to get an error and basically your entire application is going to break when this happens which you don't want it's called a fatal error and it will basically just crash everything so how do you actually do something like this in a safer way well you could do if statements and check if user.profile is an object but you know that looks pretty terrible so a better possible way is to use what we have up here so to do what's called a safe get i can just use the get function so let's create a variable full name and let's use the get function on our user object then to reach into that object we go to the profile property just type it in as a string and then the sub property full name so it's kind of the same syntax as we have up here but it's just passed in as a string literal okay so now we're calling that let's just comment this out and let's just console.log full name out with our little destructure trick we used before okay phone number and jack that's great so that works normally but what if we change this to no okay so we actually get undefined but not an error so this is actually seems like a small thing but it's huge right you don't want your application to crash and another cool thing you can do is actually set a default value so let's say we always want this to be a string downstream of where this code is right i can put a default empty string value and i can guarantee this will be a string no matter what happens with this nested object and you can also go multiple layers deep with this so if you have a huge object you can go full name first name and that kind of thing happens more than you would think you have a really huge object especially in states in javascript frameworks so that is get what is set due well maybe you can already imagine it does a pretty similar thing where you can safely set nested properties if i set in my user object profile and then sorry second argument profile.fullname and then the third argument is just the value i want to set it to so we can do new name right and then if we log that out we can see that it basically safely creates my my deep object right and then if i set this to null you know nothing's going to go wrong so at the end of the day you can easily write code to do this yourself but putting it into one line that's actually just saving you a lot of mental overhead that you would otherwise have to write out and you can just do it by importing this simple get function and you might not believe it but that's actually just scratching the surface of what lodash has feel free to check out the library documentation it's really good docs but you know just another one i like to use for example is capitalized right so it's just really easy thing that's not built into javascript that you can use and you know it's just it's just useful because then you don't have to write your own you know it's always going to be good and it's always going to work so just simple stuff like this i love using as well all right so i already know someone's typing in the comments why would you just have an extra dependency for such simple things you know it's wasting bundle space this library takes space you're downloading it right but what you might not know is that's not necessarily true so if you just import everything from low dash like this yes you're gonna import the whole library which again is not that big but you know it's still maybe probably more than you need there's like 100 plus functions in there but what you might not know is if you're using a module bundler like let's just say webpack for react if you import one off functions like let's just say set at the bundle time a process called tree shaking that you don't even really have to know how it works is only going to import the single function from low dash the rest is just going to get rid of so it's shaking the rest of the things off my point for saying this is if you try to use lowdash at work you can literally just say you know this is what's happening we're not importing the whole library don't worry about it because in theory your bundler should take care of you and only import the code you need while we're up here in the import statements though not too many videos actually talk about this so maybe let's spend a little time and you can learn a new trick or two with these import statements now as we were just talking about we're importing a single function from lowdash that is being taken care of and tree shaking and what this set function between the curly brackets is is known as a module so what lowdash library is effectively doing is at some point in its code it's importing or rather exporting the function set like this so not export default just export and everything that gets exported this way gets turned into a module you have to destructure like this one more important thing about modules the name does matter so if i name it set in my lodash file then that's also have to import it like this okay okay so that's modules now at a different point in lowdash they're also exporting a default function and you can only do one of these per file now this is if you want to import the whole library which people often do by not using any destructuring so this will import the whole library it won't use tree shaking and you're gonna have the whole library in your bundle so let's get rid of this okay back to set now let's say i do want to name set something else that's exported from lodash now that's pretty easy to do you can just write as set as set lowdash and then it's exactly the same thing okay so you're just casting the name from set to whatever you want as the second argument after as okay here's another cool thing you can do you can actually mix and match default and modules in the same statement so if i wanted to do this i can import the default low dash and then just get set in its own variable and then i could do set low dash and i can import multiple ones i could do get as get low dash and i can actually make it pretty complex and this is semantically nice this would take me multiple lines uh before but you know now i don't have to do that so bottom line you can mix and match this as the defaults and the modules that's just kind of the anatomy of the import statement all right for the last couple i've just got a few that didn't fit into any category and these are actually kind of the dark arts of javascript not necessarily things you're supposed to do but i think it's really good to be aware of these just have them in your tool belt if you're able to use them and in fact i use them a lot but you know keep it on the dl that i told you anyway the first one is where you have a situation like this you have an if statement just a super simple conditional check followed by some simple logic inside the if block now this is the right way to do that do it right you have your brackets like this or even like this but this is actually four lines of your function already this is like a third of my entire page so what i actually think is if your team's okay with this and big if there no pun intended you can actually put this on one line and this is really useful for when you have multiple if statements maybe different flags you're checking in your function all up at the top and for me it's much easier to read because it's just if logged is is logged in return okay and then if not do this just two lines super simple and i think this actually improves readability personally all right here's another example and this is the darkest start of all i mean your co-workers actually may hate you if you do this but you know i'm just being honest i use this one a lot and you know it feels good to break the rules sometimes so anyway here's another example you have two flags and you are setting a variable based on the value of these flags so if paid then set the status to paid user otherwise if they're logged in but not paid you know you set status here and so on so what you have here is eight lines just to set a simple string and i just hate it when when stuff takes up this much space like i don't know what it is but i just want to tell you this so you're aware of it you can do this in one line and the way to do that is with a ternary operator more specifically a double ternary operator so let's build up to it if you only had one of these variables you would write it like this if they're paid is paid otherwise not paid you probably know about this ternary is actually in every programming language not just javascript what you might not know is instead of just doing one which would replace an if else you can do multiple so if paid is paid else is a lot are they logged in yes if so is logged in no not logged in so the hardest part about this is understanding what's happening but if you go through it one field at a time it's not that hard so you ask are they paid first answer is yes yes set it to this variable that goes in status no this is basically yes this is no that's how i think of it so no what do i do i'm starting over with a new one no so i'm asking are they logged in yes they're logged in no just return me this so this one takes a little bit of time to understand but i just wanted to bring it to your attention because look how clean this is this is like what you think of code before you coded you're like wow all these symbols something magic is happening is just one line is this the closest we're gonna get to poetry in javascript i don't know but i think it's nice other people you know people are already reading angry comments right now i can feel the energy but you know you can do this if your team lets you or if you want to piss them off all right guys that is all i've got for you today even if those tricks don't change your life being aware of them will help you out in the future if you run into these sort of situations where you need some of these tools if you like this video i do have another javascript tricks video so check that out on my channel and i just want to remind you go check out my cheat sheet if you haven't already it's totally free no reason not to get it and uh it's actually you know just simple syntax you wouldn't want to forget nothing as complicated as this video and also if you're not already aware i do have a javascript algorithms course too that i released a few months ago people are getting really good results with it it's fully animated and it's the best way to learn the common algorithms you need for interviews so go ahead and check that out too that link is also in the description 20 off with the code summer 20 wow i feel like i'm an advertisement in this video i hope you guys are all right with that you know i gotta make a little bit of money to get the new estonia digital nomad visa you need to make 3500 a month basically if you're not aware so anyway i will catch you guys soon i got some videos planned in the works stay tuned on my channel follow me on twitter and i will see you guys in the next one
Info
Channel: Aaron Jack
Views: 44,213
Rating: undefined out of 5
Keywords: programming, web development, javascript, react, learn programming, learn to code, coding, software development, become a software developer, javascript tricks, java script, learn javascript, how to learn javascript, js, node js, lodash, DOM, web dev
Id: 3vLCthTptY0
Channel Id: undefined
Length: 23min 7sec (1387 seconds)
Published: Thu Jul 30 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.