Top JavaScript Libraries 2018

Introduction

JavaScript libraries allow us to add new features to our applications and prevent us from having to duplicate code that other people have already created. Some of the most useful JavaScript libraries have been around for many years. However, I’m going to avoid covering those. Instead, we’ll be covering some of the JavaScript libraries that are new and trending. These libraries include React, FusionCharts, math. js, Lodash, and CreateJS. This is by no means a complete list of all the JavaScript libraries that are worth learning. Entire books could be written on each one of these JavaScript libraries. This article will only scratch the surface of each of them. Two of these libraries (Lodash and CreateJS) were also covered in an article that I wrote last year, titled Top JavaScript Libraries for 2017. I originally intended not to recycle any materials on any specific libraries, but I like Lodash and CreateJS so much that I decided to also include them in this year’s edition. The other three libraries in the 2017 version (Chart.js, LeafletJS, and Three.js) are also worth learning, since one year later they are still awesome. The 2017 version of this article is located here:

https://blog.learntoprogram.tv/top-JavaScript-libraries-for-2017/

Differences between JavaScript libraries and JavaScript frameworks

Before I begin covering these various libraries, it is important to understand the difference between a library and a framework. It’s common for people to confuse these two concepts (some people even believe that libraries and frameworks are the same thing). The explanation of the difference is often confusing. It’s also possible for something to be just a library, just a framework, or both. This makes the issue even more confusing. A JavaScript library consists of source code which contains functions and objects. By including the JavaScript library in your application, you can use these functions and/ or objects without having to create them from scratch on your own. It’s a way for us to avoid “re-inventing the wheel” by allowing us to take advantage of useful code that has already been written by other programmers.

On the other hand, a JavaScript framework will usually affect the general structure of your application. Frameworks usually always contain one or more libraries. One main difference between them is that you may use a library in any way that suits you, while a framework usually specifies some guidelines regarding how it should be used. A framework will often have rules that your code (and its general structure) must abide by to “work within its framework”. Although I won’t be explaining “Inversion of Control” (IoC), it’s a concept that is crucial to completely understanding the difference. It’s beyond the scope of this article. Further research upon this subject is required to thoroughly understand the difference between frameworks and libraries. To make a long story short, when you use a library, your code makes calls to various functions or objects within the library. However, when using a framework, the framework makes calls to your code (this is often referred to as “don’t call us, we’ll call you”).

The idea of a framework is a bit more difficult to grasp than the idea of a library. Therefore, if the idea of a framework doesn’t make sense to you, don’t worry about it too much for now. I simply want to make it clear that there is a difference, even though the terms are often used interchangeably. I’m aware that this brief discussion may have opened up a can of worms within your mind, but this type of mental discomfort often plants the seeds of profound realizations. With that being said, let’s move on and begin playing with JavaScript libraries.

React

Download https://reactjs.org

React is somewhere in between the definition of a library and a framework. I won’t dwell on this matter though, since a quick Google search can provide further information about the issue and allow you to form your own perspective on this. I prefer not to get caught up in this sort of controversy, since I tend to value the actual substance of something more than the label people put on it.

React was initially released in 2013. It has grown into a very common buzzword within the world of front-end development. React is most often used for improving the efficiency, scalability, and/or simplicity of web applications. Although React is often used for large-scale applications since it is well known for scalability, it’s easy to get started with React and to begin learning it. Furthermore, there are plenty of free tutorials and other resources on the web to provide a strong foundation. I won’t cover installation in this article. You may prefer to use a different method of installation than what I used on my machine. The React website (reactjs.org) should provide everything that you need for the installation process.

Bruce Lee once said that “the best way to learn to swim is to jump in the water” (just don’t drown).
This concept also applies to programming. We’re going to use “Create React App” to create our
application, which requires that you have Node (version 6 or higher) and NPM (Node Package
Manager) at the time this article was written. If you aren’t sure whether you have Node installed (or
the version) then enter the following command at your command prompt:

node -v

If you have node installed, it will tell you the version that you have installed. If you don’t have Node installed, then you’ll most likely receive some sort of error message. Fixing this error message is easy, since installing Node is easy. If you’re a developer, it doesn’t hurt to have Node installed on your machine, even if you have no interest in using React. Therefore, I suggest installing it.

First, let’s install Create React App with the following command:

npm install -g create-react-app

