Table of Contents
Do you want to know some cool JavaScript tips, tricks and gems? Then, you are on the right place! In this second part of JavaScript tips, you will get what do you want. For example, you will learn about two gems from ES6. You will also learn why var keyword can be sometimes dangerous. Then, we will discuss style guides, their benefits and how to implement them. After that, we will talk a bit about JavaScript in external files and also about using CDNs. Lastly, you will learn about two ways to measure performance of you JavaScript code. Without further ado, let’s begin.
No.1-6 are in part 1.
No.6: Start using let and const
Let’s start this second part of JavaScript tips with changing one of the fundamental practices. Unless you started coding in JavaScript recently, you have been probably using var keyword. This was, and probably is, the usual way you declared new variables in JavaScript. With the introduction of ES6, it is maybe a good time to change this practice. ES6 introduced a lot of new things that expanded syntax of JavaScript. With this, ES6 also introduced some new practices.
The problem(s) with var and scope
Until now, we could declare new variables only with var keyword. Sure, you could omit the var keyword if you want. The only problem is that it would result on variable declared in global scope. If you are declaring variable in global scope, then there is no difference. Declaring new variables using var keyword has a couple of downsides. I already mentioned the first problem with using var keyword. When you declare variable with var, it is either in function or global scope. It depends on whether you declare it inside or outside any function.
Example:
// Variable defined in global scope var exampleOne = ‘Donald’; function variableFactory() { // Variable declared in local scope // of the function var exampleTwo = ‘Duck’; console.log(‘Before the loop: ‘ + i); // ‘undefined’ for (var i = 0, j = 10; i< j; i++) { // do something } console.log(‘After the loop: ‘ + i); // 10 } variableFactory(); console.log(exampleOne);// ‘Donald’ console.log(exampleTwo); // ReferenceError: exampleTwo is not defined
As you can see on the example above, variables declared with var keyword work quite well. Yet, there are some situations when this is no longer the truth. In these cases, variables you declared with var keyword will not work as you might want. Take a look at the example above and try to find two lines showing a bit weird behavior. Okay, it is right before and right after the for loop. In both cases, the variable i exists outside the scope of the loop and it is visible.
Another problem with var and hoisting
The second problem with declaring variables using var keyword is something called hoisting. This basically means that you can declare new variable after you use it. In other words, yes variable can be used before you even declared it. You could already see this behavior in action in the previous example. If you have no idea what am I talking about, look for a clue at the line before the for loop. Okay, let’s take a look at this part of the previous code example.
Example:
function variableFactory() { console.log(‘Before the loop: ‘ + i); // ‘Undefined’ –this is where hoisting happens for (var i = 0, j = 10; i< j; i++) { // do something } }
Example:
// Let’s try to log non-existing variable console.log(testVariable); // ‘Undefined’ // And then let’s create it var testVariable = 'Surprise!'; console.log(shadyVariable); // ‘Surprise!’
If you try to log the variable i you will get a simple message – “undefined”. The problem is that you should get something like “ReferenceError: i is not defined”. That would mean that variable i does not exist. This is something we discussed in the first part of JavaScript tips. If some variable is undefined, it doesn’t necessarily mean it doesn’t exist. This has two meanings. First, you haven’t declared the variable yet. In other words, it doesn’t exist. Second, the variable has been declared, but at this moment it has no value. How can some variable exist if we didn’t declare it?
Understanding how hoisting works
In order to answer this question, we have to make a detour from these JavaScript tips. I will have to tell you something about hoisting. It may seem like just another glitch of JavaScript. The reality is that this is default behavior of JavaScript. It means that it will move all declarations in the code to the top of the current scope. If you declare some variable inside function, JavaScript will move that variable on top of the function body. Let’s apply this theory on previous snippet.
Example:
function variableFactory() { var i; // declare i without value console.log(‘Before the loop: ‘ + i); // ‘Undefined’ - this is where hoisting happens // Assign new value to i for (i = 0, j = 10; i< j; i++) { // do something } }
Example:
// JavaScript will declare empty testVariable var testVariable; // Let’s try to log non-existing variable console.log(testVariable); // JavaScript will assign new value to testVariable testVariable = 'Surprise!'; console.log(shadyVariable); // Surprise!
If you didn’t know about hoisting, don’t worry. This is one of those shadow areas developers are not talking about as often. In a fact, many developers don’t know about it as well. I learned about it just recently. The problem is that when you don’t know about or understand hoisting, it can cause you some troubles. Due to hoisting, your code may not work as you think it would.
Fortunately, there is quite simple way to avoid any bugs related to hoisting. Make sure to declare all your variables at the beginning. This is one of the things that CoffeeScript does automatically. However, this is about JavaScript tips, right? If you use ‘use strict’ directive, JavaScript will not allow you to use any variable before you declare it.
Introducing ES6, let and const
Let’s now switch our focus on ES6. When you write your JavaScript code in ES6 syntax, you can use two new ways to declare variables. You can use either let or const keywords, or the good old var. Let’s talk about the const keyword first. Any variable you declare using const is read-only. This means that once you declare the variable, you can’t overwrite its value. Try it, you will get an error.
Example:
const x = 3; console.log(x); // 3 x = 4; // TypeError: Assignment to constant variable.
Let’s now take a look at the second newcomer that is let keyword. What is the difference between let and var? The difference is in the scope. When you declare variable with let, you declare it in block scope. This means that your variable will exist only in the scope of current block of code. For example, if you declare some variable with let in global scope it will exist in global scope. This variable will be visible everywhere. If you declare the same variable again with let, but in some function, it will be visible only in that function. The same is also true for loops.
Example:
let globalVariable = ‘Variable in global scope.’; function scopeChanger() { console.log(globalVariable); // ‘Variable in global scope.’ let localVariable = ‘Variable in block scope.’; // ‘Variable in block scope.’ console.log(localVariable); // ‘Variable in global scope.’ for (let i = 0, j = 5; i<j; i++) { // do something } console.log(i); // ReferenceError: i is not defined } scopeChanger(); console.log(globalVariable); // ‘Variable in global scope.’ console.log(localVariable); // ReferenceError: localVariable is not defined
When to use let, const or var
As you can see on the example above, let is really not visible outside the scope it was defined at. This is why you will get an error when you try to access i variable outside the for loop. To close this item on our JavaScript tips list let’s talk about when to use what. I think that the best way to decide is by asking yourself this simple question. Will I need to reassign this variable? If your answer is clear “No”, than would suggest that you use const. This will make it clear that this value shouldn’t be changed in the future. Well, with const it will not be.
On the other hand, what if your answer is “Yes”? Then, I would suggest that you use let. At this moment, I write the majority of JavaScript in ES6 and I don’t use var. Now, any time I want to use var to declare new variable I will use let instead. So, as a rule of thumb, use const for variables that shouldn’t be reassigned and let for variables that may be. And, what about var? Well, slowly stop using it. If you are writing JavaScript in ES6, as you should, don’t use it. If you are not, take this list of JavaScript tips to heart and start today.
No.7: Use style guide
Let’s now take this article about JavaScript tips on more theoretical level. It is time to talk about style of your code. What I want to suggest is that you create and start using style guide. Why? When you use styles guides, you can document your coding conventions. Your style guide can contain topics such as code indentation, spacing and linting. You can also document conventions for variable and file names. We should also not forget documenting proper use of comments, semicolons and declaring variables.
This all may seem like a lot of unnecessary work. What are some benefits of doing all that? There are two main benefits in using a style guide. First, your code will be easier to read. Style guide will force you to use consistent style. This will result in much better readability of your code. In other words, style guide will provide you with guidelines for writing clearer code. Second, when you create naming conventions naming files and variables will get easier.
As a result, you will have to think about and make smaller number of choices. This will allow you to focus on what is more important. You will be able to concentrate your mental capacities on code’s logic or design. I know, this is article about JavaScript tips. However, you can create a style guide for yourself also if you are a designer. For example, you can create naming conventions for layers in Photoshop or Sketch. You can do the same for your project files, folders and moodboards.
Create it or adopt it
Let’s say you like this idea about style guides. The question is, is it better to create your own or adopt some already existing one? In the beginning, I think that it is better to adopt existing style guide. There are a lot of topics style guide has to cover. You also have to follow all conventions defined there. If you break some convention here and there, the style guide will lose its meaning. Adopting a style guide will also help you avoid one common problem. This problem is your inner chatter. These are your thoughts based on your opinions and preferences about the what’s best.
One think to keep in mind is that developing style guide will take a lot of time. You may not have the necessary amount of time at this moment. Also, you may not know where to start. For all these reasons I would suggest that you start by looking at some well-known companies and projects. For example, there is a style guide developed by Google. You can also try out style guide created by Airbnb. Let’s also don’t forget about JavaScript style guide used by jQuery and MDN. As you can see, there is plenty of examples. Either adopt one or use them as inspiration for your own.
Style guides, experience and customization
Let’s assume you decided to adopt some existing style guide. You also found one style guide you like. Yet, there are some parts you just can’t stand. There are three possible options you can choose from. First, you can swallow that bitter pill and follow the style guide. Second, you can customize the style guide to suit your preferences and opinions. Third, you can drop that style guide completely and choose different one. Which options is better?
Let me ask you a couple of questions. How much do you dislike that convention? Can you get over it? How many experiences do you have? How important is the convention? There will be some conventions you can get over without any effort. Also, not all conventions are equally important. Some conventions are purely for better readability and has no effect on performance. Others, will may have the opposite effect. These conventions can have significant effect on performance. Yet, they may have close to zero effect on code readability.
Anyway, I think that the most important question is the one focused on your experience. Let’s say that you know that some guideline may not be the best option. Let’s say that you know about something better. Then, I would suggest that you follow your intuition and experience. Chances are that your expertise is deep enough. I think you can manage customizing the style guide to your personal tastes. If your expertise is shallow, I would suggest that you follow the style guide.
Style guides are usually created by skilled professionals with best practices in mind. If you don’t have sufficient knowledge or experience you should at least try to follow it for a period of time. Or, discuss your opinions with someone more experienced than yourself. See, if you are right.
Should you stick to style guide or not
Like best practices and quality JavaScript tips, style guides should be followed consistently. This is, in the end, why you want to use a style guide. You want to spend less time thinking about less productive topics. Your client will probably doesn’t care about what indentation do you use. She will also probably doesn’t care about what kind of quotes do you use. In the majority of cases, she will not even notice these subtle details. I don’t want to hurt your feelings, but this is the truth.
However, your client will notice if the work takes longer than it should. What do I mean? She will notice if you miss a couple of deadlines because you can’t decide on what type of quotes to use. And, she will not be happy to pay you more to cover this “thinking” time. For this reason, and couple others, choose one style guide and stick to it. Do the same if you decide to create your own. Specify all conventions, write them down and follow them meticulously.
What if you realize that some convention is not working as it should? What if you find something better? Then, you will have to decide. Don’t get me wrong, but there is no excuse for using one coding style here and another one there. Let’s say that you found some HTML, CSS, Sass or JavaScript tips related to coding style you like. Then, experiment with them outside your normal work. If you find these HTML, CSS, Sass or JavaScript tips useful, update your style guide. If you don’t want to implement these tips, don’t use them. Instead, stick to your own style guide.
Style guides and teams
There is one last topic we should discuss to before we move to another item on our list of JavaScript tips. What if you are working in team? First, when you work with more people, style guide will be even more useful. In a team, the importance of creating consistent and maintainable code is much higher. It can be also much harder to achieve. The more people are in the team the more diverse the coding style will be. You have to find compromise between different opinions.
Otherwise, the danger is that some members of your team may decide to ignore the style guide. Then, the style guide will lose any meaning. The truth is what styling conventions you choose doesn’t matter very much. What does matter is that everyone follows these conventions consistently. That’s why it is so important to discuss every angle of the style guide with all members of your team. You need to listen to all their opinions and ideas.
When you decide to implement a style guide, get everyone in one room and give everyone enough space to speak. Sometimes, it can be useful to let everyone write down his ideas first. This may help you get even the most shy people talking. When you allow them share their ideas anonymously will help reduce their anxiety. Otherwise, you may not get these people to voice their ideas and opinions. When you get all ideas, it’s important to ask a lot of “why” questions.
You shouldn’t accept or agree on any convention just because there is no other option. Instead, dig deep and find why implementing this convention is a good idea. If you adopt some style guide, do the same. Question all conventions and make sure everyone is on board. If not, change that convention.
No.8: Put scripts into external files
The last but not least of the JavaScript tips on the list is about putting scripts into external files. There are at least two reasons for doing this. First, when you put all scripts into one file, it will make your JavaScript more manageable. When you will need to change something, you will know where to look. The only thing you will need is to find the right line. It is simple as that. The second reason to put scripts into external files is to take advantage of caching.
Let’s say that you have some scripts written in HTML code. Then, browser will load these scripts every time user will change the page or refresh it. This is something that is not necessarily. On the other hand, what will happen when you put the scripts into external files? Browser will download these files and store them in the cache. This is something like browser’s local storage. In this storage, your browser keeps specific informations and objects downloaded from the Internet. If your browser download these files, it will not download them again.
The exception is when these files are deleted or they expired. The result is that the website needs less time to load – it has to load fewer resources. For example, let’s say you are using the latest version of jQuery on your website provided by some CDN. When someone visits your website and her browser has jQuery in cache, it will not download it again from your website. This is also one of the reasons why using CDNs may be a good idea.
The advantage of CDN
When I think about it, this could be another item on this list of JavaScript tips. Aside from pre-caching files such as stylesheets and scripts, what else can CDNs do for you? When you use CDN to serve some of your content you reduce the number of requests on our server. This may not look like a big deal, but it can be. Browsers limit the number of concurrent connections to a single domain. This number of active connections is usually somewhere around four. Every connection stands for downloading one file from your server.
What this means in plain English? Browsers will download up to four files at the same time. If your website requires more than four files, the rest will be blocked. Browser will download the fifth file only when one of the previous files has been fully retrieved. What will happen if you “outsource” some of this content to CDN? Browsers limit the number of connections per domain. However, files on CDN are hosted on a different domain. As a result, one CDN allows your browser to download another four files at the same time.
We can take this simple example a little bit further. Let’s say your website requires twelve files in total. Without CDN, browser will theoretically download the first four files. Then, it will download the fifth, sixth, seventh and so on. Depending on the size of the files, this can take significant amount of time. In the world of Internet, every second counts. You don’t want to make your users wait. You can bypass this. Divide the files into three chunks of four and use different CDNs. One chunk will be downloaded from your domain, one from first CDN and one from second. In this way, the limit basically doesn’t exist.
No.9: Measure performance of JavaScript blocks
The last of the JavaScript tips we are going to discuss will be about performance. As I mentioned above, performance matters a lot. This is not true only for the Internet. We want everything to be as fast as possible. Well, almost everything (spoiler: not for kids). Unfortunately, we can’t know for sure how fast something is, or not, unless we measure it. Nowadays, one of the heaviest items in performance budget is JavaScript. This is why I want to dedicate this final section of JavaScript tips to performance in JavaScript.
Two methods to measure performance
There are a couple of ways in which you can measure JavaScript performance. For example, you can use various browser extensions or benchmark tests. However, there is also one much simpler solution. What’s more, this solution is built-in right in JavaScript. I am talking about two specific methods – console.time() and console.timeEnd(). These methods are available in all modern browsers, including even IE 11. How can you use these two methods?
The first step is writing console.time() in the beginning of the block of code you want to measure. The second step is writing console.timeEnd() after that block of code. Then, these two stamps will measure the time it takes to execute whatever code is between them. For example, let’s say you want to measure how long it takes to execute certain function. In that case, you will put this function between the console.time() and console.timeEnd() methods.
Example:
// First stamp to mark beginning of the testing block console.time("Array initialize"); // Function to test function test() { // Create an array with 2000 items let testingArray = new Array(2000); // Populate the array with objects for (let i = 0, j = testingArray.length; i < j; i++) { testingArray[i] = new Object(); } } // Initialize test function test(); // Second stamp to mark the end of the testing block console.timeEnd("Array initialize"); // Array initialize: 9.864ms
Another way to measure performance
Aside from console.time() and console.timeEnd() methods there is another method you can use as well. This method is performance.now(). This method returns value that is measured in milliseconds and it is accurate to one thousandth of a millisecond. Unlike the previous two methods, this returns one value. This means that you will have to assign this method to one variable on the beginning and on the end. Then, you will have to subtract the second from the first. The result will be the time it takes to execute the code.
Example:
// First stamp to mark beginning of the testing block let timeStart = performance.now(); // Function we want test function test() { // Create an array with 2000 items let testingArray = new Array(2000); // Populate the array with objects for (let i = 0, j = testingArray.length; i < j; i++) { testingArray[i] = new Object(); } } // Initialize test function test(); // Second stamp to mark the end of the testing block let timeEnd = performance.now(); console.log(timeEnd – timeStart); // 7.265000000000001
Closing thoughts on JavaScript tips
Congrats, you just finished this mini series about JavaScript tips! I hope you found these nine JavaScript tips useful. Let’s quickly recap what we discussed today. The first tip was about starting to use let and const from ES6. These new ways to declare variables can help you solve potential problems with scope and also hoisting. The second tip was about implementing a style guide. This will help you make your code more consistent. It will also let you focus on more important things.
The third tip we discussed was about putting JavaScript code into external files. This way you can take advantage of caching. We also talked about connection limits and benefits of using CDNs. Lastly, we took a look at two ways in which you can measure performance of your code. There is also third way, using Date object, but the two we discussed are better. Anyway, I’m looking forward to seeing you here again on Monday. Until then, have a great time!
If you liked this article, please subscribe so you don't miss any future post.
If you'd like to support me and this blog, you can become a patron, or you can buy me a coffee 🙂