Getting Started with Mongo Shell Scripting – Basic CRUD Operations

MongoDB

mongoDB Logo - mongo shell scriptingLearn how to create a JavaScript file that executes mongo shell commands

Why Mongo Shell Scripting ?

In the article: “Getting Started With the Mongo Shell – Basic CRUD Operations“, I covered the basics needed to perform CRUD operations on a MongoDB database, using the mongo shell. All of the examples in that article were in real-time. This is perfectly acceptable, and there may be cases in which you will want to perform administrative tasks manually. But it is also possible (and more likely) that you’ll want to create a script that executes a batch of mongo shell tasks. So, since JavaScript is the language used to interact with the mongo shell, we can pass a JS file to the mongo command in a terminal. This is mongo shell scripting.

This functionality offers a great deal of potential. For example, in this article I will provide a very simple demonstration that performs basic CRUD operations (“Create, Read, Update, Delete”).

An important note about the following examples:

If you want to run these examples locally, you have two options:

  1. Clone this GitHub repo and follow the instructions: https://github.com/kevinchisholm/mongo-shell-scripting-basic-crud-operations 
  2. Scroll down to the section: “How to Demo“, and then follow the instructions

Creating a Database

Create the “madMen” database – Example # 1

In Example # 1, we create the “madMen” database and establish a connection to it. The “allMadMen” variable is set to null for now, but will indeed be used in the next example.

Adding Data to / Reading Data from a Database

Create the “names” collection – Example # 2

In Example # 2, we create the “names” collection and then add four documents to it. We then use the “allMadMen” variable to store a reference to the names collection, and then iterate it. The purpose of the iteration is to allow you to see in your terminal that the madMen database has actually been populated with documents. Example # 2 demonstrates both the “Create” part of our CRUD operations, and  the “Read” part as well.

Updating A Collection Document

Let’s make a change to “Donald Draper” – Example # 3

Example # 3 is the “U” in our CRUD operation; in other words: “Update”. Here we use the forEach method of the names collection to iterate and find the document whose “name” property is set to: “Don Draper”. So, once we find that document, we update its “name” property to: “Dick Whitman”.

Deleting A Collection Document

Let’s delete “Dick Whitman.” – Example # 4

In Example # 4, we delete the document whose “name” property is set to: “Dick Whitman.

Dropping a Database

Drop the “madMen” database – Example # 5

db.dropDatabase();

In Example # 5, we drop the “madMen” database.

The Entire App – Example # 6A

In Example # 6A, we have the completed example code. To demonstrate, numerous print and printjson statements have been added so that the terminal output makes a bit more sense.

The Output – Example # 6B

In Example # 6B, we have the terminal output from the code in Example # 6A.

How to Demo:

  • Make sure the MongoDB database server is running
  • Create a file named: “create-db.js”.
  • Copy the entire contents of Example # 6 to “create-db.js
  • In a terminal window, execute the following command: “mongo create-db.js

Summary

In summary, we learned how to perform basic CRUD operations on a MongoDB database by leveraging mongo shell scripting.

Helpful Links for Mongo Shell Scripting

Getting Started With the Mongo Shell – Basic CRUD Operations | Kevin Chisholm – Blog

http://docs.mongodb.org/manual/administration/scripting/

Getting Started With the Mongo Shell – Basic CRUD Operations

MongoDB

mongoDB logoLearn how to perform CRUD operations on a MongoDB database, using the mongo shell

While it is likely that you will want to leverage MongoDB for your Node.js application, the mongo shell is an incredibly useful administrative tool that should not be overlooked. The definition provided by mongodb.org is: “The mongo shell is an interactive JavaScript shell for MongoDB, and is part of all MongoDB distributions.” It really is that straightforward: you can interact with your MongoDB database using JavaScript, in a command shell. Brilliant.

In this article I will demonstrate how to create a MongoDB database, add documents to the database, update a document, delete a document, and then delete your database. All of this will be done using a command prompt and JavaScript.