Next, let’s create an app named ltp-react-tutorial:

create-react-app ltp-react-tutorial

Once create-react-app finishes getting your application ready to play with, let’s change into the directory of your application:

cd ltp-react-tutorial

Finally, let’s start the development server for our application:

npm start

It’s possible to run multiple servers for React applications, although each one needs to have a different port (port 3000 is usually the default choice). Let’s take a look at our web application in a browser at http://localhost:3000/, given that you used port 3000 (if you used a different port, just change the 3000 to whichever port you chose for the application). If you read this article more than a few months after it was written, then your results may vary. However, the initial application created by create-react-app appears as in Figure 1-1.

Figure 1-1: Initial Application

Before we take a look at App.js, let’s take a look at index.js from within the src directory of your
React application.

Code Listing 1-1: index.js

Don’t worry too much about everything that is being imported, since this article is only meant to give you a brief introduction to React. Let’s focus on the first line of code after the import statements. First, we call the ReactDOM render function, which displays our App component (the source of which is found in App.js) into an HTML element with the id “root”. If you open up the file public/ index.html, you will notice that there is a div element with the id of root. This is where the App component is actually displayed. If you removed that div, then the application would no longer function properly. That doesn’t mean you couldn’t use a div by a different id, I just want to make it a bit more clear what goes on under the hood. The next line of code registers a service worker for serving assets from the local cache. I’m not going to delve deeply into this, but you may view the code in src/registerServiceWorker.js, if you want to understand how it works. I should also mention here that React components are important to understand, since they allow us to break user interfaces down into pieces that are easy to work with. At this current point, we only have one component defined in our code (App), but that’s because it’s simply a Hello World type of application. Let’s take a look at the code for our App component, as shown in Code
Listing 1-2.

Code Listing 1-2: The App Component – App.js

Just like with the previous example, don’t concern yourself with the imports. The definition for the App component all exists within the curly braces after class App extends Component. The word “extends Component” means that it’s a type of component (and inherits all of the properties of a React component in OOP fashion). Let’s change the line “To get started, edit <code>src/App.js</ code> and save to reload.” simply to “Hello World!” for a more traditional first program. The app should refresh automatically without you manually reloading it, and you should see the message at the bottom changed to “Hello World!” React is great for all sorts of applications that you may develop. There is much to learn on how to properly wield it. Using React effectively, usually also requires knowledge of design principles, which is outside of the scope of this article. There are also other JavaScript libraries that we need to cover. Now that you’ve gotten your feet wet, you should feel comfortable delving deeper into the sea of React. The reactjs.org website has a great tutorial on making a Tic-Tac-Toe game. There are also plenty of other great resources that are freely available on the subject. Let’s move on and
play with FusionCharts.

FusionCharts

Download https://www.fusioncharts.com

In the 2017 version of this article, I covered a JavaScript charting library named Chart.js. That library is still great for charting purposes, although I wanted to cover a different charting library this time. FusionCharts only allows the “trial version” for free. However, the term “trial version” is misleading, since it still comes with full features. FusionCharts wants you to pay for it if you’re using it for commercial purposes, but allows everyone to use it for free. If it’s free, it’s for me.

In addition to creating standard charts (bar graphs, pie charts, etc.), FusionCharts is also great for creating gauge charts and map charts. In this article, we’ll learn how to create a bar graph, pie chart, and a map chart with FusionCharts. Let’s jump right in and get started by installing FusionCharts. Visit fusioncharts.com in a web browser and click “Download free trial”. You may also install FusionCharts via npm or Bower. However, in this case I simply downloaded and extracted the zip archive. The files that you will need to import into your web applications for FusionCharts to work exist within the js directory.

First, we’re going to create a bar graph showing the performance of different sales people within a sales company. The motives behind this chart are mysterious and unknown. However, one could imagine that it may be for determining who should be eligible for a promotion and who should be eligible for replacement. It could also be used to determine the effectiveness of major changes in work flow or new marketing strategies. The possibilities may be greater than what you may initially expect. Within the directory where you have your installation of FusionCharts, create a new HTML file named bargraph.html and populate it with the code shown in Code Listing 2-1. After you get it working and see the result shown in Figure 2-1, then we will dissect the code to understand how it works.

Code Listing 2-1: bargraph.html

Figure 2-1: FusionCharts Bar Graph

