Understanding the difference between scope and context in a JavaScript method


scope and contextSometimes the concepts of scope and context are misunderstood in JavaScript. It is important to understand that they are not the same thing. This is particularly important inside of a method.

In JavaScript, the concept of scope refers to the visibility of variables. On the other hand, the concept of context is used to mean: “the object to which a method belongs”. That may sound like an odd statement, but it is accurate. The only time we care about context is inside a function. Period. Inside a function, the “this” keyword is very important. It refers to the object to which that function belongs. In other words, every function is a property of some object. In client-side JavaScript (i.e. in a browser), if you declare a function at the top of your code, then that function is a property of the window object. So, inside of that function, the “this” keyword refers to the window object. If you create a new object (let’s call it: “myObject”) and add a method (i.e. a property that happens to be a function), then inside of that function, the “this” keyword refers to the object (i.e. “myObject”).

So the main issue is that inside of a method, object properties and variables can sometimes be confused. In short; when the JavaScript “var” keyword is used, that is a variable. A variable will not be a property of an object (except in the global scope, which is for another discussion). But inside a method, any variable created using the JavaScript “var” keyword will be private to that method. So this means that it is not possible to access that variable from outside the method. But inside of a method, you have access to all of the properties of the object to which that method belongs. And you access these properties using the JavaScript “this” keyword. So, for example; if myObject.greeting = “Hello” and myObject.greet is a method, then inside myObject.greet, if I reference this.greeting, I should get the string: “Hello”. And if I have declared a variable named “speed” inside of myObject.greet, I would access it simply by referring to “speed” (i.e. I would not use the JavaScript “this” keyword). Also, a big difference between variables and properties in a method is that properties are always public. That is to say: all object properties can be seen and in most cases modified. But a private variable inside of a method is completely hidden from the outside world. And only our code inside of the method has access to that variable.

Try it yourself !

In above example, we start out by creating a property on the window object named: “foo”. This “foo” object is the result of an immediately invoked function expression (aka: “IIFE“). The reason that we take this approach is so that we can have a private variable: count. Our getCount method as access to that private count variable.

There is also a count property on the “foo” object. This property is available publicly. That is to say: we are able to make changes to the count property, whereas the count variable is not available outside of the IIFE. Our getCount method has access to the count variable, but that is the only way we can reach it.

When we call foo.getCount() without passing any arguments, then it increments the count property and returns it. This is CONTEXT. By using the JavaScript “this” keyword inside of the getCount method, we are leveraging the concept of context. Conversely, when we call foo.getCount(“scope”), then the count variable is incremented and returned. This is SCOPE. It is very important to understand the difference between scope and context in JavaScript.

JavaScript Spread Syntax – Basics


JavaScript Logo - spread syntaxJavaScript spread syntax provides a way to convert an array into a comma-separated list.

In this article, I will cover the basics of JavaScript spread syntax. But first, let’s start by taking a step back and thinking about how functions work in JavaScript. A function expects a comma-separated list of arguments, so, when we call a function, we need to provide zero, one or more arguments, separated by a comma. But what happens when we don’t know exactly what all of these arguments are? Now it may be tempting to simply pass an array, but then this array would be seen by the called argument as simply the first argument. In other words, argument[0] in the function would be an array. But this is not what we want; we want to pass an array to a function and for that array to be interpreted by the function as a comma-separated list of arguments.

Why is JavaScript Spread Syntax So Helpful?

So here’s where the spread syntax comes in: it allows us to put the arguments in an array, and then pass that array to the function we are calling. And, actually, this is only one example of how the JavaScript spread syntax can be helpful, but it certainly is a great way to start the conversation.

Inspect Arguments in a Function – Example # 1 A

The Output from the inspectArguments function – Example # 1 B

Inside every JavaScript function, the “arguments” keyword provides a reference to all arguments that were passed into this execution of the function. The “arguments” keyword is not an array, but an array-like object with a “length” property. Fortunately, however, this “length” property allows us to iterate the “arguments” object as if it were an array. The “inspectArguments” function from Example # 1 A contains a for-loop, which iterates over all the arguments it receives. Inside of that for-loop, we output the value of each argument.

Nothing too special there.

On the last line of Example # 1 A, we call the “inspectArguments” function, passing it: “…letters”. What’s happening here is that instead of passing the letters array, we pass “…letters”, which spreads the letters array out into a comma-separated list. Example # 1 B contains the output from Example # 1 A, and as expected, we see the contents of the letters array.

Spreading Out the Arguments – Example # 2 A

The Output Has Changed – Example # 2 B

Example # 2 A is similar to Example # 1 A, except in the way that we call the “inspectArguments” function. In other words, instead of passing just “…letters”, we pass “x, y, …letters”. This allows us to specify that the first two arguments that the “inspectArguments” function receives are “x” and “y” and the rest of the arguments is the content of the letters array. The point here is that we can mix the use of literals and the spread syntax. So as expected, Example # 2 B shows the output, which is similar to Example # 1 B, except that “x” and “y” are the first two console.log statements.

Using Spread Syntax for Both Arguments – Example # 3 A

The Output – Example # 3 B

