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

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.

My Favorite Book on JavaScript

My first degree from college was a BA in English. The only reason I mention this is to point out that I love to read and that I can sometimes be overly critical of certain books. Because I love to read, I have purchased numerous books on JavaScript.

I’m very analytical about the books I purchase. I won’t buy just any book on JavaScript. But despite that, as I take a quick look at my library, I have over a dozen books just on JavaScript. That doesn’t even include the books on various frameworks and libraries.

So which book is my favorite? Without any further ado, here it is:

This book serves two purposes for me. It acts as a reference which I use several times a week for that purpose. The index is well done, which is necessary for a reference book. Second, it also works quite well as an instructional tool. If there is something in JavaScript I am not familiar with, I can always turn to this book for an explanation of how it works or how to use it.

The book is divided into two main parts: Core JavaScript and Client-Side JavaScript. I like this approach. It sends the message that JavaScript is not just for the browser. However, there are several important nuances when using JavaScript in the browser that are covered thoroughly in the section on Client-Side JavaScript.

This book is nothing if not thorough. I can always find what I am looking for. Want to get an intro to Node or jQuery? It is in there. Want to find out about modules. It is in there. Hoping to understand closures better? It is in there. Or maybe you simply want to know the primitive values in JavaScript. It is all in there. From the simple to the complex, this book has something to say about each topic.

This book is probably not the most exciting book I have on JavaScript. Nor is it the most interesting to read. It is probably not the book that has expanded my thinking the most about JavaScript. But it is the book I always turn to. It is the only book I have purchased twice. I originally bought the 4th edition, and then a couple years back upgraded to the 6th edition.

If you don’t have this book, you may want to add it to your library or use it to start your JavaScript library: JavaScript: The Definitive Guide.

The Difference Between let and var

JavaScript traditionally has had two types of scope: global scope and function scope. Global scope allows you to access variables from anywhere in the program. But it can be dangerous in large programs. Your global scope can become messy and you risk accidentally overwriting values that you did not intend to overwrite.

Function scope is the preferred scope method to use and there are a number of JavaScript patterns to help avoid defining things in the global scope and to take advantage of functional scope.

With ES6/ES2015 we now have the ability to define block scope: restricting the scope of a variable to a block of code. This is done with the let keyword. Its most common application seems to be in for loops, though there are numerous other applications. The pure nature of the counter variable in a for loop, lends itself to block scope.

for (let i = 0; i < 10; i++) {
console.log(i);
}

The variable i is only needed during the existence of the for loop, that particular block of code. Therefore, why define it with var and extend its scope.

In this tutorial we explore the difference between var and let. Enjoy watching and happy coding!

Trying Out Thimble by Mozilla

A couple of weeks ago I first learned about Thimble while reading one of the several newsletters I receive each week. Quoting directly from the Thimble web site, it is an online code editor that makes it easy to create and publish your own web pages while learning HTML, CSS & JavaScript.

The tool seems to be designed for younger kids, but it looks helpful to anyone that is just starting in web development and needs to learn HTML, CSS. You can view a quick introduction video, create an account and get started by visiting the Thimble web site.

Here are a list of features that Thimble offers:

  • You can start a new web page by copying an existing web page. This is called remixing in Thimble. This is a great option for beginners. You get to see the HTML, CSS and JavaScript, make tweaks and see how those tweaks change the site. If you choose to, you can also start a web page from scratch.
  • The Thimble editor consists of three areas: a file manager, a code editor and a preview pane. This allows for ultimate flexibility as you try out different things. You can add additional pages via the file manager. You can then build or edit pages using the code editor. When you make changes in the code editor, those changes automatically show up in the preview pane.
  • Assistance features are provided to help you learn. For example, you can highlight a CSS attribute or an HTML tag, press Alt+k and the code editor will display a description of the tag or CSS attribute. I tried to do this with JavaScript reserved words, but it didn’t seem to work.
  • Some projects have a tutorial file that walk you through a short tutorial different techniques for that site.
  • Once you have created a site, you can publish it to the web. You are provided with a URL that you can share with others. This is a great option for younger learners.

Go ahead and give Thimble a try and see if it is the type of tool that could aid in your web development learning.

Demystifying JavaScript Closure

Closure seems to be one of those concepts in JavaScript that can be a bit mysterious. However, the funny thing about closure is that many JavaScript developers take advantage of it before they understand what it really is. So is it necessary to understand closure?

I think it is. If you understand the concept, then you are able to take advantage of what it offers. You will find more programming situations where you can apply closure.

Here is my favorite definition of closure. This comes from one of Kyle Simpson’s books:

You Don’t Know JS: Scope & Closures

Closure is when a function is able to remember and access its lexical scope even when that function is executing outside its lexical scope.

Now the only problem with this definition is that you need to understand lexical scope. Think of it this way. When you write a program, you place a function inside a particular scope based upon where you enter that function. That is the function’s lexical scope.

Keep this in mind as you take a look at this tutorial on closure. It will explain it, present several examples and illustrate the power of closure. Happy viewing!

Some Interesting Data from the State of JavaScript Survey

The State of JavaScript survey has recently been released and shows some interesting data points. I hope this is the first iteration of many to come for this survey as I found some interesting information. You can access the survey and sign up to be included in next years survey by going to stateofjs.com.

Here are some of the data points that I found most interesting.

In the front-end frameworks section, I was amazed at the popularity and interest in React. I first looked at React a few weeks ago and was quite impressed myself. It seems that there are many others in the JavaScript world that are feeling the same way. Time to get to know React better.

Another surprise for me was the build tools category. Though not the top performer, Gulp did very well. I personally prefer Gulp and hence the interest. I always thought of it as a poor runner-up to Grunt, but it seems to fair much better than that.

The Opinions section was also quite interesting. Many agree that the JavaScript world is way to complex and changing too fast. However, what I found as an interesting twist is that many are happy with the direction JavaScript is headed.

Take a look at the report as there are many more categories than those mentioned here. I’m sure you will find some surprising results as well.

Thoughts on How to Learn JavaScript

The JavaScript landscape can be very confusing. It seems every week there is a new framework or library being released. It can be very difficult keeping up on the latest.

So if you are just starting your journey down the JavaScript highway, you may be asking yourself which direction do I take? How fast should I travel? What automobile should I drive?

In this first tutorial published at All Things JavaScript, we address the question of how to go about learning JavaScript. I believe you will find the guidance helpful as you plan your trip.

For additional tutorials you can subscribe to the YouTube channel here.