If you hover your mouse over any of the bars, you will also see a little blurb pop-up with the name of the employee and their annual sales. As you may have noticed, Chris didn’t produce a single dollar in sales this year. This was because he was too busy writing this article on JavaScript libraries.

I won’t be covering the basic concepts of HTML, JavaScript, or JSON in this article. Therefore, if my explanation of the code confuses you, you might benefit from learning those concepts. HTML, JavaScript, and JSON should be in the repertoire of most developers, so I suggest acquiring these skills if you don’t have them already. I should also note that although this example uses a JSON structure, you may also use XML instead.

The first two JavaScript elements reference the FusionChart core library and FusionChart fint theme. There are four themes available from the initial installation at this time (which are stored in the directory js/themes): carbon, fint, ocean, and zune. You can try changing the themes with various charts to see how it effects the output – preferences may vary. After the two JavaScript references, we encounter the JavaScript that does the heavy lifting. Before we explore the rest of the JavaScript, I want to note that the only portion of the HTML code that you should notice is the div (with the id barGraphContainer) which is used to render the bar graph. When the graph is rendered, the default text (If you see this message, your bar graph didn’t load properly) is replaced with the graph. Therefore, if you see the text instead of the graph, consider it to be an error message.

The first thing that we see in the JavaScript code is the FusionCharts ready function. In this particular program, pretty much everything occurs within the ready function, although this probably wouldn’t be the case for real world apps. The ready function is executed once the DOMContentLoaded browser event has been triggered, which in plain English means that all of the HTML content has been loaded. This is an advantage, since it could be a shame if our JavaScript was executed before the div element (barGraphContainer) used to render the chart was ready for it.

Let’s now take a look at what happens once the code passed to our ready function is executed. It really consists of only two main things – creating a FusionChart object (named salesChart, although you can choose a different name if you wish) in which we store the JSON structure containing the data for the chart, and then render that FusionChart object.

Although I won’t explain the general principles of JSON, I will at least define what each part of our
JSON structure means:

1. type – The type of chart that we’re rendering, which in this case is column3d. There are other types you could use instead. If you want, you can change the type to column2d to see a two-dimensional version of the bar graph.

2. renderAt – This specifies the HTML div in which the chart should be rendered at.

3. width –The width of the chart in pixels.

4. height –The height of the chart in pixels.

5. dataFormat –The data format (both XML and JSON are valid data formats) of
the chart.

6. dataSource –Data source actually consists of two children JSON objects: chart and data. The chart JSON specifies the general background information of the chart, while the data JSON represents the specific information to populate the chart with.

6a. chart –This consists of caption, subCaption, xAxisName, yAxisname, and theme. It should be fairly self-explanatory about how these work, if you take a close look at the graph. You can even manipulate the values to see how it effects the output.

6b. data –The data used to create each bar in the graph. It’s an array of labels and values; each label represents the name of the employee, while each value represents their annual sales.

The only other thing that we do, is call the render function on our FusionChart object (salesChart). This renders the chart into the HTML div with the id barGraphContainer, since that was the div specified for rendering in our JSON.

FusionCharts may appear intimidating at first, but once you have created only a few charts, you’ll be amazed at how easy it is to use. Let’s take a look at two other examples of FusionCharts. However, I won’t explain the code in depth, since it should be easy to understand now that I’ve explained how the bar chart works in depth. Let’s take a look at a pie chart which shows the owners of the United States National Debt. The code is shown in Code Listing 2-2, and the output is shown in Figure 2-2.

 

Code Listing 2-2: piechart.html

Figure 2-2: FusionCharts Pie Chart

I configured this pie chart to show the percentage of the debt next to each country name. The dollar amount of the debt for a particular country is shown when you hover over the portion of the pie for that country. Finally, we will create at a map chart that displays the number of illicit drug overdose deaths by state in the United States. You can move your cursor over a particular state to see the number of illicit drug overdose deaths in 2014.

Code Listing 2-3: map.html

 

Figure 2-3: FusionCharts Map

Math.jsv

Download https://mathjs.org

