What Are the Best Links for Learning About ECMAScript 6 ?

JavaScript

ECMAScript 6 LogoLike it or not, ECMAScript 6 is coming soon to a browser near you (and what’s not to like about that?). Learning about new additions to the specification is only a few clicks away.

Being in a “feature frozen” status since August of this year, ECMAScript 6 is on its path towards becoming a part of daily life. While the speed with which each browser manufacturer will implement these features will vary, adoption is inevitable.

I won’t waste pixels discussing why ECMAScript 6 is such a big deal. I’m assuming that you are aware of some of the more well-known features and are excited about them. But understandably, it can sometimes be difficult to decide where to jump in. I’ve gone through the tons of ECMAScript 6 bookmarks that have piled-up in my Google Docs and detailed the best ones below. This is by no means an exhaustive list; I tried to limit it to articles or videos that I felt were the most well-presented.

ECMAScript 6 Introduction

ECMAScript Language Specification ECMA-262 6th Edition – DRAFT

https://people.mozilla.org/~jorendorff/es6-draft.html

It doesn’t get much drier than this. But sometimes dry is good. There are many links out there that will be more enjoyable to read (and possibly more helpful), but when you really need to drill-down on a particular topic, the specification is always a source worth considering.

ECMAScript 6 with Kit Cambridge

Kit does a really nice job here. He starts out with a history of JavaScript that is worth the price of admission alone. Instead of just regurgitating key dates and facts, he helps you understand why the ECMAScript standard has evolved the way it has (did you know that ECMAScript 4 never survived beyond “draft” status?). He then prioritizes some of the less “sexy” features such as: the Spread operator, Default parameters, the Destructuring Assignment, Symbols and Generators. This guy is pretty young, but he is incredibly smart, super-technical, and presents himself very well.

Kit Cambridge, “EcmaScript Next: The Subtleties of ES 6” at W3Conf 2013

This is technically the same exact presentation as the previous video. But I must say, just like watching a good band perform the same song on two different occasions, it is still worth watching, even if you have seen the previous video.

Announcing Understanding ECMAScript 6 | NCZOnline

http://www.nczonline.net/blog/2014/03/26/announcing-understanding-ecmascript-6/

https://leanpub.com/understandinges6/read/

https://github.com/nzakas/understandinges6

OK, the first link is actually promoting his book: “Understanding ECMAScript 6”. But I wanted to include it because Nicholas C. Zakas is a JavaScript developer who is really worth listening to. I think the intro blog post is worth a read. The second link is where you can read the current state of the book.  The third link is the GitHub repository for the book, in case you want to follow his work in real-time.

Toward Modern Web Apps with ECMAScript 6 | Blog | Sencha

http://www.sencha.com/blog/toward-modern-web-apps-with-ecmascript-6/

Ariya Hidayat presents a clear and well-thought-out overview of some of ECMAScript 6’s most exciting features.

ECMAScript 6 Features

While there is much to shout about, it can also be a bit overwhelming. Here are the ECMAScript 6 features you are most likely to experiment with, or be asked about in an interview.

Arrow Functions

Functions have gotten a significant injection of new functionality: Greater control over lexical “this” binding and streamlined syntax.

Arrow functions – JavaScript | MDN

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

ECMAScript Wiki – Arrow Functions

http://tc39wiki.calculist.org/es6/arrow-functions/

Understanding ECMAScript 6 arrow functions | NCZOnline

http://www.nczonline.net/blog/2013/09/10/understanding-ecmascript-6-arrow-functions/

Kevin Chisholm – Blog

http://blog.kevinchisholm.com/javascript/ecmascript-6/getting-started-with-ecmascript-6-arrow-functions-basic-syntax/

http://blog.kevinchisholm.com/javascript/ecmascript-6/getting-started-with-ecmascript-6-arrow-functions-parameters/

http://blog.kevinchisholm.com/javascript/ecmascript-6/getting-started-with-ecmascript-6-arrow-functions-the-this-keyword/

Block-Level Scope

Learn about how the new “let” and “const” keywords break the “functions-only” paradigm with regard to managing scope.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

http://www.sitepoint.com/preparing-ecmascript-6-let-const/

Rest parameters

If you’ve ever written a function that needs to take a variable number of arguments, you’ve probably used the Array.prototype.slice.call approach to convert the arguments object into a true array, or designed the function so that it expects an array. ECMAScript 6’s Rest Parameters removes this pain and makes for more concise code.

Rest parameters – JavaScript | MDN

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters

Default and Rest Parameters in ES6

http://www.htmlxprs.com/post/24/es6-functions-default-and-rest-parameters

ECMAScript 6 and Rest Parameter

http://ariya.ofilabs.com/2013/03/es6-and-rest-parameter.html

Spread Operator

A yang to the Rest Parameter’s ying, the Spread Operator allows you to pass the elements of an array to a function as individual arguments in one shot, without the need to iterate that array.

Spread operator – JavaScript | MDN

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator

ECMAScript 6 and Spread Operator

http://ariya.ofilabs.com/2013/03/es6-and-spread-operator.html

Classes

Although constructors provide a way to implement classes JavaScript, ECMAScript 6 introduces a syntax that more closely resembles languages such as Java and PHP, not only in the way you create a class, but also in how you inherit from it.

An introduction to ES6 classes

http://javascriptplayground.com/blog/2014/07/introduction-to-es6-classes-tutorial/

Use ECMAScript 6 Today – Tuts+ Code Article

http://code.tutsplus.com/articles/use-ecmascript-6-today–net-31582#class

 

Getting Started with Highcharts Part II: Formatting the Y Axis

JavaScript

Highcharts chartLearn how to properly format the “y” axis values of your Highcharts chart.

In “Getting Started with Highcharts Part I: Basic Charts,” we covered the absolute basics of how to use the Highcharts jQuery plugin. In that article, we demonstrated that with minimal effort, we can render a professional looking chart in our web page. So the final example was a column chart that provided a data visualization of total 2014 sales in the Acme Widgets company.

But when you look at that final jsFiddle.net link, there are a few areas that could use additioal effort. The first area I wanted to focus on is the “y” axis (aka the “up and down” dimension of our chart). We have properly labeled that axis “US Dollars,” but this approach is inefficient, and the actual dollar amounts are not formatted correctly.

Example # 1

So, in Example # 1, we have a column chart that is borrowed from the previous article in this series. The “y” axis is labeled as “US Dollars,” which is ok, but not very efficient. The actual numbers do not have dollar signs next to them, which minimizes the visual impact. Also, if we format these numbers correctly, we shouldn’t need to use the word “Dollar” in the label. So something like “Sales” would be more efficient and visually cleaner.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 1: http://jsfiddle.net/gf9d3pq4/1/

Example # 2

In Example # 2, we made two changes: 1) We simplified the label as: “Sales”, 2) We aded a “labels” property. This property is an object with one value: “format”. The value is a string which provides a template for how the “y” axis values should be formatted. In this case, we have added a dollar sign to the left of the number. This is great, but there is still one problem: the highest value on the “y” axis is “1100”. This number is not formatted correctly for most locals. Using the United States as an example, there should be a comma after the “1”. So let’s fix this.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 2: http://jsfiddle.net/gf9d3pq4/2/

How to Demo:

  • Click the jsfiddle link
  • Change the values of the “yAxis” property and then click the “Run” button in the upper-left-hand corner of the screen to see how your changes affect the appearance of the chart.

Example # 3

In Example # 3, we updated the labels.format value so that a comma is added for thousands. We also specified no decimal places. The comma is a big improvement, making four-digit numbers display correctly for the United States numbering syntax (proper syntax for other locals will vary).

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 3: http://jsfiddle.net/gf9d3pq4/3/