Now, in Example # 3 A, we take things a little further. We use the spread syntax twice, which calls the “inspectArguments” function, passing the contents of both the days and letters arrays, spread out into one comma-separated list. Consequently, the output that you see in Example # 3 B is exactly as expected: the contents of the days and letters arrays.

JavaScript – For-In vs For-Of


JavaScript Logofor-in and for-of both provide a way to iterate over an object or array. The difference between them is: for-in provides access to the object keys ,
whereas the for-of operator provides access to the values of those keys.

Iterating over an object or array is a pretty routine task with JavaScript, in fact, it’s hard to imagine a day when you don’t’ need to perform this action. When Iterating over an array, things are a bit easier because you can leverage the array’s “length” property to set up your iteration. But when you need to iterate over the properties of an object, things get a little sticky.

Why For-In vs For-Of

In his article, I will demonstrate the difference between the for-in and for-of JavaScript operators. Now, while these two methods may seem to provide the same functionality, actually, they do not. In fact, you might say that they are polar opposites. The for-in operator returns the keys of an object of array, whereas the for-of operator provides access to the values of these keys.

For a better understanding, let’s take a look at some examples.

for-in – Example # 1

In Example # 1, we use a for-in loop to iterate over the elements of the days array. Now, since we are creating the variable: “day in days”, on each iteration of the loop, we have access to a day variable, which represents the element over which we are currently iterating. The output for this example can be seen in line #s 8-15, and the purpose of this example is to demonstrate that the for-in operator provides the keys of an object, not the values of those keys. It is possible to get ahold of these values, which we will see in a moment, but, for now, I just wanted to point out that for-in provides direct access to the keys of the object over which we are iterating.

Using Bracket Notation – Example # 2

Example # 2 is virtually identical to Example # 1, in that we leverage almost the exact same code to iterate over the days array. The difference here is that we manage to get ahold of the key values by using bracket-notation. So, instead of outputting console.log(day), we output console.log(days[day]). In a pseudocode kind of way, we are saying: “give me the value of the days property that had this key”. The output for this example can be seen in line #s 10-14, and it is exactly what we wanted: we see the value for each key. This does feel a little hackey though, so let’s see if we can do better than this.

for-of – Example # 3

In Example # 3, we’re able to achieve our goal by leveraging the for-of operator. Simply by using for-of (instead of for-in), we’re able to access the value of each key. So, not only is this a non-hackey way to approach this problem, it is also cleaner and easier to read.

JavaScript Rest Parameter – Basics


JavaScript LogoThe Rest Parameter allows you to do two things: (1) break out the first X arguments passed-into the function, and (2) put “the rest” of the arguments into an array.

Passing arguments to a JavaScript function is quite common. If a function expects one or more arguments, then it follows that inside of that function you’ll want to examine the incoming arguments. But things can get problematic when you’re not entirely sure exactly what the incoming arguments will be at design time. Now it’s true that inside of any function you have a local variable named “arguments” that is an array-like object, but there are two problems with this array-like “arguments” object.

First of all, it’s not an array, and while you can leverage the Array.prototype object in order to treat the “arguments” object as if it is a true array, that approach feels like a hack. Secondly, if you want to act upon the incoming arguments differently, based on their position, things can get messy. Now this is where the JavaScript Rest Parameter comes in – it’s a powerful tool that can help solve these problems.

Why Should I Care About the JavaScript Rest Parameter?

In this article, I will cover the basics of the JavaScript rest parameter. I’ll walk through the ways in which it can be used to collect the incoming arguments of a function and convert them into a true JavaScript array. I’ll also demonstrate how you can use the JavaScript rest parameter to break out the incoming arguments so that one or more of the initial arguments can be left as is, and then “the rest” of them can be put into an array.

Using the Rest Parameter – Example # 1 A

inspectArgs Output – Example # 1 B

Above we’ve created a function named “inspectArgs”, which we’ll use in the rest of the code examples for this article. In Example # 1 A, we use the JavaScript rest parameter to collect all of the arguments that are passed into the function, we and put them into an array. So, on line # 2, since theArgs translates to an array, we can use the forEach method of the “theArgs” variable to iterate that array. Inside of the anonymous callback function that we pass to the forEach method, we have access to each array element, as well as the index of that element. Now using this information, we output the value of each argument, and the index of that argument.

So, the key point here is that by placing “…theArgs” where the incoming arguments would normally go, we are saying: “take all of the arguments that are passed-into this function, put them into an array, and create a local variable for this function named theArgs”. And in Example # 1 B, you can see the output of Example # 1 A, which is exactly what we expect: the value of each argument that was passed to the inspectArgs function.

When you actually want “the rest” of the arguments – Example # 2 A

We See the First Argument, and “the rest” of them- Example # 2 B

Now, in Example # 2A, we made one small change, in order to really demonstrate the power of the JavaScript rest parameter. We changed “…theArgs” to “x, …theArgs” where the incoming arguments would normally go. So, what we are saying to the JavaScript engine here is: “let the first argument be what it is, but then take the rest of the incoming arguments and put them into an array”. So, before we use the “theArgs.forEach” method to iterate the “theArgs” variable, we take a look at the very first argument: “X” and output it.

Now if we take a look at Example # 2 B, we see the output of Example # 2 A. As expected, we see “x -> a” first, because we examined the first argument. Then we see the “rest” of the arguments, because we used the rest parameter to iterate the “rest of” the arguments that were passed into the function.