Now, let’s have some fun with math.js, which is a JavaScript library for performing mathematics. Since JavaScript has some built-in support for math, we will explore some of the advanced features that math.js has to offer. Many applications don’t involve advanced mathematics, but the applications that do greatly benefit are from libraries such as these. In our examples, we will be downloading the math.js file and placing it in the same directory as the code for our examples. However, if you install math.js via npm (with the -g option, which means global installation) you may also use it on the command line. We won’t be covering that in this article, but it’s worth knowing. Head on over to mathjs.org, which is the math.js website. It’s quite possible for the layout of the website to change, but it should be relatively easy to navigate towards the download/installation page. Once you’ve created a directory with the math.js library in it, create another HTML file within that directory and populate it with the code in Code Listing 3-1. The output will exist within the web console, as shown in Figure 3-1.

Code Listing 3-1: mathjs.html

Figure 3-1: Console Output

When you run this code in a browser, you will simply see a blank white page. Don’t freak out – this is all part of the game plan. All of our output is in the console for this example. Therefore, go ahead and enter the web console. The procedure for entering the console varies slightly depending on the browser. However, most modern browsers have user friendly developer tools. If you’re confused, a quick Google search should be able to come to the rescue.

Most of the workings of the math.js library should be relatively straightforward just by browsing through the source code. However, there are a few things that I should note. First, make sure to use “math” and not “Math” if you’re trying to use math.js instead of the native JavaScript Math object. Some numbers also might not output properly, without using math.format (such as arrays and matrices). However, in many cases you can get by fine without it. Regardless, you should always check the output of your calculations whenever you begin working with a new mathematics function within the library. Everything should work as expected much of the time, but it’s always best to make sure you’re using the function properly before applying it to some real-world problem.

There are much more advanced things that you can do with math.js, but even this basic example covered things such as simplification, derivatives, and matrix math. Keep in mind that you don’t have to use this library all by itself. For example, combining the power of math.js with FusionCharts could help you perform valuable mathematical computations on your data prior to using it to generate a chart. This could allow you to utilize information that may have been unavailable (or at least rather time consuming to figure out) by simply using FusionCharts directly with data from a database. You could even also throw React into the mix in order to improve the efficiency of the application and to help with building the user interface. The next library that we’re going to cover (Lodash) is helpful in many different applications. It also works well with other libraries. To make a long story short, each of these libraries may seem somewhat limited in application by themselves, but no library needs to feel lonely. To be completely honest, it’s actually best for libraries to be oriented towards specific types of problems. A jack-of-all-trades library would be extremely bloated, take longer to learn, and most users would only use a small fraction of its features.

Lodash

Download https://lodash.com

Lodash is a JavaScript library of utility functions that helps us to avoid writing our own custom functions for common programming tasks. Lodash is actually based upon another JavaScript library named underscore.js (which was developed in 2009). The original developers of underscore .js have instead shifted their energy into further developing Lodash. I personally believe that Lodash actually gets its name from underscore.js, since an underscore ( _ ) looks like a dash (-). However, it is lower than a regular dash – hence a “low dash”. This is merely speculation and I could be wrong. When calling Lodash functions, we reference the Lodash library with the underscore character (similar to how we reference the Leaflet library with the L character).

A utility function allows us to put code that often gets re-used into a single function. This prevents us from duplicating code, avoids sloppiness, and encourages organization. The utility functions within Lodash apply to arrays, collections, loops, numbers, strings, and objects. In other words, Lodash is practical for an extremely wide range of different programming situations. To get started, visit the Lodash website (lodash.com) and download the library. In the 2017 version of the article, we used a CDN (Content Delivery Network). However, in this edition, we’ll DOWNLOAD: https://lodash.com download the library instead. The src attribute of our script tag will point to the lodash.js file that we downloaded from the Lodash website. Create a file named hello-lodash.html, and then copy/paste the code from Code Listing 5-1 into it. It contains all of the code that we’ll be using to display a few utility functions within Lodash that work
with arrays.

Code Listing 5-1: hello-lodash.html

 

When you view this page in a browser, you should receive the same output displayed in Figure 5-1.

Figure 5-1: hello-lodash.html

This program is really quite simple, but it shows off how Lodash makes it so easy to perform common programming tasks. First, we create an array and use the Lodash forEach utility function to iterate through each of the elements (displaying each element in our HTML div that we named output):

 

A “for-each” loop is native to many languages, but it isn’t a native part of the JavaScript language. In a nutshell, Lodash makes JavaScript much more powerful and awesome. Next, we reverse the order of the values within the array by using the Lodash reverse function. We then display the values yet again by iterating through the array with the forEach utility function:

 

