Good Coding Practices: Liberal Use of White Space

White space will make your code more readable. You may ask: “Why is that important? The JavaScript engine doesn’t need it and it just adds more size to my JavaScript file. So why do it?”

Well, the JavaScript engine will ignore it, so no issues there. If you are concerned about the size of your JavaScript files, then you should be minifying your code anyway, which will remove the white space for you. So really we can ignore both of those arguments. However, you can’t ignore yourself or others that may need to read your code.

One half of the battle of writing JavaScript code is accomplishing your task is the most efficient way you are able. The second half is making sure yourself and others can read and understand what you have done. You may say that I’m the only one that will ever look at this code. And that may be true. But I can pretty much guarantee that if you come back to the code in 6 months, you won’t remember why you did certain things. Therefore, we need to make the code as readable as possible.

White space seems like such a small thing, but most good coding practice are small things. They do add up though and can save time.

Notice the title of this article. It includes “liberal use of white space”. Don’t be stingy with white space. Separate parts of your code with returns. Use multiple lines to declare variables. Put spaces between operators and arguments in a function. Don’t try to be so clever with your JavaScript code, that you lose everyone else but your self.

Here are some common rules about the use of white space. Some have already been mentioned.

  • Separate distinct parts of your code with returns. This will act like chapters and paragraphs in written language.
  • Use multiple lines to declare variables. I discussed this in an earlier article. Not only is it easier to read all the variables, but if each variable is on its own line, you are able to add a comment describing that variable.
  • Place a space before and after an operator. This simply makes the expression easier to read.
  • Add spaces between arguments in a function.
  • Include spaces between items in an array.
  • Separate the three elements in a for loop (after the semicolon) with a space.
  • Add a space before the curly braces when declaring a function.

What are your thoughts on using white space in your code?

Using the Delete Command

The delete command has confused a lot of new JavaScript developers. The name can be a bit confusing, not because it doesn’t delete something, but because it is only used to delete object properties. It sounds like a general purpose command, but it isn’t.

If you want to remove a property from an object, you use delete. However, the confusion occurs when a new developer wants to delete a variable. He or she goes looking for a way to do it, finds the delete command, and assumes this should work. They then try it and wonder why it is not working.

JavaScript does not have a method for deleting variables. If you want to remove the value in a variable, set it to null. Undefined and null can be used to indicate nothingness with variables. Undefined should be reserved for the JavaScript engine (not set by the programmer) and indicates that a value has never been assigned. Null means that the program has intentionally set the variable to nothingness.

For more information on how to actually use delete, view this tutorial.

Common JavaScript Style Guide Sites

Perhaps you remember writing research papers in college, and you had to use a specific style guild such as MLA. Some people thrive on style guides, but I think most of us chafe at the need to use them. However, they are very useful to the reader. Information can be expected in a uniform manner. Such is true for coding style guides as well. In fact because of the variability in writing JavaScript, style guides may be just as important in JavaScript.

If you work at a large organization, most likely they already have a JavaScript coding style that you should stick with. However, if you are coding by yourself, or with a small group, or maybe you are the one responsible for coming up with that coding style guide, the following websites may be helpful.

I have gathered some of the more common sites that have something to say about coding styles in JavaScript.

  • W3Schools Style Guide. This site presents some basic style preferences for JavaScript coding.
  • Google JavaScript Style Guide. If you want to see what one of the power users of JavaScript recommends, refer to this site.
  • Mozilla Coding Style Guide. This guide doesn’t restrict itself to JavaScript, but there is a lot of information regarding JavaScript in it.
  • jQuery Style Guide. Use this site to view the conventions used by one of the most popular JavaScript libraries.
  • Douglas Crockford’s Style Guide. Douglas Crockford, the maker of JSLint, the sometimes maligned linting tool, has his own recommended style guide that you may want to take a look at.

With these five sites you can get a pretty good idea of the recommendations that are agreed upon, but also those preferred by different organizations. If you are interested in looking at style guides by other organizations, a simple google search on JavaScript style guides or coding conventions with provide some additional sites. Happy JavaScript styling.

Good Coding Practices: Declare Variables at the Top