How to Demo:

  • Click the jsfiddle link
  • Change the values of the “yAxis” property and then click the “Run” button in the upper-left-hand corner of the screen to see how your changes affect the appearance of the chart.

Summary

In this article we learned how to format the “y” axis of a Highcharts chart. We discussed the “yAxis” property of the configuration object, the “labels” property, and how to add a dollar sign to properly convey US currency. We also demonstrated how to add a comma so that four-digit numbers are properly formatted.

Helpful Links for How to format the Highcharts “y” Axis

http://api.highcharts.com/highcharts#yAxis.labels

http://stackoverflow.com/questions/19810931/highcharts-y-axis-thousands-separator

Getting Started with Highcharts Part I: Basic Charts

JavaScript

Highcharts ChartLearn how to incorporate data visualization into your web page with just a few links of JavaScript

The data visualization trend shows no signs of slowing down, and charting is a key skill in that area. Highcharts is a jQuery plugin that provides a simple interface for creating great looking charts. There is a tremendous amount of muscle under the hood, which means that complex charts are not only within reach, but they do not require a degree in advanced mathematics. If you want to use Highcharts for a personal or non-profit project, then it is available without cost under the Creative Commons Attribution-NonCommercial 3.0 License.

In this article, I will cover the absolute basics of Highcharts. I will keep the deeper features for a later post, and instead focus on the bare minimum needed to leverage this super-powerful jQuery plugin and quickly spin up a chart on your web page.

Since Highcharts is a jQuery plugin, rendering a chart in your web-page could not be more simple:

So that’s it! Of course this little snippet of code has no use because highcharts knows nothing about the chart that we want to create. As simple as this library is to use, you do need to provide a few details so that Highcharts knows what to do. There are plenty of defaults that are provided so that you can worry about only the most critical details, but at minimum, Highcharts needs the data that powers your chart.

Example # 1A

Example # 1B

In Example # 1A, we have the base HTML for the rest of the examples in this article. For the sake of brevity, I will not include the HTML in further examples, only the JavaScript. Just keep in mind that the JS in the rest of the examples will go where you see the comment: “highcharts code will go here.”

In Example # 1B, we have the bare-minimum JavaScript needed to invoke the highcharts jQuery plugin. We passed an object to the highcharts method, which contains a “series” property. The value of this property is an array. There are multiple options when it comes to this series property, for now we will keep things very simple; the array has one element and that element is an object. This object has a “data” property whose value is an array. The element of that array has numbers, and the numbers in that array are the key to your chart.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 1B: http://jsfiddle.net/u4wke4vo/1/

How to Demo:

  • Click the jsfiddle link
  • Change the data in the “series” property’s array and then click the “Run” button in the upper-left-hand corner of the screen to see how your changes affect the appearance of the chart.

X and Y Axis

Now it might be a good idea to take a moment to discuss the concept of the x and y axis. Although this article is focused on the absolute basics of Highcharts, there is little to accomplish here without a firm understanding of how data is represented visually. The “x” axis represents the horizontal dimension of the chart, and the “y” axis represents the vertical dimension. Another way of looking at this is: the “x” axis is the “left to right”, and the “y” axis is the “up and down”.

When you look at the jsfiddle link for Example # 1B, you’ll notice that the “x” axis doesn’t really offer too much value. What do the numbers 150, 900, 675 and 400 mean when they are mapped to an “x” axis of 0 to 3? For this article, I am using a “Total Sales” context so that each example will present the total sales for a group of three representatives of the Acme Widget Company. The “x” axis is the sales reps. So instead of displaying arbitrary numbers, the “left to right” dimension of our chart will display names of the sales reps.

Example # 2

Here in Example # 2, we’ve added a second property to the configuration object named “xAxis.” The xAxis property is an array of strings, and each string provides a label for the “x” axis. So, in our case, that “left to right” dimension of the chart represents the Acme Widget company’s sales representatives.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 2: http://jsfiddle.net/u4wke4vo/2/

How to Demo:

  • Click the jsfiddle link
  • Change the data in the “series” property’s array and then click the “Run” button in the upper-left-hand corner of the screen to see how your changes affect the appearance of the chart.

Notice that Example # 2 is a line chart. That is the default chart type that Highcharts presents when you do not provide enough specifics. It looks nice, but it does not make a great deal of sense in this context because visually, it gives the impression of “data over time”. Our “Total Sales” context represents a series of set values for a year, so we need a chart type that better represents that kind of thought process. So, in my opinion, a column chart is a perfect example.

Example # 3

Here, in Example #3, we’ve added a new property to the configuration object called “chart”, which is an object. This object has one property: “type”. This is where you tell Highcharts whether you want a “pie” chart, a “bar” chart, or a “line” chart, etc. For our examples, a “column” chart makes much more sense than a line chart.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 3: http://jsfiddle.net/u4wke4vo/3/

How to Demo:

  • Click the jsfiddle link
  • Change the data in the “series” property’s array and then click the “Run” button in the upper-left-hand corner of the screen to see how your changes affect the appearance of the chart.

You may have noticed that the chart’s title is: “Chart Title”, the “y” axis label is: “Values” and the “x” axis label is: “Series 1.” These are defaults that Highcharts provides when you have not specified them. While a helpful feature, it is likely that you’ll want to specify those kinds of labels. Let’s take care of that now.

Example # 4

So, now we’ve changed a few things in Example # 4. The “title” and “subtitle” properties are self-explanatory. The “yAxis” property is an object, whose “title” property is yet another object with a “text” property. This determines the label for the “up and down” dimension of our chart. The sole object in the “series” property’s array now has a “name” property. This provides the label for the “x” axis, or “left to right” dimension of our chart. In this case, it indicates that all sales figures represent sales in the United States only.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 4: http://jsfiddle.net/u4wke4vo/4/

How to Demo:

  • Click the jsfiddle link
  • Change the values of the various properties and then click the “Run” button in the upper-left-hand corner of the screen to see how your changes affect the appearance of the chart.

Summary

In this article, I covered the bare minimum needed to render a Highcharts chart in your web page. We covered the simple syntax for instantiating the jQuery plugin, and how to pass-in the configuration object. We also covered how to provide data, the x and y axis, and how to label them. We also discussed how to specify the type of chart that should be rendered.

Helpful Links for getting started with HighCharts

http://www.highcharts.com/

http://www.highcharts.com/docs

http://www.highcharts.com/demo

Renaming a file with Node.js

Node.js

Node.js LogoLearn how to rename a file with Node.js, in ten lines of code

I was fleshing out a few ideas on a project today and found myself trying to figure out how to rename a file with Node.js. I have no doubt that there are better ways to go about this, but I thought I’d document my findings.

The first thing I realized is that the low-level nature of Node.js offers a great deal of power, but also with that power comes the need to handle all of the details. For me, this meant getting references to four things:

  1. The name of the old file
  2. The name of the new file
  3. The full path to the old file
  4. The full path to the new file (which does not exist yet)

The first two items are easy: I just had to provide a name for the old file, and decide what to call the new file. The last two items involved a bit more effort. I needed to do three things:

  1. Get the path of the folder that contains the old file
  2. Add a trailing slash to that path
  3. Set a permanent reference to the old file

So, to accomplish all of these tasks, I decided to use the filepath Node.js module.

Example # 1A

 Example # 1B

Example # 1A shows the contents of package.json. There is only one dependency: the filepath Node.js module.

In Example # 1B, I first set references to the file system module, as well as the filepath module. Next, I provided strings for the names of the old and new files. The filepath module is then used to get the path to the current folder; I set that to the fpFolder variable (adding a trailing slash to that string, which will be needed when we append file names to that string).