Skipping Arguments – Example # 3 A

The Second Argument Has Been Skipped – Example # 3 B

In Example # 3 A, we take an approach that’s very similar to that of Example # 2 A, by examining the first argument and outputting it to the console. But when you look at Example # 3 B, the output of this call to inspectArgs skips the second argument: “b”. This is because we specify: “x, y, …theArgs” where the incoming arguments would normally go. So now what we are saying to the JavaScript engine here is: “let the first and second arguments be what they are, but then take the rest of the incoming arguments and put them into an array”. As a result, we wind up with three local variables in this function: “a” “b” and “theArgs”. We output the value of “a” and “theArgs”, but we ignored “b”. The main point here is that we have changed the value of “theArgs” simply by specifying a “b” argument. So, as you can see, Example # 3 A truly demonstrates the power of the JavaScript Rest Parameter.

mapbox-gl Uncaught ReferenceError: t is not defined


JavaScript LogoMy Mapbox integration was working fine locally. But then when did a Webpack build and pushed the assets to my web server, there was a JavaScript console error

I was implementing Mapbox in an Angular 4 application and everything was going fine. I was working locally, but after getting some UI issues worked out, things seemed to be going very smoothly. But when I ran my build and then viewed the static assets remotely, I had this lovely little JavaScript error in my console: “Uncaught ReferenceError: t is not defined“.

Hmmmm. everything seemed just fine to me. I did some troubleshooting and the issue looked like it was being caused by Mapbox. How could this be? It was not a problem locally.

I found the answer here: Build fails when using mapbox-gl webpack 2 and UglifyJSPlugin #4359.

Credit really goes to zezhipeng  – whose answer was spot-on. Seems that when Webpack parses the mapbox-gl module, things do not go too well. So I just needed to add this line to my Webpack config:

(the “” is just whatever else you have in your module.exports.module object.)

And that was it, working again. Thanks zezhipeng!

What is the difference between LET and CONST in JavaScript?


JavaScript LogoThe JavaScript let and const keywords provide block-level scope, but there is a slight difference in how they behave. With const, you can not re-assign a value to the variable. With let,
you can.

Over time, JavaScript applications have grown in complexity. As a result of the increased code complexity programmers have been faced with a challenging dilemma: build applications that satisfy ever-evolving business requirements, yet continue to work with the same tools. It only makes sense that JavaScript would be in need of improvements, since for much of its history, functions were the only tools available to achieve scope. But, for several years, block-level scope was a feature that was sorely lacking. Then along came the ECMAScript-2015 specification that finally met that need with the let and const keywords.

The JavaScript let and const keywords are quite similar, in that they create block-level scope. However, they do differ a bit in the way that they behave. For example, the JavaScript let keyword is similar to the var keyword in that assignments can be changed. On the other hand, the JavaScript const keyword differs in that assignments can not be changed. So, once you declare a variable using the const keyword, you cannot re-assign a value to that variable. This does not mean that the variable is immutable. If you assign an object to a variable using the const keyword, you can mutate that object. You just can’t re-assign that variable with a new value. Let’s take a look at some examples.

Example # 1 A

Example # 1 B

In Example # 1 A, we have two different versions of the “i” variable. I say “two different versions” because the same variable name exists in two difference scopes, the global scope and a block scope. The block scope exists between the two curly braces: “{ }”. Then inside of the two curly braces, I used the JavaScript let keyword to declare a second “i” variable. Because we used the let keyword, that particular “i” variable is scoped to the block in which it was declared. And because of this, the console.log() statement on line # 6 outputs  50. I’ll just note here that it may seem a little odd at first to declare a variable anywhere other than at the top of the function, but this actually is the correct syntax; if we want a block-level scope variable, we use the let keyword inside of a set of curly braces.

Take a look at Example # 1 B. Notice how, in the second console.log() statement, the output is 100. This is because that second console.log() statement is in the global scope, and in that scope the “i” variable is equal to 100. So, there we have it: two different scopes without even having used a function.

Example # 2 A

Example # 2 B

Now, in Example # 2 A, there are two “j” variables.
The first “j” variable is a global, equal to 100, and the second is defined inside of the for loop. And because it’s defined inside of a block, it has block-level scope. Now look at example # 2 B. Because “i” is global, the “i” variable increments, just as we would expect. But notice that the “j” variable is always 50 in each console.log() statement, even though there is a global “j” variable. This is because on each iteration of the for loop, a block-level “j” variable is declared using the let keyword, and it is incremented (just to demonstrate that with let, we can re-assign a variable value). So in this case, with each iteration of the for loop we have a block-scoped “j” variable and it is always 51. Note that the global “j” variable is ignored on line # 12.

Example # 3 A

Example # 3 B

In Examples # 3 A and # 3 B you’ll see a similarity to Examples # 1 A and # 1 B, the only difference being the use of the use of the const keyword instead of let when declaring our block-level version of the “i” variable.

Example # 4 A

Example # 4 B

Now here in Example # 4 A, we’ve run into a problem. We tried to take the same approach as Example # 2 A, that is, we tried to increment the “j” variable declared on line # 6. The problem, though, is that when you use the JavaScript const keyword, you cannot re-assign a new value to a variable. So when you look at Example # 4 B, you’ll see that we never see the full output of the for loop that we expected, because line # 9 of Example # 4A throws a TypeError. This is because when we try to change the value of “j”, we find that this is not possible because it was created using the const keyword. In other words: it’s a constant.

