mapbox-gl Uncaught ReferenceError: t is not defined

Mapbox

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

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.

Summary

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

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?

Sigh.

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.

ECMA-Everything

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.

Summary

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

React

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.

Abstraction

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.

Ejecting

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

Node.js

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

Node.js

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.

Bravo!

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.

Summary

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

https://docs.angularjs.org/guide/services

http://blog.pluralsight.com/angularjs-step-by-step-services

https://blog.codecentric.de/en/2015/03/five-ways-to-write-better-angular-services/

Getting Started with Gulp.js – Creating Multiple Tasks

Gulp.js

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

Summary

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

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.

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.

gulp.src

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.

Summary

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

http://gulpjs.com/

https://github.com/gulpjs/gulp

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

https://github.com/gulpjs/gulp/blob/master/docs/API.md

https://github.com/gruntjs/grunt-contrib-concat

https://www.codefellows.org/blog/quick-intro-to-gulp-js

What Are the Best Links for Learning About ECMAScript 6 ?

JavaScript

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

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

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

ECMAScript 6 Introduction

ECMAScript Language Specification ECMA-262 6th Edition – DRAFT

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

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

ECMAScript 6 with Kit Cambridge

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

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

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

Announcing Understanding ECMAScript 6 | NCZOnline

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

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

https://github.com/nzakas/understandinges6

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

Toward Modern Web Apps with ECMAScript 6 | Blog | Sencha

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

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

ECMAScript 6 Features

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

Arrow Functions

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

Arrow functions – JavaScript | MDN

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

ECMAScript Wiki – Arrow Functions

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

Understanding ECMAScript 6 arrow functions | NCZOnline

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

Kevin Chisholm – Blog

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

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

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

Block-Level Scope

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

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

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

Rest parameters

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

Rest parameters – JavaScript | MDN

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

Default and Rest Parameters in ES6

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

ECMAScript 6 and Rest Parameter

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

Spread Operator

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

Spread operator – JavaScript | MDN

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

ECMAScript 6 and Spread Operator

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

Classes

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

An introduction to ES6 classes

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

Use ECMAScript 6 Today – Tuts+ Code Article

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

 

Getting Started with Highcharts Part II: Formatting the Y Axis

JavaScript

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

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

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

Example # 1

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

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

Example # 2

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

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

How to Demo:

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

Example # 3

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

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

How to Demo:

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

Summary

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

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

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

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

Getting Started with Highcharts Part I: Basic Charts

JavaScript

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

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

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

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

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

Example # 1A

Example # 1B

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

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

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

How to Demo:

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

X and Y Axis

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

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

Example # 2

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

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

How to Demo:

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

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

Example # 3

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

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

How to Demo:

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

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

Example # 4

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

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

How to Demo:

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

Summary

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

Helpful Links for getting started with HighCharts

http://www.highcharts.com/

http://www.highcharts.com/docs

http://www.highcharts.com/demo

Renaming a file with Node.js

Node.js

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

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

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

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

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

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

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

Example # 1A

 Example # 1B

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

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

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

Example # 1C

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

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

How to Demo:

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

Example # 2

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

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

How to Demo:

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

Example # 3A

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

Example # 3B

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

How to Demo:

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

Summary

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

Helpful Links for Renaming a File with Node.js

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

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

Getting started with the filepath Node.js module

Node.js

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

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

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

Example # 1A

Example # 1B:

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

How to Demo:

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

Example # 2

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

How to Demo:

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

Example # 3A

Example # 3B

Example # 3C

Example # 3D

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

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

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

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

How to Demo:

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

Summary

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

Helpful Links for the filepath Node.js module

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

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

Getting started with the uglify-js Node.js module

Node.js

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

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

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

Example # 1A

Example # 1B

Example # 1C

 Example # 1D

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

Example # 2A

 Example # 2B

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

How to Demo:

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

Example # 3

 

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

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

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

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

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

How to Demo:

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

Example # 4

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

Summary

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

Helpful Links for the uglify-js Node.js module

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

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

http://lisperator.net/uglifyjs/

Node.js Basics – Command-Line Arguments

Node.js

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

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

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

Example # 1A

Example # 1B

Example # 1C


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

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

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

How to Demo:

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

Example # 2A

Example # 2B

 Example # 2C


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

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

How to Demo:

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

Example # 3A

 Example # 3B

 Example # 3C


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

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

How to Demo:

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

Example # 4A

Example # 4B

Example # 4C


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

How to Demo: 

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

Summary

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

Helpful Links for Node.js Command-Line Basics

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

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

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

JavaScript: WAT!

JavaScript

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

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

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

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

Now that you have (hopefully) watched the video:

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

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

ANSWER: An empty string

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

ANSWER: “[object Object]”

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

ANSWER: 0

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

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

Array + Object

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

Array + Function

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

Object + Function

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

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

OK Kevin, so what’s your point?

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

Troubleshooting

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

A Deeper Understanding

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

VIDEO LINKS

Jump to: 1:22 for the good parts

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

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

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

 

JavaScript Object Inspection with Object.getOwnPropertyNames

JavaScript

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

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

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

Example # 1 A

Example # 1 B

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

Example # 2

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

Summary

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

Helpful Links for Object.getOwnPropertyNames

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

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

JavaScript

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

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

Example # 1A

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

Example # 1B

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

Example # 2

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

Lexical binding of “this”

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

Example # 3

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

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

Summary

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