NOTE: I assume that you already have MongoDB installed globally. If you do not have MongoDB installed and need assistance with that, please see the “Installation Links” section at the end of this article.

Starting the Mongo shell

Before you can interact with a MongoDB database using the mongo shell, you’ll need to have the MongoDB database server running. In order to start the MongoDB server, execute: “mongod” in your terminal window. The output you see should be similar to this:

Starting the Mongo shell couldn’t be easier. Open a second terminal window, and then execute the command: “mongo”. You should see the following output in your terminal window:

You may be surprised to see that you are connected to “test”, but that is the default database. In order to see a list of existing databases, execute the following command:

You should see the following output in your terminal window:

Creating a MongoDB Database

In order to create a new database, use the “use” command. Execute the following command:

You should see the following output in your terminal window:

Now take a look at the existing databases again by executing the command: “show dbs”. You may be wondering why the new database “madMen” does not show up in the list of existing databases. This is because it has no data. Let’s add some data to that database.

Adding Documents to a Collection

With MongoDB, we can create collections on the fly when we add data. For example, the new database “madMen” is empty. We can add a “names” collection and insert a document into that collection all in one command.

Execute this command:

You should see the following output in your terminal:

Now, let’s take another look at the list of databases. Execute the command: “show dbs”.

You should see the following output in your terminal:

The reason you now see the madMen database in the list is because it contains some data. Let’s add three more documents to the “names” collection. Execute the following commands:

If you executed the previous JavaScript, the “names” collection should now have four documents. Let’s talk about how you can view all the documents in a collection.

Iterating Over the Documents in a Collection

If you want to view all of the documents in a collection, using the mongo shell, it is at minimum, a two-step process. First, obtain a reference to the collection, and then iterate over the collection using the next() method. In the following example, we’ll create a while loop. The hasNext() method will be used as the condition of the loop, and then inside of the loop, we’ll use the next() method to get the “next” document in the collection. The return value of that method will be passed to the printJson function, which is specific to mongo.

Execute this code:

In the previous example, we set the variable “allRecords” equal to the result of “db.names.find()”. The “allRecords” variable then has a reference to all of the documents in the “names” collection. We then use a while loop to iterate over the collection. On each iteration, the next method of the allRecords variable is passed to the printjson function. The output in your terminal should be similar to this:

The values of each document’s “_id” property will differ in your terminal because these are unique IDs, generated by the instance of MongoDB. The rest of the data should be the same.

Updating a Document

Now that we have four documents in the “names” collection, let’s update one of those documents. We do this by using the “save” method of the collection object. We’ll need to pass the “_id” of the document that we want to update, as well as the new data. Let’s change “Don Draper” to “Dick Whitman”.

You should see the following output in your terminal:

Now, let’s use the while loop we created earlier to inspect all records of the “names” collection:

You should see the following output in your terminal:

As you can see, the document that contained “Don Draper” has now been changed to “Dick Whitman”.

Deleting a Document

Let’s delete the same document that we just updated. In order to do that, we’ll use the “remove” method of the collection object, passing it the “_id” of the exact document that we want to delete:

You should see the following output in your terminal:

Now let’s take a look at all the documents in the database again:

As you can see, the document that we deleted no longer exists.

Deleting a Database

While not something you are likely to do too often, deleting a database is a perfectly valid MongoDB operation. The syntax could not be more simple; use the “dropDatabase” method of the db object.

You should see the following output in your terminal:

Now, execute the command: “show dbs”. You should see the following output in your terminal:

 Summary

In this article, we learned about basic CRUD operations in Mongo Shell. We learned how to start the database server, start the shell and view a list of all databases. We also covered steps needed to create a database, add documents to that database, update a document, delete a document and delete a database. There is a mountain of topics when it comes to the Mongo Shell. I hope this article helped you in getting started.

Helpful Links for the mongo shell

General Links

http://www.mongodb.org/

http://try.mongodb.org/

http://docs.mongodb.org/manual/crud/

http://docs.mongodb.org/v2.2/mongo/

http://www.tutorialspoint.com/mongodb/