Example # 5 A

Example # 5 B

Now Example # 5 A is virtually identical to Example # 4 A, except that we have not tried to increment the “j” variable. And when you look at Example # 5 B, you’ll see that we no longer have an error. In the console, the value of “j” is 50 every time.


So to recap, we now know that the JavaScript let and const keywords allow you to create block-level scope for variables, which, in turn, negates the need to always use functions to create scope. With block-level scope, all you need are the curly braces “{ }”, and within that block, any variable created using let or const is private (or local) to that block. This is particularly helpful with for-loops. And a very important thing to keep in mind: with const, you cannot re-assign values to a variable. In other words, any variable created with the const keyword is a constant and the assignment cannot be changed.

A lot to take in here, but I think it’s worth keeping on your radar, given this very functional block-level scope now increasingly available in browsers.

The Paradox of JavaScript


JavaScript LogoAre you getting an ECMA-Headache?

In the book: The Paradox of Choice: Why More Is Less, author Barry Schwartz argues that too many choices can dilute satisfaction. While this title spends much of its time in the context of consumer products, a similar argument can be made about the world of JavaScript. There is so much going on in the wild wild west that is JS, but is that really a good thing?

In short, I’d say  yes, it is a good thing. Even though it can be difficult to navigate the maze of libraries and frameworks, the explosion of activity breeds a world of innovation and creativity. But there is no doubt a cost; Where to begin? How to keep up? There is a lot of noise associated with the world of JavaScript. I actually feel that most of it is good noise, but it can be overwhelming.

I recently participated in an  Aquent Gymnasium webinar titled: keeping up with javascript is a full-time job, and I thought the title was brilliant. Not only are beginners feeling JavaScript anxiety, but experienced developers as well. I’ve heard many people ask the same questions: “Should I learn Angular or React”? – “If few ES-2015 features are currently supported, should I still learn them?” – “Grunt , Gulp or Webpack?” and so on.

ES6 vs ES-2015 vs ES-2016 vs ES-WTF

And speaking of ECMAScript, what is up with the naming-scheme? ES6 is AKA ES-2015, and ES7 is AKA 2016? Ok, that’s easy to remember. But what to learn? What the hell is a JavaScript symbol? And, what significance does it play in the million-and-fifty-fifth JavaScript slideshow I will have to make in my next Agile Sprint? Is this just like all that cruddy math that we had to learn in 8th grade, knowing perfectly well that we’d never ever need it in adult life?


So many libraries, so little time

This is where the paradox may lie. We have so many JavaScript toys to play with, but who has time to keep up with all of them? First, you have to be aware of changes in the JavaScript jungle. For example, Angular 4 is out, but there is no Angular3. Okie dokie. Next you have to understand the role of each library or framework. And then at some point, you want to learn how to use it, right?

Sometimes it is really tough to know where to invest your time. I’ve been hearing more and more about Aurelia and Vue.js. Both have enjoyed positive reviews and are gaining traction. But are they really going to take off line Angular? Am I really going to benefit in my next job interview by learning either one of these libraries or any of the other up-and-coming JavaScript libraries/frameworks ?

My answer: Bet on JavaScript every time

I’m not sure it is necessary to learn every single JavaScript framework or library that falls from the tree. We all have lives to live and there are only 24 hours in each day.

Something interesting about all of this craziness is that there is one common thread throughout: JavaScript.  JavaScript is the language used in all of these libraries/frameworks/build tools. So, you simply cannot lose by making JavaScript your top priority. If you have a free hour, spend 45 minutes studying JavaScript, and 15-minutes learning a new library. As long as your JavaScript skills continue to improve, you will always have the tools you need to learn any new library/framework/build tool. Not only that, but you will get better at picking them up. In addition, you will start to see the similarities between them and common patterns in the source code.

In short: you simply cannot lose by concentrating on JavaScript.


Not only is it important to focus on JavaScript, but it is also key to learn the new features of the specification.  Most browsers do not support these features, but they will soon, so best to get ahead of the eight-ball. ES-6 and ES-7 features are powerful and when supported, will take much of the pain out of creating sophisticated client-side web applications. More important than Angular, more important than React, learn the newest features of JavaScript. And, Babel is your friend; it allows you to use features that browsers do not yet support. Also, the combination of Typescript/Webpack is another solid solution.

Planning is key

I can only speak to what has worked for me, and that is: always trying to decide where my time is best spent. For example, one of the biggest arguments in the JavaScript world is: “should I learn Angular or React?” Well, I’d say: learn both!

You don’t have to master each one, but learn enough to understand the differences between them as well as their strengths / weaknesses. Since, I happen to spend 90% of my professional day working with Angular2, I am a fan. But, I was worried that I was falling behind on my knowledge of React, so I spent my last Christmas holiday building an application with React. Now, I am far from a React guru, but in building a simple CRUD application that I actually use each day, I was able to gain an understanding of how it works, how it differs from Angular, and what its strengths are.

