JavaScript ES6

The ES6 or ES2015 standard for JavaScript provided a number of enhancements. Many of those are now working in all modern browsers. Developers that use transpilers have been taking advantage of the new features for some time now. But maybe some of you have held back.

Well, unless you are not using a transpiler AND you are targeting older browsers, you can begin to take advantage of ES6 features. If you need to get up to speed with ES6, here are a few resources.

First, I find it helpful to check support for ES6 features for the browsers or environments I am targeting. You can do that by going to: The compatibility table is easy to use and it shows all the different environments that you may be targeting.

Second, the best reference source I have found for explaining all of the ES6 features is the book: ES6 & Beyond by Kyle Simpson. It is part of the You Don’t Know JS series. It is the most complete resource I have found.

Finally, at All Things JavaScript we have created a YouTube playlist of all our training videos on ES6 features. Each time we create a new training video on an ES6 feature, we will add it to the playlist. You can access the playlist here.

Caching the Length Property in a for Loop

As you know it is quite common to use a for loop to iterate over an array or an array like object. Array like objects include the arguments parameter on a function or a collection of HTML elements from the DOM. The for loop functions great for this kind of work. But here is a little tip you may want to try.

If you cache the length property, you can increase the speed of the loop. This way you can avoid reading the length during each iteration of the loop. This is especially important if you are iterating over a collection of HTML elements. Every time you access the length property, you are querying the DOM.

So here is the traditional approach, assuming arr is an array or an array like object:

for (let i = 0; i < arr.length; i++) {
//Code that modifies the array elements

With a simple change you can cache the length property, so you don’t look it up during each iteration of the loop. This example shows how you would cache the length property.

for (let i = 0, tot = arr.length; i < tot; i++) {
//Code that modifies the array elements

In the first part of the for loop definition, we define two variables. We set i to 0 and tot to the length. From that point on we compare with tot to check and see if the loop has reached the maximum number of elements in the array.

What do you think? Anything you would change?

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!