Installation Links

Install MongoDB on OS X — MongoDB Manual 3.0.1
http://docs.mongodb.org/manual/tutorial/install-mongodb-on-os-x/

Install MongoDB on Windows — MongoDB Manual 3.0.1
http://docs.mongodb.org/manual/tutorial/install-mongodb-on-windows/

Install on Linux — MongoDB Manual 3.0.1
http://docs.mongodb.org/manual/administration/install-on-linux/

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

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/

JavaScript Interview Questions – Functions

JavaScript

JavaScript LogoBefore you head into that interview, make sure you understand how functions work, and the various components of their behavior.

Functions play a major role in the JavaScript language. In addition to providing private scope, they allow you to organize blocks of code for later execution. While most front-end developers have used JavaScript functions many time, there are some core areas of knowledge that are important to know.

I consider the following topics to be the baseline for a decent understanding of JavaScript functions.


Q: What is the length of the above function named: “foo”?
A: 3

Hint: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length


Q: In a function, what does the word “arguments” refer to?
A:
It is a property of the function, and is an array-like list of the arguments that were actually passed into the function
Hint: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments


Q: What does the above function return?
A: “undefined” (without quotes)
Hint: If you do not specify a return value in a function, it returns undefined .

return – JavaScript | MDN

undefined – JavaScript | MDN


Q: Given the above code, what will be the console output when foo() is executed?
A: “hello there undefined”
Hint: When a function executes, any  arguments that are not passed-in have a value of: undefined.


Q: Given the code above, how would you programatically obtain a string representing the source code of the function?
A: foo.toString()
Hint:
Function.prototype.toString() – JavaScript | MDN


Q: Given the above code, how would you change the call to: “executeFunction” function, so that it will execute the “sayHello” function?
A:

Hint:

javascript pass function as parameter – Stack Overflow


Q: Given the above code, how would you change the call to the: “alertGreeting” function, so that it will alert the return-value of the “getGreetingText” function ?
A:

Hint:

Functional Programming — Eloquent JavaScript


Q: Given the code above, how would you change the “isFunction” function so that when it is passed a function, it returns true, and if not, it returns false?
A:

Hint:
Use the JavaScript “instanceof” operator:  instanceof – JavaScript | MDN


Q: Given the code above, how would you change the “sayHello” function so that it executes immediately after it id defined? (i.e. there is no need to call it, it executes right-away)

A:

Hint: You can turn that function into a self-executing or “immediate” function by wrapping it in parentheses, and adding a pair of parentheses after that: (yourFunctionHere)().

Immediate Functions in JavaScript – The Basics | Kevin Chisholm – Blog

Immediately-invoked function expression – Wikipedia, the free encyclopedia

JavaScript Interview Questions – Beginner

JavaScript

These are basic JavaScript questions that any front-end web developer should be able to answer.


Q: What is the keyword used when declaring variables that makes them private to a function?

A: “var”
Hint: http://stackoverflow.com/questions/1470488/difference-between-using-var-and-not-using-var-in-javascript


Q: What is the one and only way to control variable scope in JavaScript?
A: Functions
Hint: http://blog.kevinchisholm.com/javascript/scope/


Q: What are the two possible values of a boolean type?
A: true and false
Hint: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Boolean


Q: Which web browser implements Document.attachEvent()?
A: Internet Explorer 8 and below
Hint: http://msdn.microsoft.com/en-us/library/ie/ms536343(v=vs.85).aspx


Q: How do you create a DIV element using JavaScript?
A: document.createElement(‘div’)
Hint: https://developer.mozilla.org/en-US/docs/DOM/document.createElement


Q: if var foo = “hello”, how do I coerce foo to be a false value?
A: !foo
Hint: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Logical_Operators


Q: If I have var foo = document.createElement(‘img’), how do I set the “src” attribute of that image element to “someimage.jpg”?
A: foo.src = “someimage.jpg”
Hint: http://www.javascriptkit.com/jsref/image.shtml