I’ve tried to take this approach with every other segment of the JavaScript ecosystem: NPM vs Yarn, Gulp vs Grunt vs Webpack, Typescript vs Vanilla JavaScript, and so on. In each case I ask myself: “What is the most important thing I need to know about this library/framework/build-tool ?” and then my goal is to be able to speak intelligently about it. Sometimes it takes a Saturday afternoon, sometimes it takes a month. Sometimes it turns out that I wind up using that particular tool heavily in my daily work. But I try to at least understand what it does, how it differs from its competitor and what it brings to the table.


In my opinion, there will always be a couple of JavaScript libraries or frameworks that you work with on a daily basis, a few that you used to work with, and then a zillion that you have heard of but have not had time to learn yet. They key from my perspective, is to accept this reality; you can’t have an expert-level knowledge of everything. But you can keep your finger on the pulse of what’s going on out there, and do your best to have a good understanding of the more popular tools and the role the play.

Why the create-react-app Node module is so awesome


angular2 KEYWORD

This tool is perfect for beginners as well as React experts

The JavaScript ecosystem is the wild wild west of the technology world. It seems like every year there is a new heavyweight champ. Right now, Angular and React are duking it out for the belt. They are both solid and enjoy tremendous corporate backing / community support. But they are as different as chalk and cheese. Learning new technologies can be painful. Chances are you got here because you have decided to take the dive into the world of React. Depending on your level of experience, this can be a challenge. The create-react-app Node module can definitely help.


The create-react-app Node module protects you from all of the pain involved with setting-up a React application. Granted, there are tons of JSFiddle links out there that show you how you can spin-up a React application simply by adding to script tags to your web page. Yes, but this kins of setup is not going to cut it in the real world. These are examples that help you get up-and-running and learn.

If you are going to build a real production-ready React application, even a small one, you need some kind of workflow. This is where the pain is: front-end tooling. The create-react-app Node module takes care of all of that for you, literally. Once you have cloned the github repo, you simply execute the following command: create-react-app YOUR_APP_NAME.

Yep, that’s it!

The create-react-app  module takes care of all your Webpack, Babel & ESLint configuration and setup. The funny thing is: you don’t see it. Under the hood there is one main dependency: the react-scripts Node module. This module is like your personal front-end engineer. It sets-up Webpack and Babel  and configures it. You never have to write one line of configuration code for any of this. After you run that create-react-app YOUR_APP_NAME command,  you cd YOUR_APP_NAME, and the npm install. After the npm install is complete, npm start is your last terminal command and your local instance is alive in the browser.

Why this is so amazing

The beauty of all this is: you can get a production-ready React application setup in about 3 minutes. Not only that, this setup was created by the Facebook React team and sanctioned by them. So, you have a great template to start with. The actual application itself is literally a static “Hello World” HTML page. Before you complain, keep in mind that if you are going to learn React, you have to actually write a little code! But the really amazing part is that the most painful aspect of setting up a React application is taken care of for you. You can clone, create, install in a couple of minutes and then start writing code.


Finally, there is the “Eject” command. When you run npm run eject, the create-react-app Node module will un-wrap all of the abstraction. What this means is: all of the front-end tooling remains in-tact and continues to work perfectly, but you are no longer protected from it. Tools such as Webpack and Babel are now available to you and completely customizable. The advantage to this approach is that you can customize your application however you like. It’s also a great way to learn about front-end tooling: you can really see the recommended ways that these tools are configured.

Down sides

There are a few downsides to the create-react-app Node module. The biggest one is that there is no consideration for CSS pre-processors such as LESS and SASS. Also, you cannot configure your application when creating it. You are stuck with the configuration and tooling that is provided. Of course you can use the eject command to reveal all of that detail and do as you wish, but that brings us to the final downside: when you eject, you can never go back.

Helpful Node.js Education Links


JavaScript LogoNode.js is growing fast. This is a great problem. While is means that JavaScript lovers have a rosy future, it can sometimes be difficult to keep up with what is going on with Nodes.js

Here are a list of links that you might find helpful in your Node.js travels. In each case, I’ve provided a brief description of the link / organization / article, so that you have a sense of where you are are headed. If you feel that there is a Node.js link that I should have included in this article, please contact me at: kevin@kevinchisholm.com.

Critical Node.js Links

Node.js Logo

Title: nodejs.org

Link: nodejs.org

Description: Since this is the home page for Node.js, you cannot go wrong here.

Node.js Logo

Title: Node.js v6.6.0 Documentation

Link: nodejs.org/api

Description:The official documentation for Node.js. Very well organized and easy to read. Almost the most important Node.js documentation you can read if you are getting started.

Node.js Logo
Title: npm – Home of the package manager for JavaScript.

Link: www.npmjs.com

Description: It’s hard to imagine doing anything with node without the use of NPM. This is the official home page of NPM, and a great starting point.

Node.js Logo

Title: Homebrew. The better way to install Node.js on Mac OSX

Link: brew.sh

Description: I’m being a little opinionated here (ok. I’m being a lot opinionated). But, for Mac users, Homebrew is the way to go when you install Node.js (sorry Windows users, you are stuck with scoop : – )

Node.js Logo

Title: Built in Node.js – startups, apps, projects using Node

Link: builtinnode.com

Description: A great way to learn about who is using Node.

Node.js Newsletters

Node.js Logo