The variable fpFile is used as a permanent reference to the old file (this will come in handy for Example # 3.) Finally, I build the full file paths for the old and new files. After that, a couple of console.log statements to make sure all of this work is correct.

Example # 1C

Example # 1C shows the output of the two console.log statements. Each path will vary for you a bit, so I simply put “[YOUR LOCAL PATH TO]” for the folder structure that leads up to that file in the github repo that you cloned (see “How to Demo” below).

This example does not actually rename a file. So, now I will use the file system module to make that change.

How to Demo:

  • Clone this github repo: https://github.com/kevinchisholm/video-code-examples
  • Navigate to: JavaScript/node-js/node-modules/fs/fs-rename
  • Execute the following command in a terminal prompt: npm install
  • Execute the following command in a terminal prompt: node filepath-1.js

Example # 2

In Example # 2, I use the file system module’s rename method to rename the file: “re-name-me.txt.” This method takes three arguments: a path to the old file, a path to the new file and a callback. The callback takes one argument: an error object. Inside of the callback, I check for the error object, and then output the path of the new file. So now, follow the instructions below to see this code in action. After you execute the code, the file: “re-name-me.txt” will be renamed to: “ive-been-renamed.txt.”

In order to rename Example # 2 again, you’ll need to manually rename the file: “ive-been-renamed.txt” back to: “re-name-me.txt”. After a few times back and forth, this got pretty tedious and I started to think that there must be a way to toggle the file back and forth. Meaning: If the file has been renamed, change it back to the original name, and so forth.

How to Demo:

  • Clone this github repo: https://github.com/kevinchisholm/video-code-examples
  • Navigate to: JavaScript/node-js/node-modules/fs/fs-rename
  • Execute the following command in a terminal prompt: npm install
  • Execute the following command in a terminal prompt: node filepath-2.js

Example # 3A

In Example # 3A, I use the ternary operator when setting the final path for the old and new files. In each case, I check to see if the old file exists, and then depending on the answer, I set each path accordingly.

Example # 3B

Example # 3B is the full code for the final version of this file. I combined all var statements and cleaned up the code a bit. When you follow the instructions below, you’ll see that you can keep executing node filepath-2.js over and over, and the text file will toggle between the old name and the new name.

How to Demo:

  • Clone this github repo: https://github.com/kevinchisholm/video-code-examples
  • Navigate to: JavaScript/node-js/node-modules/fs/fs-rename
  • Execute the following command in a terminal prompt: npm install
  • Execute the following command in a terminal prompt: node filepath-2.js

Summary

As I mentioned, there are probably a number of ways to do this that are more efficient. Everything I detailed here was the result of a few minutes with Google. Hopefully, this article either got you where you needed to go, or pointed you in the right direction.

Helpful Links for Renaming a File with Node.js

http://nodejs.org/api/fs.html

https://www.npmjs.com/package/filepath

Getting started with the filepath Node.js module

Node.js

Node.js LogoWhen you need to reference and work with the local file system in your Node.js program, the filepath module is quite a handy tool.

Even if your Node.js program is a web-server of some sort, working with the local file system is somewhat inevitable. While Node.js does provide low-level file system access (see the Node.js fs module), abstraction is always helpful, particularly when dealing with absolute paths.

The filepath Node.js module is a very helpful utility for simple access to file paths. You’ll need only a package.json file with this module as a dependency, an “npm install” command, and then you are up and running. This article provides a quick introduction to a few of the most common methods.

Example # 1A

Example # 1B:

In Example # 1, we first create the FP variable, which references the filepath module. Then we create the path variable, which holds the return value of the FP object’s newPath method. And finally, we output the path in the console. Example # 1B shows the terminal output when we use console.log to view the path variable. This path will vary for each user so I simply put “[YOUR LOCAL PATH TO]” for the folder structure that leads up to that file in the github repo that you cloned (see “How to Demo” below).

How to Demo:

  1. Clone this github repo: https://github.com/kevinchisholm/video-code-examples
  2. Navigate to: JavaScript/node-js/filepath
  3. Execute the following command in a terminal prompt: node filepath-1.js

Example # 2

Example # 2 demonstrates the list method. The only real difference between this code and Example # 1, is the new variable “files”, which receives the value of the list method, when called on our path variable. The files variable ends up as an array. Each element in the array is an object whose “path” property is a string that points to a file in the current directory.

How to Demo:

  1. Clone this github repo: https://github.com/kevinchisholm/video-code-examples
  2. Navigate to: JavaScript/node-js/filepath
  3. Execute the following command in a terminal prompt: node filepath-2.js

Example # 3A

Example # 3B

Example # 3C

Example # 3D

In Example # 3A, we see the recurse method in action. Just as the name implies, the recurse method will recursively list all of the files in the current directory. As a result, if one of those files is a folder, then it will list all of the files in that folder, and so on. This method differs from the previous two examples in that it takes a callback. The callback is a bit like a forEach call; it iterates over all of the files or folders in the path, and calls the callback for each one. Inside of the callback, the path variable is the current path being iterated over.

Example # 3C is the output from the code in Example # 3A.

In Example # 3C, we use the toString() method of the path object so that instead of a bunch of objects that we would need to handle, we just get the values we are after; the string representation of the path to that file or folder.

Example # 3D is the output from the code in Example # 3C.

How to Demo:

  1. Clone this github repo: https://github.com/kevinchisholm/video-code-examples
  2. Navigate to: JavaScript/node-js/filepath
  3. Execute the following command in a terminal prompt: node filepath-3.js

Summary

The filepath Node.js module has much more to offer than was demonstrated here. Hopefully, this article has demonstrated how easy it is to get started with filepath.

Helpful Links for the filepath Node.js module

https://www.npmjs.com/package/filepath

http://nodejs.org/api/fs.html

Getting started with the uglify-js Node.js module

Node.js

Node.js LogoLearn how to easily implement minification and file concatenation right in your Node.js program.

There is no doubt that tools such as grunt and gulp provide powerful front-end tooling, particularly for large-scale applications. But in some cases, you may want to “roll your own”. If you want to minify and / or concatenate files from your Node.js application, the uglify-js module offers a simple syntax yet plenty of muscle-power.

So, if you want to get serious, a quick package.json file and “npm install” command are all you need to get started. Once these two tasks are taken care of, you can minify one or more files, and concatenate the output to a new file. In this article, I will show you how to do just that in less than 20 lines of code.

Example # 1A

Example # 1B

Example # 1C

 Example # 1D

In Example # 1A we have the contents of the file: package.json. This tells npm that our program depends on the “uglify-js” module. Examples # 1B, 1C and 1D are the contents of the files we will “uglify”. The actual code has no significance. We just want to have a reference so that once we have uglified the files, we can see the difference in the output.

Example # 2A

 Example # 2B

In Example # 2A, we minify the file: file-1.js. In this case, the minified code is simply shown in the console. Example # 2B shows the minified code. It’s hard to imagine a case where we would want to minify code, but only show the result in a terminal window. Realistically, we need to write the output of the minified file to a new file.

How to Demo:

  1. Clone this github repo: https://github.com/kevinchisholm/video-code-examples
  2. Navigate to: JavaScript/node-js/uglify-js
  3. Execute the following command in a terminal prompt: npm install
  4. Execute the following command in a terminal prompt: node uglify-1.js

Example # 3

 

In Example # 3, we have the content of uglify-2.js. Here, we’ve moved things into a more real-world context; we save the result of the minification to a physical file. Now notice that after you execute node uglify-2.js in your terminal, there is a new file named: output.min.js, which is a minified version of file-1.js.

The first change we made was to add a reference to the “fs” module, which provides access to the file system in Node.js. The console.log statement was left in, just so you can still see the output in the console. Below that, we call the writeFile method of the fs object. We pass it three arguments:

  1. the name of the file that will contain the result of the minification process (i.e. the minified code)
  2. the content for that file (i.e. the minified code), and
  3. a callback. The callback takes one argument: an error object. In the callback, we check to see if there was an error, and if not, we send a success message to the console.

In this Example, the callback is optional as it has nothing to do with the minification process and only provides messaging as to the status of the minification attempt.

Although Example # 3 is more of a real-world context than Example # 2, it is still a bit unrealistic as we only minify one file. In a typical production workflow, one would likely want to minify and concatenate more than one file.

How to Demo:

  1. Clone this github repo: https://github.com/kevinchisholm/video-code-examples
  2. Navigate to: JavaScript/node-js/uglify-js
  3. Execute the following command in a terminal prompt: npm install
  4. Execute the following command in a terminal prompt: node uglify-2.js

Example # 4

Example # 4 shows the contents of uglify-3.js. The only change we have made is in the call to UglifyJS.minify. Instead of passing it a string, we pass an array. Each element in the array is a path to a file we want to minimize and the concatenate to the output file. In this case all of the files are in the same folder as our program, so there is no folder structure (i.e. just the file names). You can take the same exact steps to demo this example, and when you do, you will see that the file output.min.js contains the minified code of file-1.js, file-2.js and file-3.js.

Summary

The uglify-js offers a ton of options, parameters and features. For this article, I wanted to demonstrate how easy it is to set up and use this Node,js module. But if you want to understand the true power of uglify-js, there is a ton of documentation available online. Hopefully this article got you to first base!

Helpful Links for the uglify-js Node.js module

https://www.npmjs.com/package/uglify-js

https://www.npmjs.com/package/uglify-js#api-reference

http://lisperator.net/uglifyjs/

Node.js Basics – Command-Line Arguments

Node.js

Node.js LogoLearn how to access command-line arguments passed to your node.js file

When you use Node.js as a command-line tool, you most likely type the following into your terminal application: node some-file.js. Once your application grows to even a modest level of complexity or sophistication, you will probably want to accept arguments on the command line. So, in this article, I will explain the basics of how to gain access to the arguments that are passed to your node application on the command line.

The key to accessing command-line arguments lies in the argv property of the process global. The process object is a global object, which means that you can access it from anywhere in your program. The argv property is an array that contains all arguments provided when you executed your program on the command line.

Example # 1A

Example # 1B

Example # 1C


In Example # 1A, we have the contents of the file: showArgs-1.js. Then this line simply inspects the argv property of the process objet. The output will go straight to the terminal window the moment you execute your program.

In Example # 1B, we have the actual command you use to execute the program; first node (the executable for Node.js), and then the name of the file we want to execute: showArgs-1.js.

Example # 1C shows the output of this program. So, in the console, you will see an array. The first element of that array is node, and the second element is the path to the program. This path will vary for each user so I simply put “[PATH TO]” for the folder structure that leads up to that file in the github repo that you cloned (see “How to Demo” below).

How to Demo:

  1. Clone this github repo: https://github.com/kevinchisholm/video-code-examples
  2. Navigate to: node/cli-arguments-basics
  3. Execute the following command in a terminal prompt: node showArgs-1.js

Example # 2A

Example # 2B

 Example # 2C


In Example # 2B, you’ll see that we passed some additional arguments to our program: “arg2”, “arg3” and “arg4”. I used the numbers 2, 3, and 4 because they make more sense, due to the 0-based nature of this arguments array. Remember: arguments 0 and 1 are node and the file that contains your program, so the additional arguments here are indexed as 2, 3 and 4.

Since we know that the first two arguments will be the same every time, let’s try to get rid of those first two arguments.

How to Demo:

  1. Clone this github repo: https://github.com/kevinchisholm/video-code-examples
  2. Navigate to: node/cli-arguments-basics
  3. Execute the following command in a terminal prompt: node showArgs-1.js arg2 arg3 arg4

Example # 3A

 Example # 3B

 Example # 3C


In Example # 3A, we use the Array.prototype.slice method to remove the first two elements of the arguments array. Specifically, process.argv is an array, so we use its slice method to remove the first two elements of the array, and assign that return value to the variable args. We then inspect the args array using a console.dir statement.

In Example # 3B, we execute our program, passing three arguments: “arg0”, “arg1” and “arg2’. Example # 3C shows the output, which is an array containing only the arguments that we passed to the program.

How to Demo:

  1. Clone this github repo: https://github.com/kevinchisholm/video-code-examples
  2. Navigate to: node/cli-arguments-basics
  3. Execute the following command in a terminal prompt: node showArgs-2.js arg0 arg1 arg2

Example # 4A

Example # 4B

Example # 4C


In Example # 4A, we make the output a bit easier on the eyes. Instead of a simple console.dir statement, we use the forEach method of the args array for iteration. Inside of each iteration, we use a console.log statement to output a more human-friendly message that shows the argument that is contained in that element.

How to Demo: 

  1. Clone this github repo: https://github.com/kevinchisholm/video-code-examples
  2. Navigate to: node/cli-arguments-basics
  3. Execute the following command in a terminal prompt: node showArgs-3.js arg0 arg1 arg2

Summary

While the examples here were quite basic, they are perfectly valid and could be used in your code. There are Node.js modules that provide powerful abstractions when it comes to Node.js command-line arguments. The one I have probably heard about the most is minimist. So, if you are writing an application that has even a moderate level of complexity, you will likely want to use something like minimist. That said, understanding how things work on a low level is always a good idea. Hopefully, this article has provided a helpful introduction to this concept.

Helpful Links for Node.js Command-Line Basics

http://nodejs.org/api/process.html

http://nodejs.org/api/process.html#process_process_argv

https://www.npmjs.com/package/minimist

JavaScript: WAT!

JavaScript

JavaScript LogoIf you think JavaScript is an odd language, just wait: a few experiments with the addition operator will really leave you scratching your head

Every now and then, I am reminded that as corny as the term “web surfing” may sound, it is sometimes an amazing experience. Recently, while digressing from a sub-reference of a side-topic that was tangentially related to a random blog post I stumbled across while procrastinating, I found a video titled: “WAT”. If you have even the slightest appreciation for, or hatred of JavaScript, it is a hilarious four minutes.

SPOILER ALERT: Try to watch the video before going any further. It’s much more enjoyable if you don’t know what is coming.

https://www.destroyallsoftware.com/talks/wat

Now that you have (hopefully) watched the video:

I have no idea who Gary Bernhardt is, but he makes some interesting points. Here are a few highlights:

QUESTION: What is the return value of this expression? [] + [];

ANSWER: An empty string

QUESTION: What is the return value of this expression? [] + {};

ANSWER: “[object Object]”

QUESTION: What is the return value of this expression? {} + [];

ANSWER: 0

There are a few more examples, but the overall message is: the JavaScript addition operator produces very odd results in corner cases. I must admit, I’ve never thought to explore this behavior and not only were my answers to all three of the above questions wrong, but I was pretty shocked by the correct answers.

Inspired, I decided to try a few of my own.

Array + Object

While [] + {} does return “[object Object]”, that return value is not an object, but simply a string whose value is: “[object Object]”. To prove this, I did the following:

Array + Function

The return value of this is the exact same thing as foo.toString();

Object + Function

As I tried yet another combination, I started to notice a pattern. When using the typeof operator, the return value was a concatenation of the “toString” methods for each value that was being added. So, if the expression is: {} + foo(), the result is “object” and “true” combined, which is: “objecttrue“. ok, got it.

But the fact that foo + {} returns NaN, makes no sense to me. And then there are a few more adventurous roads one might waddle down:

OK Kevin, so what’s your point?

That’s a fair question. Ultimately, since we never do those kinds of things in our JavaScript code (right? right? : – ), none of this should matter. But as I played around with these examples, two important things came to mind:

Troubleshooting

If you ever replicate these kinds of patterns by accident, it results in the kind of hair-pulling frustration that makes you start to actually believe that there is a dark lord of JavaScript controlling your browser. When trying to track down what seems like unexplainable behavior in your code that is clearly a bug, in addition to that missing semi-colon, implied global, or accidental use of “=” instead of “===”, consider these kinds of patterns. While they all seem very unlikely, typos can happen, and are sometimes hard to spot.

A Deeper Understanding

JavaScript is a truly odd specification. While there are plenty of odd things about it that we do know, there are always a few strange patterns like these that one might not have come across yet. There may or may not be anything useful about all of this, but as JavaScript’s ubiquity and maturity continue, any deep understanding of its quirks and idiosyncrasies can only benefit the developer.

VIDEO LINKS

Jump to: 1:22 for the good parts

(If this video link ever stops working, just google: “A lightning talk by Gary Bernhardt from CodeMash 2012”. There are many pages out there that feature this video)

https://www.youtube.com/watch?v=Othc45WPBhA

https://www.destroyallsoftware.com/talks/wat

 

JavaScript Object Inspection with Object.getOwnPropertyNames

JavaScript

JavaScript LogoWhen you need to get all of the names of an object’s properties as an array of strings, the Object.getOwnPropertyNames method is an excellent tool

In the article: “The JavaScript for…in statement – enumerating object properties,” I discussed the for-in statement as the “go-to” tool for object enumeration. I’m a big fan of that feature and feel it is worth its weight in gold. But I’d be remiss if I did not mention Object.getOwnPropertyNames.

The getOwnPropertyNames method of the “Object” object differs from the for-in statement in two ways: It returns an array, and the elements of that array are strings. These strings are the property names of the specified object.

Example # 1 A

Example # 1 B

In Example # 1 A, we create the object: “userObject”. Then using the Object.getOwnPropertyNames method, we inspect it. Example # 1B accomplishes the same thing, but the results are significantly different because we inspect the window object, and there are literally hundreds of properties. In each case though, the return value of the Object.getOwnPropertyNames method is an array. The array elements are strings that contain the names of each property contained in that object. But what if we want to get the value of each property?

Example # 2

In Example # 2, we use the jQuery.each method to enumerate the elements of the array returned by the Object.getOwnPropertyNames method. Inside the callback, we output not only the name of the property, but the value of that property. The key here is that we use the following syntax: userObject[val]. Since we know the name of the property, we can use bracket notation to get its value (e.g. object[propertyName] ).

Summary

The Object.getOwnPropertyNames method may not always be the right tool for the job. Some may say that the for-in statement is more than sufficient for object enumeration and, often, that may very well be the case. But if you ever need to get all of the names of an object’s properties as an array of strings, the Object.getOwnPropertyNames method is an excellent tool.

Helpful Links for Object.getOwnPropertyNames

http://mdn.beonex.com/en/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames.html

Getting Started with ECMAScript 6 Arrow functions – The “this” keyword

JavaScript

ECMAScript 6 LogoOther than syntax, the biggest change that ECMAScript Arrow Functions brings about, is how it relates to context: in the function body, “this” has a different meaning than you may expect.

It seems to me that the two problems that are solved by ECMAScript 6 Arrow functions are: verbose syntax and the tricky nature of “this” inside a function. Granted, when working with methods and constructors, the meaning of “this” is a bit easier to understand. But when working with functions that are not constructors, or not bound to an object, the “this” keyword will resolve to the window object, and that is rarely the behavior you want. In a function that is defined in the global scope, it is probably unlikely that you will intentionally want to refer to “this” (and global function declarations should really be kept to a minimum or even better, avoided at all costs). But when you have a function that is declared inside of a method for example, it is not at all uncommon to attempt access to “this” from the nested function. This is where the frustration starts, because the meaning of “this” will vary depending on the circumstances.

Example # 1A

In Example # 1A, the object foo has two properties: “color”, whose value is: “red”, and the method: “getColor”. The method foo.getColor has a nested function: privateGetColor, which references “this”. The problem is: inside of privateGetColor, “this” refers to the window object. Since there is no window.color, privateGetColor returns: “undefined”, which means that foo.getColor() returns “undefined”.

Example # 1B

In Example # 1B, we have fixed the situation by creating a private variable named: “me” inside of foo.getColor, which caches “this”. This way, the nested function: “privateGetColor” now has access to “this”, and this foo.getColor returns “red”.

Example # 2

In Example # 2, we have a more elegant solution. By leveraging an arrow function, we no longer need to create the variable “me”, in order to cache the value of “this”. Now that the nested function: privateGetColor is an arrow function, we can reference “this” in the arrow function’s body. Since privateGetColor now returns “red”, foo.getColor() returns “red”.

Lexical binding of “this”

The reason that Example # 2 saves the day, is because of the change in meaning for the “this” keyword inside of an arrow function. Normally, “this” will refer to the object of which the function is a method. With arrow functions, “this” is bound lexically. This means that it is where an arrow function is defined that affects the meaning of “this”, not where it is executed.

Example # 3

In Example # 3, we have an object named “bar”, which has a “color” property. When we execute foo.getColor(), we use the call method to change the context in which getColor is executed. This should have changed the meaning of “this” to “bar”, which would result in the return value of “blue (i.e. privateGetColor.call(bar) should return: “blue”). But that is not what happens; the return value of foo.getColor() is: “red”.

The reason for all of this is that inside of an arrow function, “this” is bound lexically. So, it is where an arrow function is DEFINED, not where it is executed, that determines the meaning of “this”. It might help of think of how scope works in JavaScript. The lexical binding of “this” inside the body of an arrow function behaves in a similar way. The closest containing object outside of the arrow function will be resolved as “this”.

Summary

The meaning of “this” inside an arrow function is without doubt a significant change in the JavaScript specification. Since ECMAScript 6 is 100% backwards-compatible, this has no effect on the meaning of “this” inside of normal function definitions, function expressions, constructors or methods. While it may take a while to get used to this concept, the ramifications are very positive. The ability to reference a specific object inside of a click-handler or AJAX calls makes for code that will be easier to read, manage and extend.

Getting Started with ECMAScript 6 Arrow function Parameters

JavaScript

ECMAScript 6 Logo - arrow functions parametersThere is a tremendous amount of flexibility when it comes to parameters in Arrow Functions.

In the previous article: “Getting Started with ECMAScript 6 Arrow functions – Basic Syntax,” we had a very basic overview of ECMAScript 6’s Arrow Functions and their syntax. In this article, I’ll dive a little deeper into the topic of parameter.

In the previous article, we learned how the parameter(s) now come first, and then the “=>” characters, which effectively replace the “function” keyword. This is very efficient and is a key aspect to the simplicity of arrow functions. But it won’t take long before you’ll want to accept multiple parameters in your arrow function. And of course, you may want to accept no parameters.

Example # 1

In Example # 1, the function addTwoNumbers accepts two parameters. This differs from all of the examples in the previous article, each of which dealt with only one parameter. In ECMAScript 6’s arrow function, when you need to accept multiple parameters, you leverage syntax which should be quite familiar to you: enclose the parameters in parentheses.

Arrow Functions that Take No Parameters

In situations in which you’ll want to accept no parameters, the syntax will be empty parentheses.

Example # 2

In Example # 2, we have the function: returnHello. This function takes no parameters and simply returns the string: “hello”. It is certainly not a very useful function, but the main point here is that if you need to create an arrow function that takes no parameters, simply use a set of empty parentheses in place of what would have been a single parameter or parentheses that contained multiple parameters.

The Arguments Object

According to the ECMAScript Language Specification ECMA-262 6th Edition – DRAFT, “Arrow functions never have an arguments objects.” At the time of this writing, version 33.1 of FireFox does allow access to the arguments object inside of an arrow function.

Example # 3

Running Example # 3 in the JavaScript console of FireFox 33.1 demonstrates that the argument object is, in fact, available inside of an arrow function. I’m not sure if this is a mistake or an intentional disregard for the specification. For now, it’s probably best to not attempt access to the arguments object inside of an arrow function.

Summary

In this article we talked about parameters in ECMAScript 6 Arrow Functions. We discussed how to accepts multiple parameters, as well as how to specify none. We also talked a bit about access to the arguments object inside an arrow function. In the next article, I will discuss the value of “this” inside an arrow function.

Getting Started with ECMAScript 6 Arrow functions – Basic Syntax

JavaScript

ECMAScript 6 Logo - arrow function syntaxArrow functions provide a terse syntax, making for code that is more concise and flexible.

One of the most significant features of the ECMAScript 6 specification is arrow functions. Also referred to sometimes as “fat functions,” this change radically alters the rules with regard to functions in JavaScript. Initially, I had planned on writing an “Introduction to / Overview” article about arrow functions. But since code samples are always helpful, I didn’t want an “Overview” article that had code examples for every aspect of arrow functions. Instead, I decided to just jump in, and create an article that focuses on each area of importance. So this article provides a very simple introduction to general arrow function syntax.

Perhaps the hardest part to get used to with regard to ECMAScript 6 arrow function syntax is the fact that the “function” keyword and parameters are reversed. In addition, the “function” keyword is replaced by: “=>”. So, the end result is:

The above example is pseudo code, but my intention was to demonstrate the correct syntax for arrow functions. So let’s look at a working example:

Example # 1A

 Example # 1B

In Example # 1A, we have the standard syntax you would use when creating an anonymous function expression. That is, the function “addOne” takes a single parameter (a number), and returns that number plus one.

Now in Example # 1B, we have accomplished the exact same result, using arrow function syntax. The “var addOne =” portion of the code should be familiar to you. But it’s after the assignment operator, that things start to look quite different. First, we next have the single parameter: “someNumber”. That parameter is followed by: “=>”. This equal+greater than character combination replaces the “function” keyword. Next we have the function body.

The Function Body

In Example # 1B, you may have noticed the absence of the curly braces. This is because the body of our arrow function consisted of one expression. In this case, the curly braces can be omitted. When the arrow function consists of more than one expression, then curly braces are required. Also, when the function body consists of a single expression, the implicit return value of the function is the result of that expression. This is why the return value of our arrow function is the passed-in parameter plus one, even though there is no “return” statement.

Example # 2 A

Example # 2 B

 

In Example # 2A, the return value of addOne(2) is: “undefined”. This happens because the function body of addOne has curly braces, but we have not explicitly returned a value. So, just as with any function in JavaScript, a function that does not specify a return value returns “undefined” (the exception to this rule is a constructor function, which can return any object but returns the instance object when no return value is specified).

In Example # 2B, we get the expected behaviour because we specify a return value.

Returning an Object in a Single-Expression Function Body

One of the main benefits of arrow function is the terse syntax. While multi-expression function bodies are perfectly acceptable, it is likely that in many cases, you’ll want to leverage that streamline single-expression (hence single-line) syntax. But what if you want to return an object in this scenario? Since the curly braces can be omitted, you simply need to wrap the object you return in parentheses.

Example # 3

In Example # 3, we’ve gone back to a single-line version of the addOne arrow function. What differs here is that the function body is wrapped in a set of parentheses. Inside of these parentheses is an object. The beauty of this approach is that the single-line version of arrow functions allows you to omit the “return” statement, so we just provide the object that we want to return in the parentheses.

Summary

This article merely scratches the surface of what is possible in ECMAScript 6 Arrow functions. But the goal here was to simply provide a gentle introduction to the syntax. The biggest changes you’ll notice right away are:

  • The order of the parameter(s) and the “function” keyword are switched.
  • The “function” keyword has been replaced by: “=>”.
  • When the function body has a single expression, no curly braces are required.
  • When the function body has a single expression, the implied return value is the expression.
  • When the function body has a single expression, an object can be implicitly returned if it is wrapped in parentheses.

In my next post, I’ll dive a bit deeper into Arrow Function parameters.

Helpful Links for ECMAScript 6 Arrow functions

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

http://wiki.ecmascript.org/doku.php?id=harmony:arrow_function_syntax

http://people.mozilla.org/~jorendorff/es6-draft.html#sec-arrow-function-definitions

Formatting Code Samples in a Google Docs Document

JavaScript

Formatting code in Google Docs

If you are formatting code samples for your Google Docs document, there is an odd little tool that you might find quite helpful.

I recently worked on a project for a client that required adding JavaScript code samples to the documentation. At first I made a very bad assumption that there was no way for formatting code in a Google Document, so I started out using images of code samples. What a waste of time. Finally, it occurred to me that this must be a common challenge.

It turns out that there are two tools available: “Code Pretty,” and “Online syntax highlighter like TextMate.”

OPTION # 1: Online syntax highlighter like TextMate

Formattig CodeThere is an odd little tool called: “Online syntax highlighter like TextMate.” At first glance, this page might appear incomplete, if not broken. It is interestingly un-styled and bare-bones. But here is the thing: this tool is actually pretty awesome. Just paste your code snippet in, choose from one of the many supported languages, then click the “Highlight” button. You wind up with two things: raw HTML and formatted text. The HTML is perfect if you need markup. Copy and paste this formatted text into a Google Docs document. The final impressive feature is the “Style” drop-down. There are about 20 different themes to choose from. For example,  an example of formatted code generated with the Online syntax highlighter like TextMate tool is to the left.

Link for Online syntax highlighter like TextMate: http://markup.su/highlighter/

OPTION # 2: Code Pretty

Code Pretty is not bad. After a super-easy Chrome install, I was fortunately able to format code blocks quickly and easily. There are however,  clearly some drawbacks to Code Pretty.

Unfortunately, the only formatting option is font-size.  Also after a while, Code Pretty generated repeated messages saying that too many calls were being made to the service

Ultimately, Code Pretty simply stopped working. After a while it was functional again, but there is no pattern to the issue. Therefore this is not a recommended application.

Installation Link for Code Pretty:  https://chrome.google.com/webstore/detail/code-pretty/igjbncgfgnfpbnifnnlcmjfbnidkndnh?hl=en

Summary

Code Pretty” is good, but has issues and a limited feature-set. On the whole,  “Online syntax highlighter like TextMate” is an oddly-named, yet super-useful tool that is otherwise perfect for use with Google Docs documents.

Helpful Links

https://docs.google.com

http://markup.su/highlighter/

Better JavaScript Alerts with SweetAlert

JavaScript

From time to time, you may actually need an alert-like user experience. When you do, SweetAlert beats the built-in JavaScript alert function hands down.

I think most would admit that the alert was one of your first “JavaScript moments.” Or at least, it is how you debugged your very first JavaScript project. If you are a member of neither group, then you get to pick from the treasure chest on the way out. Regardless, the alert function is one that, from time to time, may be what you want… at least in spirit. More likely, you will want to use the built-in confirm functionality to act upon a “yes / no” user response. If you find yourself actually considering using or imitating the alert or confirm functions, consider SweetAlert from Tristan Edwards.

SweetAlert isn’t a jQuery plugin. Instead, it is a combination of one JavaScript file, some CSS and a handful of images. Together, they produce an alert / confirm UX that is highly-configurable and pretty serious eye-candy. Implementation is super-simple, using the global “swal” method.

Examples

A fancy JavaScript alert

A JavaScript alert with a custom icon

You can definitely do better than alert-like messages though. When you wander into confirm territory, you can customize the yes/no experience, and even provide a callback to inform that user that something they agreed to do completed successfully. I won’t try to replicate the SweetAlert examples here because Tristan Edwards already does an excellent job of that. My only message here is: If you need a better JavaScript alert/confirm experience, consider SweetAlert!

The SweetAlert Home Page: http://tristanedwards.me/sweetalert

SweetAlert on GitHub: https://github.com/t4t5/sweetalert

Two thumbs up for JSCritic.com

JavaScript Tools

JavaScript Logo

Cleaner code is always critical. When you are staring at an empty text file, using online tools such as jslint.com and jshint.com is pretty easy. But when your code grows to hundreds or even thousands of lines, constantly copy/pasting the entire contents of your JS file into these tools gets tedious. Some text-editors have great plugins that incorporate linting into your development environment, that that is often a great way to go.

But what if you simply want to do a quick “dummy-check” ?

I just stumbled across jscritic.com by Juriy Zaytsev and found it to be quite helpful for just that purpose.

The sub-title of this tool is: “Quickly check how well 3rd party script behaves.” That promise is kept by the following features:

  • Does it browser sniff?
  • Does it extend native objects?
  • Does it use document.write?
  • Does it use eval?
  • Does it use ES6 features?
  • Does it use Mozilla-only features?
  • Does it have IE incompatibilities?

But it is was these tools that really impressed me:

  • How many global variables?
  • How many unused variables?
  • Total size KB
  • Minified size

The first time I visited JSCritic.com, I quickly dumped the script I was working on into it and found out that I had a few un-intended implied globals and plenty of unused variables. The total “Total size KB” and “Minified size” are also helpful in terms of getting a quick idea of your script’s overall footprint. A quick look at Juriy Zaytsev’s blog and you can see he’s a serious JavaScript developer. I’m looking forward to reading his articles. In the meantime, I’m making good use of his tool: JSCritic.com.

Helpful Links

jscritic.com
perfectionkills.com

Video – Back-End vs Front-End Web Programming Languages

Videos

The main difference between a back-end and a front-end web programming language is where the code is executed. In this video, I demonstrate how a back-end programming language is executed on the server, whereas a front-end web programming language is executed in the browser.

Read the Full Post: What is the difference between a back end and a front end web programming language?

Back-End Programming Languages

While there are certainly a number of back-end web programming languages, for this video I use PHP. I demonstrate who the server escapes the opening / closing PHP tags and executes whatever code is inside of them. I’ll also show you how the client can send a message to the web server in order to dynamically alter the HTML that is served.

Front-End Programming Languages

The list here is pretty short: JavaScript. Every modern web browser understands JavaScript. In this video I demonstrate how JavaScript is executed on the client-side (i.e. in the browser). I show you how JavaScript code is delivered from the server, but executed on the client. I’l also show you how to run arbitrary JavaScript code in the client using The FireFox plugin: FireBug.

Getting Started with Backbone.js Models – Part II : Creating an Initialize Method

Backbone

Backbone.js LogoIn the previous post: “Getting Started with Backbone.js Models – Introduction,” I discussed how the extend method of the Backbone.Model constructor is extended, which results in a new “class” that you can instantiate. When extending this constructor, an object was passed-in, which contained default values for the model data. Those default values were key/value pairs that were contained in the “defaults” property of the passed-in object.

In this post, we will talk about a sibling the of “defaults” property: the “Initialize” method.

The “Initialize” method

Why would we care about an Initialization method? Single page applications require an intimate relationship with the data. Not only do you consume and present data, but in many cases, you will want to know when a Backbone model is created or changed. Adding an “Initialize” method to your Backbone model allows you to interact with your model at the time of creation.

Why would I need an “Initialize” method?

While there are many answers to that question, a fairly typical one would be: “notification.” Let’s say that your single page application (aka “spa”), consumes a list of salespeople who work for a company, and presents that list in the DOM. If the application allows the user to create a new salesperson, then you would likely want to update the DOM, adding the new salesperson to the list. The most logical way to accomplish this is to have a method attached to your model that executes when a new instance is created (i.e. when the model constructor is instantiated), and that initialize method would update the DOM, possibly even presenting the data from this new model.

NOTE: In order to keep the code examples here short and simple, I will only present code that has changed since the last post. For the base code that is behind the working example below, view the page source as well as the link to the JavaScript file.

Example # 1A

Example # 1B

In Example # 1A, we have a quick re-cap of or SalesPerson Backbone model from the previous post. As discussed, we extend the Backbone.Model constructor, passing-in an object with a “defaults” property, which contains key/value pairs that supply default data values (e.g. “John” and “Smith”).

In Example # 1B, we have added a method named: “Initialize”. This method is executed when the model is instantiated. This means that every time we create a new model, that model’s “Initialize” method will execute. In this example, a message is logged to the console, which includes the “fname” and “lname” properties.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 1B: http://jsfiddle.net/y5j7G/

(be sure to open your JavaScript console when you view the JS Fiddle link above)

Example # 2

 

 

In Example # 2, we have the actual code from the full working example (link below). The reason for the setTimeout is to exaggerate the “message” effect. Since things happen pretty quickly, I wanted to make it a bit easier to see that when a new model is created, that model’s “initialize” method executes.

HERE IS THE LINK TO THIS ARTICLE’S FULL WORKING EXAMPLE: http://examples.kevinchisholm.com/backbone/models/basics/html/part-ii.html

How to Demo:

Each time a new SalesPerson item is created, a green message flashes in the upper-left-hand corner of the browser. When the page loads, there are four such messages. As you manually add new SalesPerson items, a green message will flash, showing the model data. All of this is made possible by the SalesPerson constructor’s initialize method.

Summary

In this post, we learned how to create an initialize method for a Backbone Model. We discussed why this is important, and how it can be used in a real-world context.

Helpful Links for Backbone Model’s initialize method

http://stackoverflow.com/questions/10118988/whats-the-difference-between-initialize-and-constructor-on-a-backbone-model

http://vairix.com/blog/backbone-initialize

Getting Started with Backbone.js Models – Introduction

Backbone

Backbone.js LogoLearn how Backbone.js Models provide abstraction that simplifies data management in your single page application

In my previous articles about Backbone.js, I covered the basics of routes and views. I chose those areas as starting points because they are a bit easier to digest and put to use. For example, you can put together simple pages that demonstrate routes and views. To me, these are “quick wins.”

But data is where the real action is. The whole point of a single page application (aka “spa”), is that the page loads, you pull in data, display the data, possibly allow the user to change some of the data, and update the page accordingly. If there is no data in the mix, it’s just a static web page. Even in that scenario, Backbone routes and views can be very helpful because they force you to organize your code so that it is easy to read, manage and extend. But when you need to consume, display and manage data, Backbone really shines.

Why Backbone Models?

Well, in short: Backbone Models wrap your data with super-useful functionality, providing time-saving abstraction.

What?

Ok, consider the following data:

Now, that all seems nice. But what if you needed to run a function as soon as that object is created? You would need to write a function that “creates” the object first, and then calls a callback (a typical approach). Ok, but now what if you wanted to have a function that was executed any time that the data changes? Well, then you would need a “setter” method, that… yep…. calls a callback. And then what about if the “setter” method had to return only the data that was changed? Oh yeah, and it has to return the previous value of any changed data as well. This is more than a few lines of code.

Now, what if you realized that a giant e-commerce app you are building will probably need all of that functionality, but there will be different kinds of data and you will probably need even more data management tools

All of this (and more) has already been done for you: Backbone.js Models.

Example # 1

In Example # 1, we have created a variable named “salesperson”. As a result, this variable becomes a constructor function. (If you are not familiar with the concept of JavaScript constructor functions, you might want to review this article: What is the difference between an Object Literal and an Instance Object in JavaScript ? | Kevin Chisholm – Blog )

It is important to understand that you are “extending” the Backbone Model “class”. This means that you are creating a constructor function that inherits from the Backbone Model constructor. You will never execute your SalesPerson constructor. In other words, you will never do this:

You will instantiate that constructor in this manner:

In this scenario, “someVariable” becomes an “instance” of the SalesPerson constructor, which inherits from the Backbone Model constructor. So far we have not added any new functionality to our “sub-class” of the SalesPerson constructor, which means that it is virtually identical to the Model constructor. Let’s change that.

Example # 2A

In Example # 2A, we passed an object into the extend method of the Backbone.Model constructor. This is where we start to see some value in our efforts to sub-class this constructor. This object tells the extend method: “Hey, give me the Backbone.Model “class” but add the properties and methods that I provide in this object.

The “defaults” property is a big first step. What you are doing with that property is proving values for all of the properties that EVERY instance of the SalesPerson will constructor will have. In most cases, you will want to overwrite those properties (i.e. there is not too much use in having 700 data objects with the same “fname” of “John”. This approach makes more sense with properties like “totalSales” or “title”. These are the kinds of values that can have a default, and then on a per-item basis, when appropriate, a specific value can be provided.

Example # 2B

In Example # 2B, we have instantiated our new SalesPerson constructor three times. The first two instances: “tom” and “andy” provide all three properties that our Backbone Model expects: “fname”, “lname” and “totalSales”. But you might have noticed that the third instance: “jane”, does not provide a “totalSales” property when instantiated, which means that the default value of “$0” will be used.

Example # 3

In Example # 3, we have the full JavaScript code for our working example.

DISCLAIMER: There are a number of JavaScript anti-patterns here. I wanted to keep things simple here so please disregard the fact that there are multiple global variables, an overall lack of names-spaced methods, and no client-side templating is used.

First we have a variable named: myJsonData, which simply provides the raw data. We then have our SalesPerson constructor, which extends Backbone.Model, and has default values of “John”, “Smith” and “$0” for the properties “fnam”, “lname” and “totalSales”. We then instantiate the SalesPerson constructor four times, creating instances, which are each Backbone models (i.e. “tom”, “andy”, “jane” and “kendall”).

The variable: “isNewItem” simply provides a way to give any user-created LI elements a different appearance.

The function: “makeLi” takes a Backbone model instance and uses its “get” method to get a property value from the model. That function returns a jQuery object (i.e. an LI DOM element wrapped with jQuery).

The function: renderInitialSalesData passes our four Backbone model instances to the makeLi function, and injects them into the DOM.

Finally, we create a click-handler for the ‘#addModelSubmit” button. This handles the form submit so that the user can add a new Sales Person. On each click, the “First Name”, “Last Name” and “Total Sales” values from the form fields are passed to a new instance of a Backbone model, and then injected into the DOM.

HERE IS THE LINK FOR FULL WORKING EXAMPLE: http://examples.kevinchisholm.com/backbone/models/basics/html/part-i.html

HERE is the JAVASCRIPT: http://examples.kevinchisholm.com/backbone/models/basics/js/part-i.js

How to Demo:

When the page loads, you’ll notice that there are three items rendered in the DOM. The data for these elements comes from the global variable: myJsonData.

After page load, enter “First Name”, “Last Name” and “Total Sales” values from the form fields, and then click: “Add New Sales Person”. Each time you do so, a new LI is injected into the DOM, using whatever values you entered. Notice that for any field you leave blank, the default value defined in our model constructor is used (i.e. “John”, “Smith”, and “0”).

Summary

In this article we were introduced to Backbone.js Models. We talked about the value that they provide, and main reasons for using them. We learned how to extend the Backbone.Model constructor, add default properties to the new sub-classed constructor, and then instantiate it.

There is much much more to talk about with regards to Backbone.js models. This article barely scratched the surface, but I hope it has been a helpful introduction to the topic.

Helpful Links for Backbone.js models

http://backbonetutorials.com/what-is-a-model/

http://www.codebeerstartups.com/2012/12/3-defining-models-in-backbone-js-learning-backbone-js

Getting started with Mustache.js now available on learnable.com

JavaScript-Templating

Learnable LogoIn my first screencast with Learnable, I cover the basics of Mustache.js, a popular client-side JavaScript templating library.

A Subsidiary of the well-known SitePoint brand, Learnable.com has been an independent course platform since 2010. They have a catalog of over 4,000 videos, covering a wide range of technology-specific topics. Learnable’s web site is well organized and easy to navigate. They work with highly-respected professionals who create short videos and long-form courses. The content is top-notch and well-produced.

Mustache LogoIn this video, I cover the basics of Mustache.js. You’ll learn how to include mustache.js in your web page, creating HTML templates, rendering an HTML template with data, as well as rendering a list of values in a template. There are code-examples included with the video as well, in case you want to follow-along and edit the code as you watch.

Here is a link to the Learnable.com Video Page: https://learnable.com/hub/play/79

Many Thanks to Erica Wass and Angela Molina from Learnable for so much help in making this first screencast a success!

 

When did Walmart become so hip?

Node.js

WalmartLabs LogoWalmartLabs is doing some very cool things with Node.js. When the heck did all this happen?

Did you know that Walmart supports nearly 30 open-source modules, most of which are used in production, or that they created their own “private npm” to prevent hacks? Nope, neither did I.

I must admit, Walmart is not a company that comes to mind when I think of leading-edge web development. But like many older large-scale organizations, they have realized that they need to better leverage technology, or lose market share to companies such as Amazon. Well, it sure seems like they are very focused.

I had never heard of WalmartLabs until very recently. I kept noticing that in my Node.js-specific web-surfing, their name started to pop-up. So I took a look, and what I found was impressive.

It seems to me that Walmart has been hiring top engineering talent, and putting them to good use. They are doing some pretty cool stuff with Node and making serious contributions to the open-source community. Below are two videos I have recently viewed that are very much worth checking out. If you are interested in Node.js in the enterprise, these folks have a lot to share.

Cheerios and Fruit Loops: Frontend Node At Walmart by Kevin Decker

Walmart Senior Mobile Web Architect Kevin Decker talks about how Walmart threw out their legacy Java stack, and the many challenges of SPAs. In particular, he provides an in-depth discussion on pre-caching with Phantom.js, Thorax, the Cheerios Library, Fruit Loops (“a sugary cheerios) and Contextify.

Node.js at Walmart

Walmart Sr. Architect Eran Hammer talks about the server stack that they built on smartOs, hapi – their open-source Node framework, and custom “server partials”. He also discusses their use of Node as an orchestration layer, and some of the challenges of migrating from their legacy Java back-end.

http://nodejs.org/video/

Interesting Links related to WallmarLabs

http://www.walmartlabs.com/

https://github.com/walmartlabs

http://en.wikipedia.org/wiki/@WalmartLabs

http://www.walmartlabs.com/the-blog/

http://techcrunch.com/tag/walmartlabs/