Q: How would you check if the variable “foo” is equal to exactly 5 OR is equal to exactly 7?
A: if (foo === 5 || foo === 7){ // do something here…};
Hint: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Logical_Operators


Q: What is the difference between “=”, “==” and “===” in JavaScript?
A: “=” assigns a value, “==” checks for equal value, “===” checks for equal value and type
Hint: http://stackoverflow.com/questions/4846582/what-is-difference-between-and-in-javascript


Q: Does Internet Explorer Implement Event Capturing?
A: Only IE 9 and above
Hint: http://javascript.info/tutorial/bubbling-and-capturing

The JavaScript “this” Keyword Deep Dive: jQuery Click Handlers

JavaScript

JavaScript LogoLearn the difference between $(this) and “this” inside of your jQuery event handler.

In two previous posts, we learned that functions that are properties of an object are called “methods” (The JavaScript “this” Keyword Deep Dive: Nested Methods & The JavaScript “this” Keyword Deep Dive: An Overview). In this case, the JavaScript “this” keyword refers to the object that the method belongs to. Well, of course, this is usually pretty obvious from looking at the code.

But in an event handler, it may not be apparent to all that the JavaScript “this” keyword, is available to you inside of the event handler, and that it refers to the element that generated the event. Since many front-end developers are comfortable with jQuery, I thought I’d start with jQuery event handlers. And since click events are so common, let’s stick with that.

Example # 1

In Example # 1, we have created a click event handler using jQuery. When the user clicks the anchor tag inside of the element with the class: “download”, the jQuery “toggleClas” method is used to change the text “Click Me” fom red to blue.

Of course, many have seen $(this) used inside of the event handler to set a reference to the element that was clicked. It is helpful to know, however, that $(this) is an enhanced version of the JavaScript “this” keyword. That is to say: inside of the click event handler, “this” refers to the element that was clicked. When you put “this” inside of: $( ), you “wrap” the JavaScript “this” keyword with jQuery, which adds a number of properties and methods.

As a result of this “wrapping”, you can set a reference to the element that was clicked, but you can also leverage the power of jQuery. The native JavaScript HTML element does not have a “toggleClass” method, but jQuery does. So, by wrapping the JavaScript “this” keyword with jQuery, $(this) has allowed you to reference the clicked element, and use jQuery methods.

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

How to Demo: Click the text that says: “Click Me”. Each time you click that element, the text color will toggle between red and blue.

Example # 2

In Example # 2, we have changed the reference to the clicked element from $(this) to “this”. But when you click that element, there is an error in the JavaScript console. In Google Chrome, the error is: Uncaught TypeError: Object [object HTMLAnchorElement] has no method ‘toggleClass’, and in FireFox, the error is: TypeError: this.toggleClass is not a function. The reason for this error is that while the JavaScript “this” keyword can be used to reference the element that was clicked, it does not have a “toggleClass” method. So, an error occurs.

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

How to Demo: Open up your JavaScript console, and then click the text that says: “Click Me”. When you do, you will see an error indicating that the element you clicked does not have a “toggleClass” method.

Example # 3

So, in Example # 3, we continue to reference the element that was clicked by using the JavaScript “this” keyword, without the jQuery “wrapping”. That is: we are not using: $(this). The reason that the example now works, is because we are using the “classList” property of the element, and in-turn, the “contains”, “remove” and “add” methods. Consequently, this allows us to mimic jQuery’s “toggleClass” method.

It’s important to note that although we used jQuery to create the click handler, we can still use the JavaScript “this: keyword inside of that event handler, and access the native JavaScript element object.

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

How to Demo: Click the text that says: “Click Me”. Each time you click that element, the text color will toggle between red and blue.

Summary

In this article, we learned about the JavaScript “this” keyword when used inside of a jQuery event handler. We learned that we can “wrap” that keyword with jQuery, leveraging that library’s DOM manipulation methods. We also discussed how inside of a jQuery event handler, we can still use the “un-wrapped” version of “this”, and leverage native JavaScript DOM manipulation methods.