Title: npm Weekly

Link: www.npmjs.com/npm-weekly

Description: Find out what npm has been working on, thinking about, and talking about every week. A great newsletter if you are into NPM.

Node.js Logo

Title: node weekly

Link: nodeweekly.com

Description: A free, once–weekly e-mail round-up of Node.js news and articles. Another awesome newsletter if you are into Node.

Other Helpful Node.js Links

Node.js Logo

Title: Node Tutorials on scotch.io

Link: scotch.io/tag/node-js

Description: scotch.io tutorials are very easy to read. The site is in general a great resource for learning about a number of web development technologies. Fortunately, they are passionate about Node!

Share Node.js code with JSApp.us


JavaScript LogoJSApp allows you to write Node.js code in a browser, run it, and also share it with others

One of the things that makes front-end development so much fun is that you can easily create and share code. With tools such as JSFiddle, you can create an example web page and then send that JSFiddle URL to someone. Or you can even send someone the URL of a JavaScript file that you created so that they can just run $.getScript(yourJavaScriptURL) to inject your code in their page. And there are plenty of other clever ways to share / demo front-end code without a lot of fuss.

But what about Node?

Well, it’s not always so easy with Node, right? It’s server-side code, so you can’t just send someone a URL of your Node.js file to inject in their page. Github really saves the day in this case; you can create a public repo, and then send someone the Github repo URL. But that still requires the recipient to have at least git installed on their computer. And as we all know, once something takes more than 2 clicks, you start to lose your audience. That said, anyone with a reasonable attention span and a genuine interest in your code will follow the few clicks needed to clone your repo and run your code, but for quick little snippets, it sill feels like overkill sometimes.

For example, I like to write blog posts here about Node. In some cases, it does make sense to create a Github repo, especially if you have to leverage package.json, and the app requires file access, etc. But what about little examples? Just 10-20 lines of code to demonstrate a concept? Or even a simple working example?

Enter JS App!

When you navigate to jsapp.us, you immediately see some sample Node.js code. You can delete it and write your own. Then,  you simply click “test” in the sidebar (or CTRL + b), and a new browser window opens with your Node.js code running!

If you create a profile (free), you can save your code and share it with others. This is one of the most clever things I’ve seen in a long time. You can also go back and edit your files, re-name them, delete them. Really fun stuff.

If you need to create a quickie Node.js app and a Github repo would be overkill, JSApp might be just the tool you need. It’s been a while since I was this impressed but something I stumbled upon.


What are the Five Ways to Create an Angular Service?

Angular Services

Angular.js LogoThere is a lot of confusion over the difference between the angular’s factory, service and provider methods. This article explains the different ways that an Angular service can be created.

The official Angular 1.4.0 documentation page describes services as: “…substitutable objects that are wired together using dependency injection (DI)” Stating: “You can use services to organize and share code across your app.” While a bit dry, I think this is actually a perfect description. I think that many who are new to Angular are confused about which of the many methods available should be used when creating a service. Fortunately, the answers are fairly simple and straightforward.

Five Ways to Create an Angular Service

The angular.value method

The value method, one the most overlooked approaches, is most commonly used to turn a global into an injectable Angular service. While the approach is simple, the application is powerful: the value of your service is testable and can be shared across your application.

Example # 1A

 Example # 1B

Examples 1A and 1B use the exact same syntax when creating an Angular service. The only difference is their value. Example # 1A’s “speed” service is a primitive: the number 100. Example # 1B’s value is an object with a “title” property.

The angular.constant method

This works the same as the angular.value method. The difference is that it is available during the configuration phase of your Angular application. Also, the value of a this constant can never be changed.

Example # 2

 The angular.factory method

The angular.factory method takes two arguments: a string and a function. The string represents the name of the service, which will be used to gain access to this service (e.g. to inject this service into a controller as a dependency). The anonymous function that you provide as the second argument provides the actual implementation. When you register your service, Angular will execute this function.

The only difference between angular.factory and angular.service is that the callback function you provide with the service is instantiated. With the factory method, it is executed.

Its return value is cached and will be shared with any component of your application that injects the service. It is important to note that this function will only be executed once.

This is the scenario most are thinking of when they intend to create an Angular service, and probably the most common approach.

Example # 3

In Example # 3, we create a service named “myService”. Any component that lists this service as a dependency will receive the object that you see returned. This object has one method: “sayHello”.

The angular.service Method

This approach is similar to the angular.factory method with one big exception: the function that you provide is treated as a constructor and is instantiated. It is important to note that this function is instantiated only once and every component that injects your service as a dependency shares the same exact cached object that this instantiation returns.

Example # 4

Example # 4 is very similar to Example # 3, except that the latter uses the JavaScript “this” keyword when defining the properties and methods of the object that the service returns. The reason is: the function provided when registering the service is instantiated (i.e. treated as a constructor), not just executed.

The angular.provider method

This approach is the most complex of the five. The angular.provider method is actually used under the hood by all four of the other service registration approache. While this approach is more verbose, it provides a powerful feature that the others do not: the service you are registering is available to your application during its configuration phase. This is useful when creating a service that will be shared across multiple applications and needs to be configured in order to work properly.