It wouldn’t be difficult to write a function that starts at the maximum index of an array, and then proceeds to iterate through the array until we reach index 0. With each iteration, we could add each value to a new array (which would be the same size as the original), and then return that new array (the Lodash reverse function probably works similar to this under the hood). However, it’s even easier to just call the reverse function on the array as opposed to writing our own utility function. It serves as good exercise to learn how functions like this actually work, but it would be a waste of time to keep writing functions like this over and over again.

As I’ve matured as a developer, I’ve realized that even copy/ pasting code can be a waste of time (as opposed to using libraries), and it isn’t fun to update the same function in twenty different source code files each time you decide you want to change how that function works. Finally, we call the sortBy function on our array of ages. The sortBy function sorts the ages from smallest to largest, and then outputs them to our output div within each iteration of the forEach loop:

We’ve only covered a few simple utility functions within Lodash that work with arrays, although there are many other Lodash functions specifically for working with arrays. There are also Lodash utility functions for working with all sorts of things besides just arrays or collections. An entire book or course could be written to teach any of the libraries that we’ve examined in this article. I encourage you to read the Lodash documentation at https://lodash.com/docs/ to discover some of the other great things that Lodash has to offer. Many JavaScript libraries are only helpful to a niche of programmers, although Lodash may benefit just about anyone that writes JavaScript code. It wouldn’t be difficult to write a function that starts at the maximum index of an array, and then proceeds to iterate through the array until we reach index 0. With each iteration, we could add each value to a new array (which would be the same size as the original), and then return that new array (the Lodash reverse function probably works similar to this under the hood).

However, it’s even easier to just call the reverse function on the array as opposed to writing our own utility function. It serves as good exercise to learn how functions like this actually work, but it would be a waste of time to keep writing functions like this over and over again. As I’ve matured as a developer, I’ve realized that even copy/ pasting code can be a waste of time (as opposed to using libraries), and it isn’t fun to update the same function in twenty different source code files each time you decide you want to change how that function works. Finally, we call the sortBy function on our array of ages. The sortBy function sorts the ages from smallest to largest, and then outputs them to our output div within each iteration of the for Each loop.

CreateJS

Download http://www.createjs.com

CreateJS is actually an entire suite of multiple JavaScript libraries and tools. It allows us to easily integrate graphics, animation, sound, and interactivity via the HTML canvas element. It consists of four primary libraries:

EaselJS is primarily used for creating and rendering graphics, text, and animations via the HTML5 canvas element (which we saw earlier in our index.html). For more information on EaselJS, check out the official documentation at:http://www.createjs.com/docs/easeljs/
modules/EaselJS.html

TweenJS is designed for tweening animation. I’m sure you may be confused by the word tweening (as I certainly was). Tweening is defined as generating the values between two points. For example, the points between (1, 2) and (4, 5) is (2, 3) and (3, 4), if following a straight line (but keep in mind that not all trajectories are necessarily straight). TweenJS has great synergy with EaselJS, since it can add neat features to your animations. For more information on TweenJS, check out the official documentation at: http://www.createjs.com/docs/tweenjs/modules/TweenJS.html

SoundJS is an API for working with sound. It is used to create sounds, play/pause/stop sounds, change the volume of sounds, load sounds, and even install plugins. For more information on SoundJS, check out the official documentation at: http://www.createjs.com/docs/soundjs/modules/SoundJS.html

PreloadJS is used for preloading our assets. Preloading refers to the initial loading that takes place before the rest of our application executes. For more information on PreloadJS, check out the official documentation at : http://www.createjs.com/docs/preloadjs/modules/PreloadJS.html

Since CreateJS is so large, I decided not to provide any examples of each library in an effort to prevent this article from becoming too large and intimidating. However, CreateJS is an awesome suite of Javscript libraries. I felt that I would be doing this article an injustice, if I didn’t at least mention it. There are numerous tutorials on the web which may help you get started with CreateJS. I also teach how to develop an application using CreateJS in the book that I wrote with Mark Lassoff: “App Development Guide: Wack-A Mole” (which is available on Amazon.com). I can absolutely guarantee that CreateJS will make your applications much more fun, interesting, and interactive. If you’re interested in using JavaScript to create games, do yourself a favor, and check it out!

Be the first to comment

Leave a Reply

Your email address will not be published.


*