Because of hoisting, JavaScript allows you to declare variables at anytime as long as they exist in the same scope. That can lead to sloppy code. I prefer the recommendation found in many JavaScript books, blogs and training: Declare all your variables with a single var statement at the top of your function.

This can provide several benefits:

  • You are able to view all the variables in one place.
  • It helps you remember to declare variables. If you do not declare a variable and use it (which is allowed in JavaScript), you might inadvertently create a global variable.
  • It can result in less code because you are not repeating var statement for each variable.

I prefer to place each variable on its own line. I feel this makes it much more readable. Here is an example declaration statement that you might see in my code.

var obj = {},
    num = 0,
    options = [],

I also prefer to initialize my variables when I declare them. JavaScript doesn’t have a mechanism for typing variables, but I use initialization as a means to indicate to myself, or anyone else that views my code, what the type should be. One of the times I may not initialize is if I want to be able to check for undefined to see if the variable has been set yet. The name variable in the example above is not assigned a value for this reason.

Just a couple of hints for good coding practice. How do you feel about a single line variable statement at the top of your functions.

The Most Unique Book on JavaScript

When I first read the title of this book, it immediately caught my attention. You have to admit If Hemingway Wrote JavaScript by Angus Croll is an intriguing title. I immediately wanted to find out what the book was about. I have not finished reading it yet, but one thing I can say with a great amount of certainty is that this is the most unique book on JavaScript I have encountered.

The premise of the book is that 25 famous authors have been given an assignment to solve a problem in JavaScript. Not every author is given the same assignment, but enough authors have each assignment that you get to see multiple approaches.

For each author there is first a discussion of their writing style, and then the solution to the assignment is presented. The assignment is completed in a way that reflects the style of the author. I have found it a very interesting read. Not only because of the different solutions to the assignments but the discussion about the authors is also intriguing.

So what does this book have to say about JavaScript? In his introduction, Angus Croll calls JavaScript the “most literary of computer languages”. What exactly does he mean by that? Well, here is my take.

Many languages are like a paint-by-number set. There is a certain way to accomplish the task. You can use different numbers if you choose to. And you can paint outside the lines and things may end up fine. But many times if you don’t follow the method used by so many before you, you end up with an inferior product.

With JavaScript, you are given the entire palette and a blank canvas. Yes it is possible you will end up with something that is a complete mess, or looks very much like a child created it. But you can also end up with something that is beautiful and unique. Even the same picture can be painted in many different ways.This, I believe, is one of the messages of If Hemingway Wrote JavaScript.

I love this statement from the introduction.

Natural language has no dominant paradigm, and neither does JavaScript. Developers can select from a grab bag of approaches–procedural, functional, and object-oriented–and blend them as appropriate. Most ideas can be expressed in multiple ways, and many JavaScript programmers can be identified by their distinct coding style.

If you have any interest in literature and JavaScript, pick up a copy. You won’t be disappointed.

JavaScript Equality: == or === ?

JavaScript uses two different operators for equality (== or ===), and two different operators for inequality (!= or !==). So which should you use?

Well the simple and quick answer is to always you === for equality and !== for inequality. That is the quick answer, but it is better to understand why that is best. The difference has to do with coercion. Coercion happens when one value is forced to become a different value. For example, the boolean true can be forced to become a number, which would be 1.

The == and != uses coercion, if it can, before it compares the values. This can create some strange results in certain situations. We show a few of these in the tutorial.

As I was writing this, I was curious about the definition of coercion outside of JavaScript. The standard definition is very similar to how it is used in JavaScript: the act of compelling by force of authority. So in JavaScript == and != acts by compelling by force of authority before it determines if the values are equal.

In this tutorial we explain why you almost always want to use === and !== because of coercion. Happy viewing!

Floating Point Numbers in JavaScript

When JavaScript was first created, a single data type for numbers was established. Integers and floating point numbers are combined in the same data type. This is not true for most programming languages.

The simplicity of the single data type is one element of JavaScript that helps make it is easy to learn. Perhaps that was one of the motivating factors. It also can lead to better performance. However, there is a tradeoff. JavaScript can produce errors, in certain situations, when doing arithmetic using decimal numbers. Here is an example:

var i = 0.1,
j = 0.2;
console.log(i * j);     //0.020000000000000004

Well, that is weird! The reason behind this anomaly has to do with a single data type for numbers. Accuracy has been exchanged for performance and ease of use. So what is to be done when you need to perform arithmetic operations on decimal numbers?

There are several solutions out there. Some truncate decimal places to the number of positions they know should exist. Others, and this is my preferred solution, work only with integers. So when it is necessary, such as when you are computing money values, you can do something like the following:

var i = 0.1,
j = 0.2;
i = i * 10;   //Shorthand code: i*=10
j = j * 10;   //Shorthand code: j*=10
console.log((i * j)/100);     //0.02

Mathematical Note: You must divide by 100 because you multiplied two separate numbers by 10 and then multiplied them together (10 * 10 = 100).

Don’t you love it when JavaScript throws these little quirks at you?

Getting a Grasp on Scope

I think I probably dabbled with JavaScript for several years before I thought seriously about scope. It led to some mistakes in my code, which I could have easily prevented if I had understood how scope works in JavaScript. That beginning was some 15 years ago, and as I now look back on it from the perspective of a teacher of JavaScript, I have come to feel that understanding scope is very important. And not only just understanding it, but understanding it early in the process of learning JavaScript.

Scope can be defined asa set of rules for how you can store and retrieve values. To shed more light on the topic, I address scope in the following tutorial.

If you feel like you are in the same position I was, and don’t have a clear grasp of scope, or if you just want a refresher, take a look at this video. Then if you still have questions or you want to add to the information presented, comment below.

Enjoy the video!

Converting Strings to Numbers


I frequently find myself needing to convert a string to a number. It may be a date I have received where I want to convert the month to a number so I can increment it (commonly happens when using the Date object). Or it may simply be a number I received as input, which comes in as a string.

A short-hand way to convert a number to a string is using the + operator as shown here.

var month = “06”;
month = +month;
console.log(typeof(month));     //number

Another method for converting a string to a number is using the Number() function. Here is the same code using that funciton instead.

var month = “06”;
month = Number(month);
console.log(typeof(month));     //number

There is one more function that will convert a string to a number and until recently I was not aware of the advantage it provides. If you have a string that contains a number but also other string elements that cannot convert to a number, the previous techniques shown will fail with NaN (not a number).

var month = “06 month”;
month = Number(month);
console.log(typeof(month));    //number
console.log(month);    //NaN

Initially, just checking the typeof may make you think the conversion worked. It returns a number as the type. However, the reason for that is that if you check typeof for NaN, it returns number. As soon as you try to log the variable, you receive NaN.

The parseInt() function allows you to parse the number (instead of converting it). Therefore, you can pull the number element out of the string without receiving NaN.

The parseInt() function takes two parameters: the string to parse and the radix. Normally you will want to put 10 as the radix parameter in order to convert the number to base-10. Here is the same code using the parseInt() function.

var month = “06 month”;
month = parseInt(month, 10);
console.log(typeof(month));    //number
console.log(month);    //6

The first two methods for converting a number are faster as they do not need to parse the string, simply convert it. But as you can see in certain situations parseInt offers a distinct advantage.

Doing Away with Global Variables

If you have been around the JavaScript world long enough, you have heard that you should not use global variables. The problem with that little statement is that any JavaScript program starts in the global space, so it is very convenient and easy to create global variables. Telling you not use global variables solves only half the problem. You also need to know how to avoid using them.

The statement would be more appropriate if phrased this way:

You should avoid using global variables in JavaScript and here is how.

So there are two possible tutorials that could come out of that statement: Why global variables are bad and how to avoid them. So guess what? That is right. We are including two separate tutorials in this article.

First, if you are not sure why global variables are bad, watch this tutorial.

Now that you know what is wrong with global variables, it is important to understand patterns you can employ in order to prevent using unnecessary global variables.

It can be easy to fall into the trap of using global variables, because they can help you quickly solve problems in certain situations. Some globals are necessary, but the choice to use them should not be because you don’t know any other way.

In the second tutorial we provide three techniques you can employ for preventing the use of global variables. Watch the video and begin incorporating these techniques in your own coding.