When using angular.provider, there are two important details to keep in mind:
  1. The callback function that you pass to the angular.provider method will be treated as a constructor – This means that the callback will be instantiated for each application that it is registered with, and its return value will be shared by all components that inject that service.
  2. The callback function that you pass to the angular.provider method must have a $get method – When you inject a service into a component that was created using the provider method, Angular will call that services’ $get method to retrieve the object to inject.

Example # 5

In Example # 5, we have created an angular service named “helloWorld”. This service is available during the configuration phase of your application. After registering the service, we call the app.config method, passing the “helloWorld” service as an argument to the anonymous callback function. Inside of that callback, we use the services “setName” method to set the value of its “name” property. We could use the “helloWorld” service in a different application and set that “name” value to something different, as needed.


Most of the time, the angular.factory method is the approach that is desired / used. This does not mean it is the “right” way to create an Angular service. The approach you take should be driven by the problem you are looking to solve. angular.value and angular.constant are often helpful when you need to share a simple value across your application (keeping in mind that the value returned by angular.constant cannot be changed). The angular.service method is helpful when you want your service to be instantiated, and the angular.provider method provides a way to configure your service before any component gains access to it.

Helpful Links for Understanding the Different Ways to Create an Angular Service




Getting Started with Gulp.js – Creating Multiple Tasks


Gulp.js Logo
Learn how to create multiple Gulp.s tasks

In the article: “Getting Started with Gulp.js – Introduction,” I discussed the absolute basics needed to set up a Gulp.s task.  In that article’s gulpfile.js, we had only one task named “default”. One of the great features of Gulp, is that it will look for a task named “default”, and execute it automatically. This is fine if you have only one task, but as soon as you have two or more, it makes sense to give each one its own name.

When you have one or more named Gulp tasks, you’ll want to execute those tasks from the default task.

Figure # 1 – The folder structure before running Gulp

File structure - before

In Example # 1, you’ll see the folder structure before running gulp. So, if you look in the BUILD folder, you’ll see two sub-folders: JS and CSS. The file main.scss will be compiled into CSS and the output will go into the BUILD/CSS folder. The file: SRC/JS/main.js will be uglified and the output will go in the BUILD/JS folder. The file SRC/COFFEE/global.coffee will be compiled and the output will also go in the BUILD/JS folder.

Example # 1 – gruntfile.js

In Example # 1, we have the contents of gruntfile.js. You’ll notice that there are four tasks: default, uglify, sass and coffeescript. The default task is executed automatically. So that task simply executes the other three tasks.

How to Demo the Code Example

  1. Clone this repository: https://github.com/kevinchisholm/gulp-basics-tutorial-multiple-tasks
  2. Install node_modules with this command: npm install
  3. Run gulp: gulp
  4. Look in the following folder: BUILD/CSS, you will see the file: main.css
  5. Look in the following folder: BUILD/JS, you will see the files: main.js and global.js

Figure # 2 – The folder structure after running Gulp

File structure - after


One of the key features of Gulp is the ability to have a default task. This task is always executed by default. In this article, I demonstrated how to execute one or more named Gulp tasks from within the default task. While I chose to uglify JavaScript, compile SASS and compile coffeescript, you can create Gulp tasks for any need you might have. I hope that this article has made it easy for you to understand how to run multiple Gulp tasks.

Getting Started with Gulp.js – Introduction


Gulp.js LogoLearn how to automate your front-end build process using this streaming build system

A while back, I posted an introduction to Grunt, the JavaScript task-runner. I also posted an article about the basics of concatenation and minification with Grunt. Grunt is an excellent tool, and still enjoys a large audience. That said, the most common complaint against Grunt is that its configuration-based syntax can become tedious and cryptic. In this article, I will introduce you to Gulp.js, an excellent streaming JavaScript built tool that has become quite popular in recent years. For this article, I will not discuss the details of installing Node or Gulp. There are plenty of articles available that will provide full details on that. Instead, I will provide a very gentle introduction to Gulp and how to create a simple Grunt task.

Code over configuration

Gulp’s success has to a large degree been based on the fact that it provides a powerful alternative to Grunt’s configuration-based approach. Gulp leverages actual JavaScript code in order to accomplish its tasks. With Gulp, you read files into memory, do things to the files, and then output the files from memory to a specified destination folder.

Easy Setup

Gulp is a node module. Installation and setup could not be simpler. On a very high-level, the steps needed are:

  1. Using npm (node package manager), install Gulp
  2. Create a file named: gulpfile.js or gulpfile.coffee (coffeescript)
  3. Execute the following command in a terminal: gulp

That’s it!

Gulp is simple

One of the things that amazed me most when first looking into Gulp was the fact that there are only four APIs. Yep, four. But there is a great deal of power lurking beneath the hood.

gulp.task – Defines a task
gulp.src – Reads files into memory
gulp.dest – Writes files from memory to disk
gulp.watch – Watches the files defined by gulp.src for changes

Note: The official Gulp documentation states that there are four APIs, but I find it odd that the .pipe method is not counted amongst these.

A Simple Example

I think many people might wonder: “…what would I use Gulp for?” A very common task in front-end tooling is concatenation; you may have three JavaScript files and want them to be combined into one JavaScript file that will be used in your web page. In this example, we will take three JavaScript files, concatenate them, and then output one file that consists of those three files.

Where to Get the Example Code

Clone this repository: https://github.com/kevinchisholm/gulp-basics-tutorial-introduction

Example # 1A – package.json

In Example # 1A, we have the contents of package.json. This file tells Node that we need the following modules: gulp, and gulp-concat.

Figure # 1: Project File Structure

Project File Structure

In Figure # 1, we have the folder structure of our first example. Notice that in the SRC/JS folder there are three JavaScript files. These are the files that we will concatenate into one file. The BUILD/JS folder is empty, but that is where the final concatenated file will be written.

Now, before going any further, let’s install the node modules which our code will need. Navigate to the example-1 folder with your terminal application and then execute the following command: npm install

When running npm install, you’ll notice some activity in the console (don’t worry about the “warn” message), and then there will be a “node_modules” folder. These are the node modules specified in package.json. npm has downloaded them for us and put them in the “node_modules” folder. A detailed explanation for npm and the “node_modules” folder is beyond the scope of this article. A few google searches on either topic will yield plenty of links for further reading.

Figure # 2: Project File Structure with “node_modules” folder.

Project file structure after installing node dependencies

In Figure # 2, you’ll see that we now have a “node_modules” folder. Let’s take a look at gulpfile.js.


This is the file where the Gulp code goes. Gulp does support Coffeescript, so gulpfile.coffee is also a valid file name, but for the sake of simplicity, I will only cover the JavaScript implementation.

Example # 1B – gulpfile.js

In Example # 1B, there are two things happening: First we create to variables, each representing a module that we need. Second, we create a gulp “task”. The gulp.task method takes two arguments: 1) a task name, which is a string, and 2) a callback function, which contains the code that defines the actual task. Here is where Gulp’s real power lies: a gulp task is driven by JavaScript code (i.e. code over configuration).

Returning a File Stream

A Gulp task always returns a file stream. This is to say that gulp will read a file into memory and you want to return that in-memory file object from your task’s callback function. In-between those two tasks, you “pipe” that file to one or more plugins that manipulate the file in some way.


In Example # 1B, we use the gulp.src method to read one or more files into memory. In this case, it is the three JavaScript files in our SRC/JS folder. We then chain the pipe method, passing a call to gulp.dest as an argument. The call to gulp.dest takes a string as its sole argument: the path to our output directory: BUILD/JS.

Executing the Gulp Task

In order to actually execute our Gulp task, simply type the following in your terminal: gulp

Yep, that’s it! Because our task is named “default”, we do not need to specify a task name. Gulp assumes that we want to run the “default” task, looks for it, and then executes it. Now when you look in the JS/BUILD folder, you should see three files: file-1.js, file-2.js, and file-3.js.

Figure # 3: Non-Concatenated Files in the BUILD/JS Folder.

Build output

In Figure # 3, you’ll see that there are now three files in the JS/BUILD folder.

You may be wondering why our output is three files, and not one concatenated file. This is because we did not actually concatenate the files inside of our task. In Example # 1, I wanted to demonstrate the basic flow of a Gulp task: using gulp.src to read files into memory, and then using gulp.dest to write those files from memory to disk. Now let’s update our Gulp task so that it actually concatenates the files.

Example # 2 A – Add the Contact Module to Our Gulp Task

In Example # 2 A, we have added a new line to our Gulp task: .pipe(concat(‘scripts-all.js’)). This line takes the in-memory files, pipes them to the concat module (which concatenates them into one file named: “scripts-all.js”), and returns that in-memory file. That’s really it. Now, navigate to the folder: “example-2” in your terminal, and then run Gulp again, so see the output: gulp

Figure # 4: Concatenated Files in the BUILD/JS Folder.

The concatenated JavaScript file

In Figure # 4, you’ll see that instead of three files, there is one file: scripts-all.js.

Example # 2 B – scripts-all.js

Example # 2B shows the contents of scripts-all.js. The details of the actual code are not important. What matters is that by piping the three source files to the concat module, our output is now one file that consists of the contents of all three source files.


The fact that there are only four APIs is a testament to the fact that Gulp.js is a simple yet powerful tool for running JavaScript tasks. There is a strong and growing community behind Gulp with thousands of existing plugins. The beauty of Gulp is that since it is code, you can leverage plain old JavaScript to make your gulpfile as powerful and efficient as needed. You are only limited by your imagination. While the examples in this article were very simple, there is a great deal of depth to Gulp and plenty of details / features that you can look into. I hope that this article was a helpful introduction and provided the tools you need to understand Grunt and easily start implementing it in your project.

Helpful Links for Gulp.js Basics







What Are the Best Links for Learning About ECMAScript 6 ?


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


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




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


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


ECMAScript Wiki – Arrow Functions


Understanding ECMAScript 6 arrow functions | NCZOnline


Kevin Chisholm – Blog




Block-Level Scope

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



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


Default and Rest Parameters in ES6


ECMAScript 6 and Rest Parameter


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


ECMAScript 6 and Spread Operator



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


Use ECMAScript 6 Today – Tuts+ Code Article



Getting Started with Highcharts Part II: Formatting the Y Axis


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.


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



Getting Started with Highcharts Part I: Basic Charts


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.


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




Renaming a file with 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


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



Getting started with the filepath Node.js module


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


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



Getting started with the uglify-js Node.js module


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.


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