Posts

,

15 Blogs Every Javascript Developer Should Follow in 2020

I’ve been following the most interesting JavaScript blogs quite for a while now (this is a part of my job running https://weekendjs.com/). There are many of them. More than you might think. There are blogs started more than ten years ago, and there are relatively new ones. Some bloggers are JavaScript superstars, and others are regular engineers like you and me. Some blogs are focused on a particular ecosystem (say Angular or React, or Vue), while others are rather general.

The exciting thing is that the number of good blogs with really robust material keeps growing from one year to another. It is a promising trend, which hopefully will continue.

A few words about who makes it into the list: only the bloggers who write relatively often (at least once per month). Those are all personal blogs, not hubs, companies, etc. And of course, the main metric is the quality of the material.

OK, enough words. Please welcome, in no particular order, the top 15 blogs a JavaScript developer should follow in 2018.

2ality

The author of the “Exploring ES6” book, Dr. Axel Rauschmayer is long known for his deep and comprehensive articles. They are always well-structured and tend to cover the topics in every detail. Usually he writes about ES6/7/8 features and how to use it, but recently, for example, he did a series of articles on ReasonML, which is a hot new JS-transpilable language from Facebook.

David Walsh

David Walsh is an engineer who works at Mozilla from Madison, Wisconsin. David writes regularly (several times per month). His posts are about web development in general. Usually, these are small, understandable pieces for a broad audience on JavaScript’s new features, Node, and more.

Reginald Braithwaite

Reginald “raganwald” Braithwaite, is the author of brilliant “JavaScript Allongé,” one of my favorite JavaScript books. If you haven’t read it, go ahead and do it. Seriously, it’s a pure pleasure, I promise. As you might expect, he writes a lot on functional-related topics. His articles are probably not for beginners and instead aimed at a more experienced audience.

Michael Herman

Michael Herman is a developer and public speaker. He writes about a lot of stuff such as Python, Docker, etc. Technically, I could leave him out of this list. But his write-ups on JavaScript and related material are extremely practical and helpful, so I just can’t leave out his brilliant blog.

Addy Osmani

I’m not sure I need to introduce Addy Osmani. He is a Chrome core developer, a web performance evangelist, and a public speaker. You probably use libraries he has written on a daily basis; just check his GitHub. He also wrote the very popular “Learning JavaScript Design Patterns” book. In his blog though, he writes a lot on Progressive Apps and is one of the core contributors to the concept.

Ponyfoo

This one is easily recognizable by the iconic pixelated image of a unicorn. The author writes lots about new ECMAScript features, in particular modules, and is (as you might expect) in the middle of writing a book about modules.

Dave Ceddia

Dave’s first post dates back to 2015. And it was about Angular 2 (yeah, can you believe it? Time runs so fast). In 2017, though, it seems as if he changed his preferred framework and started writing more on React. He’s also an author of a lovely little book called “Pure React” which is aimed at starters.

Todd Motto

Speaking of Angular, it’s surprisingly difficult to find robust material on the topic. It’s understandable, perhaps, since React seems to be a lot more fun to write about. Well, at least we have this guy. Todd writes a lot on connected topics (TypeScript, NGRX), speaks at the conferences and also does courses. He’s easily the best individual Angular blogger out there.

Tyler McGinnis

Tyler McGinnis is the author of many thorough React courses. So, as you might expect, he also writes a lot about React both Web and Native. His blog also contains a lot of video materials, which are a joy to watch.

John Papa

John Papa is a developer advocate, public speaker, and of course, a blogger. He also authored several courses on for Pluralsight. He used to write a lot on Angular, especially Angular 1, but it seems he’s more into Vue now. If you’re interested in this React alternative you should follow this guy.

Valentino G.

This guy writes a lot of different topics, including Django and Node. Most often he writes about React and friends.

Ben Nadel

I didn’t know about this one until recently, but now it’s easily one of my favorite JavaScript blogs. My favorite part is that he writes a lot about UX and its intersections with JavaScript. Highly recommend it!

Bram Van Damme

It’s interesting that lots of bloggers are from Europe. Like Bram, who is an engineer from Belgium. He writes about JavaScript and also more in general about the web and web development.

Ivan Akulov

Ivan writes about React and Webpack, and also in general about different optimizations you’ll need to do as a web developer. His write-ups are highly practical, and may not suit the beginners.

Robin Wieruch

Robin works in Berlin. He writes a lot (and quite often) about React and friends. But also (and that’s what makes him interesting) he writes about stuff like AI and machine learning. There aren’t a lot of places where you can read articles like “A Web Developer’s Guide to Machine Learning in Javascript” or “Neural Networks in Javascript.” If you’re interested in those topics, you definitely need to follow Robin.

I hope you liked this list. Now go ahead and add them to your preferred RSS reader as I did and enjoy the perpetual flow of the best articles from the JavaScript world!

, ,

ES6 One Liners to Show Off

This is a guest post by Hemanth H.M and was originally published on H3manth.com.

Here is a collection of ES6 one liners to show off!

Read more

, ,

ES6: What Are the Benefits of the New Features in Practice?

This is a guest post by Jani Hartikainen and was originally published on CodeUtopia.

You’ve probably seen people talk about the features in JavaScript’s 6th edition, ES6, or ECMAScript 6. Promises, let keyword, iterators, etc. But why should you care? I certainly heard a lot about it, but I hadn’t looked into it because I wasn’t interested in theory, but rather the benefits I would get in my day to day work. Is it just feature-bloat for sake of having fancy things in the language, or are they actually useful? I then did some research and discovered a number of very useful features in ES6 that you can start taking advantage of right now. Let’s take a look at the most useful ones

Can you actually use ES6?

Before we go ahead, let’s address a critical issue: Can you use these features without worrying that it’ll break in older browsers? Edge, Chrome, Firefox and Safari all have most of ES6 features implemented. With older browsers, you will either need a shim for some parts of ES6, or you need to convert ES6 into ES5 (or lower) using a tool such as Babel. If you want to learn how to get set up with ES6, check out my post on how to get started with ES6. It has all the information you need to get going, so in this article I’ll focus on the features and their benefits.

let and const

The let keyword defines a block-scoped variable. Block-scoped means the declaration is only available within a so-called “block”. Compare how it behaves vs the var keyword:

function foo() {
  //whenever we have curly braces in code, it defines a "block"
  {
    console.log(hi); //error, the variable is not defined

    //this is only available within this block
    let hi = 1;
  }
  console.log(hi); //output: Error, hi is not defined

  for(let i = 0; i < 10; i++) {
    //the variable `i` is only available within the for block
  }

  console.log(i); //output: Error, i is not defined
}

Swap in some vars instead of lets…

function foo() {

  {
    //with var, the variable declaration gets hoisted so we will not get an error
    //when attempting to use it before its declaration appears in code
    console.log(hi); //output: undefined

    var hi = 1;
  }
  console.log(hi); //output: 1

  for(var i = 0; i < 10; i++) {
    //the variable `i` is only available within the for block
  }

  console.log(i); //output: 10
}

Variables declared using var are also hoisted, as shown with the log statement, which can cause unexpected behavior to those unfamiliar with JavaScript’s hoisting rules. const declares a block-scoped constant. You may be familiar with constants from other languages, and here they are the same: A constant is like a variable, except you can’t change its value.

const foo = 1;
foo = 2; //error: cannot change the value of a constant

There is one small gotcha when using const. When assigning an object, you will still be able to modify its properties!

const obj = { hello: 'world' };
obj.hello = 'galaxy'; //no error!

But assigning another object, even if it has the same properties, will cause an error:

const obj = { hello: 'world' };
obj = { hello: 'galaxy' }; //error

A workaround exists for this, using Object.freeze:

const obj = { hello: 'world' };
Object.freeze(obj);
obj.hello = 'galaxy'; //this will now cause an error

(thanks Reddit user jcready for this tip)

Benefits of let

A major benefit of let is it works nicely within for-loops. One of the most common stumbling blocks for JS-beginners is the closure-within-for problem:

for(var i = 0; i < 10; i++) {
  foo[i].onclick = function() {
    console.log(i);
  };
}

Seasoned JS developers recognize this and know that the click handlers will all output 10. If we rewrite this using let

for(let i = 0; i < 10; i++) {
  foo[i].onclick = function() {
    console.log(i);
  };
}

…it now behaves as could be expected: the handlers will output the value of i from their respective iterations. To me, the behavior with let is better than var. let does everything, making var feel unnecessary. For an opposite point of view, check out Kyle Simpson’s in-depth article, for and against let.

Benefits of const

Constants are perhaps a bit less common, but const can bring many benefits when making sure your code is correct and easy to reason about. Sometimes you need to declare values in functions which should not be modified – in other words, constants – and using const there gives two benefits:

  1. The person reading the code immediately sees the variable should not be changed
  2. Changing the value will result in an error

Using const to indicate values that shouldn’t change, you also reduce the likelihood of bugs. The code cannot redeclare or change the value, guaranteeing that the value keeps its meaning. Bugs have been known to occur because another programmer accidentally changed a variable like that – using const eliminates the possibility. For example, one case is functions calling other functions to get data, or initializing helper variables. These can be declared const, as they are often not changed. Using const together with let and var, it’s easier to communicate the intent of your code, which helps to make the code self-documenting.

Computed property names

Have you ever had to write something like this?

var obj = { };
obj[prop] = 'some value';

I certainly have. In ES5 there is no way to use a variable directly in an object literal, so you need to assign it separately like above. It’s only a minor issue, but ES6 fixes it by allowing the following syntax:

var obj = { [prop]: 'some value' };

Another trick is more dynamic property names:

//this will assign to obj.foo10
var obj = { ['foo' + 10]: 'some value' };

You can put pretty much any code inside the square brackets. Not a life changing feature, but convenient in some cases.

Default parameters

A common source of confusion to those unfamiliar with JavaScript syntax tricks is the following pattern:

function hello(name) {
  name = name || 'Anonymous';

  console.log('Hi ' + name);
}

This syntax is often used to give function parameters default values. Even when you do know this syntax, it fails spectacularly when dealing with booleans, numbers or other falsy values. In other words, it would be better to avoid this pattern, but unfortunately there hasn’t been a convenient way to have default values… until now. ES6 allows us to define default values for function parameters!

function hello(name = 'Anonymous') {
  console.log('Hi ' + name);
}

The benefits should be reasonably clear:

  • Less boilerplate code to handle parameters
  • Anyone reading your code immediately sees which parameters are optional, without having reading the function body (where they might or might not be on top of the function).
  • This can be useful when refactoring, as you can change a function to have default parameters instead of removing a parameter altogether to keep better backwards-compatibility

One potential gotcha of this syntax is that variables without default parameters still receive undefined as their default, rather than throwing an error if not called with enough parameters. This is how JavaScript has always worked like, but especially for newcomers this could be a point of confusion. Passing undefined as the value for something with a default parameter defined will also use the default parameter instead of undefined. It’s better to use null to represent cases of “no value” instead of undefined, it will avoid this issue. There’s also an interesting trick that you can use with defaults to enforce required parameters. You can read about it here.

Destructuring assignment

Destructuring assignment, available in many other languages, can be a very convenient feature when dealing with objects or arrays. Let’s say we want to do this:

var name = user.name;
var email = user.email;

With ES6 we can use what’s called a destructuring assignment:

var { name, email } = user;

Alternatively, if we want to use variable names which differ from the property names…

//this declares two variables, userName and userEmail
var { name: userName, email: userEmail } = user;

Which is functionally equivalent to:

var userName = user.name;
var userEmail = user.email;

Where is this useful? A common pattern is using objects to pass around large numbers of parameters, especially if the parameters are optional. That scenario is where destructuring shines:

function complex({ name, email, phone = null }) {
  //variables `name`, `email`, and `phone` are available here
}

var user = {
  name: 'foo',
  email: 'bar',
  phone: '123456'
};
complex(user);

Note we used destructuring in the function parameter list – it also works there, and even supports defaults! By doing this, we get a number of benefits:

  • We make the properties the object parameter requires explicit. A common issue is seeing a function takes an object, but not knowing what kind of object. Now that’s solved.
  • We can have defaults. No need to check if the property is there
  • We make optional properties explicit. By providing a default for a property, anyone reading the code sees the property is optional.

Explicitly visible things make code easier to maintain, as you don’t have to guess or read the whole function to figure it out. You can do many fancy things with destructuring. For comprehensive examples, you should check Scott Allen’s post on ES6 destructuring. Be careful to not take things too far. It’s possible to make your code harder to read with too much use of destructuring:

let { address: { home: { street } } = user;

//is equivalent to:
let street = user.address.home.street;

You can probably see the example without destructuring above is much easier to understand.

Object initializer shorthand

This feature allows you to skip repeating yourself in object literals. A pattern seen in the nodejs world:

module.exports = {
  someFunction: someFunction,
  otherFunction: otherFunction
};

Sometimes you also see the same with the module pattern:

var myModule = (function() {
  /* declarations here */

  return {
    someFunction: someFunction,
    otherFunction: otherFunction
  };
})();

Using ES6’s object initializer shorthand, we can rewrite it:

module.exports = {
  someFunction,
  otherFunction
};
var myModule = (function() {
  /* declarations here */

  return {
    someFunction,
    otherFunction
  };
})();

Again a feature without huge benefits, but reducing duplication is always a good thing.

Rest and spread parameters

Rest and spread parameters introduce new syntax for functions which take an arbitrary number of parameters, or when using arrays as parameters. In ES5, to write a function taking multiple parameters (such as Array#push)..

function push() {
  var args = Array.prototype.slice.call(arguments);
  var list = args.shift();

  args.forEach(function(a) {
    list.push(a);
  });
}

In other words, we need to use the arguments object, which is not ideal. We also can’t describe the function’s ability to take any number of args very easily without using comments. This leads to confusing code. Using rest parameters in ES6, we can instead write the following:

function push(list, ...values) {
  values.forEach(function(v) {
    list.push(v);
  });
}

This code automatically creates an array of all the parameters after the first, and the array is assigned to the variable values. This is much more readable at a glance: You can immediately tell this function can take any number of args. And even better, we don’t need the boilerplate for using arguments. Spread parameters is similar:

var values = [1,2,3];
var target = [];
target.push(...values);

The syntax with ...list above is same as this:

target.push(1, 2, 3);

Although a bit situational, this can be a useful feature in some cases.

Template literals

At simplest, template literals allow easy interpolation of variables into strings, and easier multiline strings.

var name = "Björn";

var text = `Hello ${name}`;
console.log(text);

The output would be “Hello Björn” as you might guess. Multi-line strings work as follows:

var text = `Foo
bar
baz`;

The more complex side of template strings is called “tags”:

var sample = foo`Some text here`;

In the above example, foo is a so-called “tag”, which are functions that can transform the string. For example, we can define a naive text-reverse tag..

function reverse(strings, ...values) {
  var result = '';
  for(var i = 0; i < strings.length; i++) {
    result += strings[i];
    if(i < values.length) {
      result += values[i];
    }
  }
  
  return result.split('').reverse().join('');
}

var foo = 'bar';
console.log( reverse`Hello World ${foo}` );

The output is “rab dlroW olleH”. A text-reversing tag is not very useful, could it be used for something else? As an example, we could have a tag to auto-escape SQL strings:

db.query(sql`SELECT * FROM x WHERE foo = ${parameter}`);

This is only scratching the surface, but template strings are a powerful feature and I hope library authors will make use of it in the future.

Promises

Promises are a way of dealing with asynchronous code. Code using promises can make asynchronous code easier to compose, and can also avoid the common issue of “callback hell”. Let’s look at a simple example to show why promises can be useful vs. callbacks. Say you have three asynchronous functions and you need to run all three, and then execute another function:

//for sake of example, we're just using setTimeout. This could be any asynchronous action as well.
function asyncA(callback) { setTimeout(callback, 100); }
function asyncB(callback) { setTimeout(callback, 200); }
function asyncC(callback) { setTimeout(callback, 300); }

asyncA(function(resultA) {
  asyncB(function(resultB) {
    asyncC(function(resultC) {
      someFunction(resultA, resultB, resultC);
    });
  });
});

Compare to an implementation using promises:

function promiseA() { return new Promise((resolve, reject) => setTimeout(resolve, 100)); }
function promiseB() { return new Promise((resolve, reject) => setTimeout(resolve, 200)); }
function promiseC() { return new Promise((resolve, reject) => setTimeout(resolve, 300)); }

Promise.all([promiseA(), promiseB(), promiseC()]).then(([a, b, c]) => {
  someFunction(a, b, c);
});

Promises allow easily composable asynchronous functions, without creating a callback-pyramids like in the first example. We do need a bit more code to create the promise in the first place, but if our asynchronous functions were longer, it wouldn’t be such a visible difference. This is only one of the advantages of using promises, and it’s a very broad topic. If you are unfamiliar with promises and their benefits, I recommend reading Kyle Simpson’s take on promises in his book You Don’t Know JS (free to read online). Promises can simplify asynchronous code a lot, but it can be hard to use them to their full potential. Check out my list of the best resources to learn about Promises for more.

Arrow functions

Arrows is a new syntax for functions, which brings several benefits:

  • Arrow syntax automatically binds this to the surrounding code’s context
  • The syntax allows an implicit return when there is no body block, resulting in shorter and simpler code in some cases
  • Last but not least, => is shorter and simpler than function, although stylistic issues are often subjective

The syntax is quite flexible:

//arrow function with no parameters
var a1 = () => 1;

//arrow with one parameter can be defined without parentheses
var a2 = x => 1;
var a3 = (x) => 1;

//arrow with multiple params requires parentheses
var a4 = (x, y) => 1;

//arrow with body has no implicit return
var a5 = x => { return 1; };

this binding

How often do you see something like this done in JS?

var self = this;
el.onclick = function() {
  self.doSomething();
};

This pattern crops up occasionally, especially in less experienced dev’s code. The solution is to use bind to fix this in the function, but it’s a bit verbose. With arrows, we can instead just do this:

el.onclick = () => this.doSomething()

Implicit return

The arrow syntax allows two different styles… With a statement body:

el.onclick = (x, y, z) => {
  foo();
  bar();
  return 'baz';
}

//equivalent to:
el.onclick = function(x, y, z) {
  foo();
  bar();
  return 'baz';
}.bind(this);

A statement body allows multiple statements as shown above. An arrow function with an expression body looks like the example we saw earlier:

el.onclick = (x, y, z) => this.doSomething()

//equivalent to
el.onclick = function(x, y, z) {
  return this.doSomething();
}.bind(this);

An expression body allows only a single expression, and has an implicit return. This means it’s great for functional-style code, for example when using Array#map or Array#filter

//ES5 style
var names = users.map(function(u) { return u.name; });

//ES6 style
var names = users.map(u => u.name);

ES6 modules

The CommonJS module specification has become increasingly common. First, Node.js adopted it, starting the downfall of the competing AMD and require.js module specifications. Recently tools like Browserify and Webpack have made CommonJS modules the best choice for JavaScript code running in the browser as well. The native support for ES6 modules is still lacking, but thanks to the tools mentioned above, we can easily use the ES6 modules with our JS code. Here’s a comparison of how ES6 modules are defined vs CommonJS modules:

export const magicNumber = 42;

export function amazingFunction() { return 'the magic number is ' + magicNumber; }

//vs CommonJS...
const magicNumber = 42;

function amazingFunction() { return 'the magic number is ' + magicNumber; }

module.exports = { magicNumber, amazingFunction };

The ES6 module version allows us to write our module with some less repetition – anything we define as being exported is also available within the module itself. In the example with CommonJS, we need to define the value first, and then separately define the export using module.exports. The syntax for importing modules is also slightly more concise compared to CommonJS:

import { magicNumber } from './my-module';

//vs CommonJS...
const { magicNumber } = require('./my-module');

There’s a number of additional options available with ES6 modules. Exploring ES6’s chapter on Modules is a good resource to learn more.

Iterators and Generators

Another new feature is iterators: you can make “iterable” objects, as in similar to how you can iterate through arrays using loops. You do this either with a new syntax called symbols, which allows for special object properties with special functionality, or with another new feature called generators. Generators can yield values. The function’s execution pauses at the yielded value, and the next time the generator is called, it resumes from where it left off. This can also be used for dealing with asynchronous code in another interesting way, but I’ll talk about that in another article as it’s a big topic on its own. For working with iterators, ES6 also provides a new looping syntax called for-of:

var arr = [1, 2, 3];
for(var value of arr) {
  console.log(value);
}
//output: 1, 2, 3

This is similar to how foreach-loops work in other languages. Another similarity with foreach is that this also works with iterators, so you can use your own iterable objects with for-of. Iterators are mainly useful for library authors. It could be useful to offer an iterator-based interface for a library, but in most circumstances you won’t need them.

In closing

I’m sure you’re asking now “What about the new class syntax! ES6 has the new class syntax, right?” – well, that’s correct. However, the class syntax is only syntactic sugar over JavaScript’s prototypal OOP. It doesn’t change anything about how the system works, it merely provides some convenience if you prefer that style. There aren’t really any benefits from the syntax over just working with plain objects. The only case where the class syntax could be useful is with heavy inheritance, but it’s often better to use composition instead. This is a big topic on its own, and outside the scope of this article. Overall the new features in ES6 provide a number of benefits especially for larger applications. If you don’t need to support older browsers, then you’ll have a fairly easy time since ES6 features are well supported across recent browsers. For older ones, you may need to use Babel to compile the code into something that works. Kangax’s ES6 compatibility table is a good resource to use if you’re not sure what you need.

, ,

Introduction to Data Binding with MobX

Once you get past very simple applications, programming on the web can become a nightmare of event handling and notifications, where the state of an application is spread out among dozens of different text boxes, select boxes and similar components. This is one reason why Model/View/Controller architectures (MVC) have become pretty much de rigour (along with multiple variations on this theme) in web programming.

However, MVC also requires that when you change the model, the view will change in response. This is pretty easy to accomplish when there is a direct one-to-one relationship between a component and its associated value. Where things begin to fall apart is when multiple components are dependent upon the same set of values, or when changes in values change other values that have component dependencies. This is a behavior you see quite often with spreadsheets (and one reason why translating spreadsheets into web applications can be quite a headache).

Mobx and MVC

The Mobx library makes use of ES2015 and (with later version) ES2017 decorators in order to identify specific variables or objects and make them “observable”. What this means in practice is that the framework “keeps track” of these variables, and any time the variables change, then the a notifier is activated for handling the impacts of these changes.

An example of this can be seen in the following CodePen.

See the Pen MobX+React test by Kurt Cagle (@kurt_cagle) on CodePen.

This example is deliberately kept simple to illustrate the process. Here, you can change a person’s first or last name, or change their age by using a numeric input control. This data is kept within a particular data structure, when either part of the name is changed, a new variable called flippedName is calculated, which holds an alternative medium state (in this case the name given as “lastName, firstName”). Finally, if the age of the person is 18 or higher, the flipped name appears green – the person involved can participate in whatever activity is being supported. If the age is under 17, however, the flipped name turns red, and a warning message is posted.

This example is especially useful because the data is entangled – the dispay of the output text is dependent upon both the names and the age. Moreover, the input fields make it possible to update the model, showing a “round trip” type activity that is common with MVC type applications.

Dipping into the code, the first few lines take advantage of the Babel transpiler to implement the ES2017 decorator capabilities. Decorators are pre-process directives that perform “meta-operations” on code, and are in effect the equivalent of “aspect” programming used in languages like Java. These can be used to automate logging, to set up services from functions and, in the case of mobx, to identify and manage variables and objects to be watched.

Explore React Courses

The @observable decorator is syntactic sugar for the older ES2015 implementation mobx.observable(...). This is not a function in the traditional sense. Instead, observers act on functions and expressions of code prior to them actually being evaluated, deferring the actual evaluation until some context structures can be set up.

class Person {

@observable firstName;

@observable lastName;

@observable age:number;

constructor(_firstName,_lastName,_age){

this.firstName = _firstName;

this.lastName = _lastName;

this.age = _age;

this.bind("firstName");

this.bind("lastName");

this.bind("age");

}

@computed get flippedName() {return `${this.lastName}, ${this.firstName}` }

In this case, three properties of a given class are identified as being observable – firstName, lastName and age. This means that, when an instance of this is created, then the instance members will be observable.

The bind() function in this class is not directly mobx related. Instead, it establishes a simple binding between an input element with an id that has the same name as the variable in question. That way, if you change an input field, you also change the model, and by extension change any functionality that depends upon the variable being changed.

bind(prop,defaultValue){

document.querySelector(`#${prop}`).value = defaultValue!=null?defaultValue:this[prop];

document.querySelector(`#${prop}`).addEventListener("input", (evt)=>{this[prop] = evt.target.value});

}

An area where mobx really comes in handy is for those scenarios where you want to make computed properties. A computed property is one that has a dependency upon observable properties – when you change the observable, you also change the computed value. Here, the first and last names are inverted to create a “lastname, firstname” type string in this read-only getter. By using the @computed decorator, should the independent variables (firstName or lastName here) change, then the @computed getter is re-evaluated.

This is by itself actually a huge benefit that mobx provides. While for something like inverting name takes comparatively few cycles to perform, when you have complex structures, regular expressions, template strings, asynchronous calls or similar processes, not having to rerun a getter when nothing has changed can result in huge cycle and memory savings. The @computed decorator feature right here is well worth the price of admission to Mobx.

The mobx.autorun() decorator is one of the few that doesn’t have an associated @ property. It is one of the big workhorses of Mobx, however. Whenever an observable or computed property is changed mobx.autorun is called IF the enclosed expressions have dependencies upon those variables.

In the sample codepen, I define three “render” methods. The first displays the flipped label. The second changes the color of the inverted title from green to red if the age given is below 18, while the final method adds a warning beneath the input fields indicating when a person is too young to participate in the program.

There are three such mobx.autorun() statements, one that calls each of these functions respectively. When a user changes the first name using the input, the showLabel() and warn() functions are invoked. If they change the age, the redLabel() and warn() functions are invoked. Finally, if the last name is changed, then only showLabel() gets invoked. Why? The showLabel() function has a dependency on the first and last name, while warn() uses only the first name, and redLabel() has no dependency at all upon the last name.

The advantage of this should be obvious, especially with complex forms or applications. If a component is unchanged, then it should not be necessary to re-render it, especially when there are a lot of interdepencies acting upon that component.

In that respect, the relationship between MobX and React should be obvious. MobX creates a way to indicate when the broader (global) data model changes, notifying downstream functions when independent variables and automatically computing @computed values that can then reduce the overall computational cost. React maintains a data model at the component level, so that when state variables or attributes change, only those portions of the component dependent upon those changes gets updated.

This article focused on the basic functionality of mobx. A subsequent article will focus will look at how you can use mobx and react together to keep the total amount of unnecessary work for your application to a minimum.

Explore React Courses

, , , ,

230 Curated Resources and Tools for Building Apps with React.js

This post will curate the best resources, tools, libraries, and articles that will help you learn to build production applications with React.js. This 6000 word post will take you from getting started with React, through UI design, routing, testing, deployment, and continuous integration. There are many sections and you should feel free to jump to the resources you need.
Getting Started
+ Demos and Apps
+ Tutorials and Articles
+ Video Tutorials and Courses
+ Community
+ Boilerplates
+ UI Components
+ UI Libraries and Frameworks
+ Routing
+ State Management
+ Other Useful Libraries
Development Tools
+ Text Editors
+ Build Tools
Testing
+ Articles
+ Utilities
+ Automated Backend Testing Services
Performance
+ Articles
+ Tools
+ Libraries
Deployment
+ Continuous Integration Articles
+ Continuous Integration and Deployment Software
+ Cloud Server Provider
+ Continuous Integration in React Apps
Resources for Further Learning
+ Articles and Tutorials
+ Courses
+ Books
+ Talks and Conferences
+ More React Resources

Explore appendTo’s React Courses

Getting Started

First off, let’s start at the very beginning. This section assumes you have zero-knowledge on React and have at least a solid foundation on JavaScript basics.

Demos and Apps

You already know that you want to learn React (that’s why you’re here right?). But a good first step when learning about a new technology is to know what’s possible with it. And the best way to go about that is to check out demos and existing apps that have been built with it.

Demo Apps

Production Apps

Tutorials and Articles

Now that you know what’s possible with React, it’s now time to take a look at how you can get started learning it.

If you’re the type of person who wants to have a general idea on how a specific technology works, then ReactJS for Stupid People is a good place to start. It talks about what React is, what you can do with it, its limitations, and whether you should use it for your future projects or not.

If you’re like most people, you either came from a jQuery or Angular background before you came to know about React. Tutorials which uses a well-known library as a point of reference in learning something new is a good way to understand how things are done in that new technology. Being able to translate what you’re used to doing in an older technology to and apply it to a new one can be very empowering to new developers who are just trying the waters.

Now that you have an idea on how React works, it’s now time to dive into the core React concepts. Taking the time to understand the core concepts first before trying to write even a single line of code can really go a long way when learning React, and in fact (news flash coming up) any other new technology that you’re trying to learn. This will make the code that you see in React tutorials “click” faster. It also ensures that you won’t just end up copy-pasting the code from these tutorials. Having a good understanding of the core concepts enables you to distinguish how a specific thing works when you see them in action. So without further delay, here are a few tutorials you can read in order to understand the core concepts behind React:

Video Tutorials and Courses

Free Courses

  • Egghead.io: React Fundamentals – this series will explore the basic fundamentals of React to get you started.
  • Mindspace: ReactJS Basics – teaches the basic concepts of React.
  • Learn ReactJS – if you want a more hands-on React course, this one is for you. Aside from the usual “getting to know the syntax” part, they also have projects and quizzes to make sure you really understand what you learned.
  • ReactJS Program: React.js Fundamentals – uses a combination of tutorials, video tutorials and a project that you will build throughout the whole course.

Paid Courses

If you have some cash to spare, consider enrolling on the following courses:

  • Powering Up with React – a combination of video tutorials and hands-on exercises to get your hands dirty in using React.
  • React for Beginners – a course by Wes Bos, a Full Stack Developer, Speaker and Teacher from Canada. The course is a bit pricey but it will be worth it, because this course covers all there is to know about the fundamentals of React.js. Each video tutorial is really concise, very engaging and most important of all, it’s not sleep-inducing.
  • React.js: Getting Started – learn the basics of React.js, and build an in-browser, math skills kids’ game from scratch with it.

Community

Now that you’ve begun your journey in writing React code, and maybe have followed through a tutorial or two.

In your journey in learning React, there will always be a time wherein you get stuck with a specific bug or error in your code. Often times simply searching for that specific error on Google would help. But what if there’s no error at all? Or Google doesn’t really return useful results. In those cases what you need is a community. Most of us already know Stackoverflow. Most of the search results that you see on Google when you search for a specific error are almost always from Stackoverflow. But aside from Stackoverflow there are other good places where you can get help and talk about React stuff in general.

Now that you have an idea how React works, its core concepts and how to build things with it, its now time to take things further by learning about the tools which you can use while developing apps with React.

Boilerplates

A boilerplate is a useful tool for quickly getting started with a React project. As you might have already found out using the resources given above, the React code (JSX) that you write can’t actually be executed by the browser. This means that it has to go through a compilation process before the browser can understand it. The compiler accepts your JSX code and spits out the plain JavaScript code that’s readable by the browser. This is where boilerplates comes in. One of the tools which comes with a boilerplate is the build tool, which is responsible for compiling your JSX code.

To put it simply, boilerplates comes with a collection of tools and libraries that are commonly needed in developing React apps. Examples of such tools are build tools, test runners, and libraries for routing and state management.

  • Create React App – if you want to quickly get started writing React apps without worrying too much about the build/compile process, this is the way to go. In my own opinion, this is the only beginner-friendly boilerplate among this list.
  • React Starter Kit – if you’re looking for a boilerplate that allows you to easily set up not just the front-end but the back-end as well, this boilerplate is for you. It is built on top of Node.js, Express, GraphQL, React.js, Babel 6, PostCSS, Webpack, and Browsersync.
  • React Boilerplate – a production-ready boilerplate for starting out React projects. Highly focused on performance and best practices.
  • React-Redux Starter Kit – if you want a boilerplate which has minimal features and isn’t too opinionated about how to do certain things (project structure, build configuration) then this one is for you.

Those are just a few of the boilerplates that allows you to get started with your React projects quickly. Note that it’s not a requirement to use these boilerplates. Sooner or later you’ll find out that they’re either too rigid or too hard to customize. This is because some boilerplates can be too opinionated about how to go about things. Once you’ve tried using one or two boilerplates, you’ll pretty much have an idea on how to build your own. Every project is different so building your own boilerplate makes sense, since you only include things as you need them. This also adds up to your productivity later on, as you no know exactly where to look when you need to customize things.

UI Components

The main idea for using React is to be able to create UI components that can be reused anywhere in your app. Since React is a pretty popular library, developers and designers around the world have already created a lot of useful components that can be used in most projects. This means that you don’t need to write everything from scratch. Most of the components that you might need in your project might have already been written before.

In this section, let’s look at some useful components which you can use in your projects.

Those are just some of the components which you can use on most projects. If you need to find a custom component, you can check out the following component curators:

If you’ve looked through the curators above, you’ll notice that each component either points out to one of these two sites:

  • Github – hosts the source code for the components.
  • NPM – package manager that enables developers to install the components locally.

This means that you can actually directly search on Github or NPM for your React components and libraries.

UI Libraries and Frameworks

If you want your apps to have a standard look and feel, a good place to start is by picking a UI library or framework. Libraries and frameworks comes with a set of components with the same theme. Each of them comes with a different set of components and a different way of doing things, so you have to choose which one fits your needs and your values.

  • Material-UI – React components that implements Google’s Material Design.
  • Ant Design – a collection of components that follows Ant Design, a design language for creating user friendly and beautiful websites.
  • React Bootstrap – the Bootstrap framework re-implemented using React.
  • Rebass – a collection of 57 Configurable React Stateless Functional UI Components.
  • React Toolbox – similar to Material-UI in that it also implements Google’s Material Design. The only difference is that it uses css modules intead of inline styles.
  • Elemental UI – a UI Toolkit for React.js Websites and Apps. If you’ve used Bootstrap before, the look and feel of their UI is similar to Bootstrap’s.
  • Grommet – an accessibility-focused framework for creating amazing user experience.
  • Belle – Configurable React Components with great UX.
  • Cx – a modern framework for building visually appealing, data-oriented, web applications.
  • Reusable Components by Khan Academy – useful components from Khan Academy.
  • VistarMedia Components – a collection of React components from VistarMedia. The components has the same look as Bootstrap.
  • React Topcoat UI – if you’ve used the Topcoat CSS framework before and you want the same look and feel for your React app.

Explore appendTo’s React Courses

Routing

Routing is an important part of every application. It keeps the UI in sync with the current URL that is being accessed by the user. For example, when http;//myapp.com/#user/1 is accessed, the UI will automatically update to show the page being asked.

Here are some of the routing libraries that you can use with React:

  • React Router – the De facto routing library for React. In the beginning, this is what you want to use as it includes all the bells and whistles that you need to start experimenting with routing.

Once you’re acquainted with React Router, you might notice that there are some features that you don’t really need, or you don’t really like the way it does things. Here are a few alternatives that you might want to check out:

  • React Mini Router – if you don’t want your routing solution to consume that much space, you can use this library instead. It has a few external dependencies and only becomes 4kb when gzipped.
  • React Router Component – a declarative router component for React.
  • Universal Router – A simple middleware-style router that can be used in both client-side (e.g. React, Vue.js) and server-side applications

  • router5 – a framework agnostic routing solution.

State Management

Another important part of any application is how you manage the state. At this point, we already know that each component can have their own state. This works for really small applications because you can just pass the state from one component to another by means of props. But for real-world apps, you need a way to make the state accessible throughout the whole app. Especially the one’s that are “global” by nature (e.g. settings). This is where state management comes in. React doesn’t come with this kind of functionality, but thankfully there are libraries that allows you to manage global app state in a sane manner.

Redux is one such library. Redux allows you to have a global state for your app so that the different components in your app can communicate with each other. Note that Redux isn’t specific to React, so you have to install React Redux as well so that you can easily work with Redux within the React environment. After learning plain React, Redux is the second step. Here are some resources that will help you learn it:

Free Resources

  • A Cartoon Guide to Redux – this is a great read if you want to know about the different components that make up Redux and how they work together. The visual can really help you in understanding the different concepts better.
  • Learn Redux – from the same guy who created the React for Beginners course. This course will teach you how to create an Instagram clone using React.js, Redux and React Router.
  • Getting Started with Redux – a course from the creator of Redux himself, Dan Abramov. If you’re looking into learning the nitty gritty details of using Redux, this is the course for you. Because it will not only teach how to use Redux within a React app, it will also dive into the details of using the different tools available in Redux.
  • Building React Applications with Idiomatic Redux – in this course you will learn about the production-ready techniques for building React and Redux applications.

Paid Courses

  • Modern React with Redux – learn the basics of React, Redux as well custom components such as Google Maps and charts by developing an app.
  • Advanced React and Redux – learn how to implement authentication, test components and use middlewares.
  • Building Applications with React and Redux in ES6 – an all in one course that shows you how to setup your environment for React development, teach you the basics of React and Redux, and how to test React components and your Redux code.

Redux is pretty much the De facto standard library for managing state in React apps. But that doesn’t mean that you can’t choose to use other solutions.

Other Useful Libraries

Here are other React libraries that you may find useful:

  • React Icons – use popular icon sets (e.g. Fontawesome, Octicons) in React.
  • React i13n – allows you to include instrumentation (analytics) to your app.
  • Omniscient – provides abstraction for React components that allows for fast top-down rendering. This uses immutable.js for immutable data.
  • Search Kit – a collection of UI components for creating beautiful search applications using ElasticSearch.
  • React Motion – an animation library.
  • React Forms – provides a set of tools for React to handle form rendering and validation.
  • react-intl – provides React components and an API to format dates, numbers, and strings, including pluralization and handling translations.

Development Tools

As you’re using React, Redux and other libraries you’ll notice that there are things that you need to do repeatedly. Namely writing out common React functions and debugging your code if something goes wrong. In this section we’ll look at some of the tools that you can use to ease up your React development.

Text Editor

Once you’ve gotten used to the React syntax, it’s high time you install plugins that will help you to easily write React specific code. Two of the most popular one’s are Atom and Sublime Text, so we’re going to look at specifically these two. You can start the tooling journey by reading one of the articles below:

Build Tools

Once you’re happy with your text-editor setup, you need to get acquainted with a build tool. If you’ve checked out the Boilerplates section earlier, you might have already introduced yourself to one such build tool: Webpack. Build tools play a role in the development, testing and deployment phase of your application. Here are a few points just to give you an idea on what build tools does:

  • They accept your JSX and ES6 code and spits out JavaScript that’s readable by the browser.
  • They compile all your modules together into a single file that can be linked into your page.
  • They listen to source code changes and use either live reloading or hot module replacement to update the preview of your app in the browser.
  • They run your tests.

Now you know that there’s no escaping build tools when it comes to React development. Of course, in the beginning you can use Create React App and it will handle the compilation of your React code for you. But as soon as you get out of the “beginner zone”, the next thing that you need to learn is how to use a proper build tool. Here are some resources that can help you with that:

Note that Webpack isn’t the only build tool out there. There are lots of other tools that you might want to check out. Webpack is pretty much the De Facto standard when it comes to React apps, that’s why it’s the one that I introduced.

Debugging

Next you need to up your debugging game. That means no more using console.log when you’re trying to find out the cause of an issue.

  • React Dev Tools – allows you to inspect a React Renderer, including the Component hierarchy, props, state, and more. This tool is currently available on Chrome and Firefox.
  • React Inspector – allows you to inspect data in your React apps ala Chrome Dev Tools.
  • Redux DevTools – allows you to inspect state and action payload as they happen. Actions can also be cancelled so you can see the previous state before the action was fired.
  • Reactotron – an OS X app for inspecting your React JS and React Native apps.

Once you’re productive in using your newly found tools. You can start looking for other tools that can help you in developing React apps. Here are a few that you might want to start with:

  • React Storybook – a UI development environment for your React components. It allows you to visualize different states of your UI components and develop them interactively.
  • React Styleguidist – a style guide generator for your React components.

If you want more, Facebook has compiled a list of tools that you can use while developing in React:

Testing

In order to ensure that your code works as expected, you also need to perform tests. Three of the most common one’s are unit tests, functional tests and integration tests. If you’re not aware of any of these, I recommend you to read this article by Eric Elliot on JavaScript Testing: Unit vs Functional vs Integration Tests. That article will teach you everything you need to know about those three types of tests, why they are important, and it will also show some sample codes for each type. Testing also plays a huge role in Continuous Delivery, which is tackled in the Deployment section. Which is why testing plays a very important in the deployment of quality software.

Below are some resources that you can use to get started with your testing adventure. Note that a few of these are for testing JavaScript code in general, not just testing your React code. This is because testing should be holistic. The entirety of the app needs to be tested, so that you get the full benefit.

Testing Articles

  • Writing Testable JavaScript – shows you organize and write your code so that it can be easily tested. This uses Mocha as the test framework, Chai as the assertion library, and jQuery to verify the contents of the page. There’s also a similarly named article which is a good read as well.
  • A Gentle Introduction to JavaScript Test Driven Development – the first part of a three-part series that teaches you how to get started with TDD in JavaScript. In this tutorial, you will be building a simple application which in which you apply TDD. This means that not only do you get to see how to test code, you also get to see the decisions behind why a specific code is written in that specific way.
  • Unit Testing and TDD in Node.js – shows you how to get started in unit testing your Node.js code using Mocha, Chai and Sinon.

Once you have a good feel on how to do unit testing in JavaScript, the next step is to actually apply in your React apps:

Testing Utilities

These are the testing tools that are mentioned in the articles above:

  • Jest – a test runner.
  • Enzyme – a testing utility for React.
  • Mocha – a test framework for JavaScript projects.
  • Nightwatch.js – a functional testing tool. It verifies that the functionality of your app work correctly based on the user’s point of view.

Automated Backend Testing Services

You can use any of these two services for manual and automated cross-browser Selenium testing:

Performance

Now that you’re sure your components really do what you intend them to do. It’s now time to start looking at how to improve the performance of your React apps. Note that in most cases you don’t really need to check the performance of your app. Especially if it’s just a fairly standard app. However, if you have very complicated views you may start looking into your app’s performance. Here are a few signs that your app needs to have a performance evaluation:

  • It needs to work with lots of data.
  • Multiple parts of the app is updated at the same time.
  • It has lots of user interactions which updates the views.

Performance Articles

The following articles will give you an idea on how to get started in performance debugging your React app:

Performance Tools

Here are the tools that you could use for debugging the performance of your React apps:

  • ReactPerfTool – used for debugging the performance of your React application in a visual way.
  • React Render Visualizer – a visual way to see what is rendering and why. Each component is highlighted when they are mounted or when they are updated.
  • Why did you update? – a function that monkey patches React and notifies you in the console when potentially unnecessary re-renders occur.

Explore appendTo’s React Courses

Performance Libraries

There are also some libraries that you can use for optimizing performance:

  • React Static Container – renders static content efficiently by allowing React to short-circuit the reconciliation process.
  • React Fast Click – automatically adds fastclick touch events to elements with onClick attributes (and those that require special functionality, such as inputs) to prevent the delay that occurs on some touch devices.
  • react-lazyload – used for lazyloading components, images, and other parts of your React application.
  • React Infinite – used for optimizing the performance of infinite lists.
  • react virtualized – a collection of React components for efficiently rendering large lists and tabular data.
  • Inferno – an extremely fast, React-like JavaScript library for building modern user interfaces.

Deployment

Finally we get to deployment. This is where you set up continuous integration and deployment. If you’re new to these concepts, continuous integration is a development practice where developers frequently push code into a shared repository (e.g. Git, Mercurial). All the codes are then automatically tested (e.g. unit tests, integration tests) on a staging server. If there are errors and other problems with the code, they’re immediately reported to the developers. All of this is orchestrated by a continuous integration software such as Jenkins. Once the errors are made known to the developers, they can immediately fix the issue and push the updated code. Once all the tests passes, the current build is automatically pushed to the production server.

Continuous Integration Articles

If you’re new to continuous integration, have a read at the following articles:

Continuous Integration and Deployment Software

Now that you know all about the steps involved in continuous integration, it’s now time to pick a continuous integration service. What you pick should be based on the needs of your specific project. For example, if you use pull requests in Github to keep track of a specific change and review the code. You should pick a CI service that can do that.

Here are a few continuous integration services that you can use:

If you want to host your own, you can use the following open-source CI servers:

Cloud Server Provider

React apps are just your ordinary web apps so you can use your existing cloud server provider for deploying:

Continuous Integration in React Apps

After you’ve learned the basics of Continuous Integration, decided which CI service, and picked a cloud server provider to use. The next step is to apply what you’ve learned and actually deploy your React application.

Since day 1 we all know that React doesn’t exist alone. There are other components that may be used in your code. That also includes your back-end code, which is most commonly Node.js. But others might also be using PHP, Ruby, Python or any other server-side language. This means that you should include those in your tests as well.

As you have already learned, the most important part of continuous integration is the testing process. First you test your code locally, and if it passes, you push it to the staging server for another set of tests. If it fails, you go back to step 1 until such time that all the tests passes. Once all the tests passes, only then is the code pushed to production.

But how specifically can we set this up for React applications? Well, by now you should already be proficient in using Webpack, Browserify, or any other module bundler that you decided to use. So it’s only a matter of figuring out how to automatically run tests when you push changes to your staging server, have the CI server generate a report on the results of the test, and automatically push the code to the production server when all the tests passes.

A huge part of your deployment process is handled by the build and testing tools of your choice. As you’ve learned earlier, Webpack is the one that’s most commonly used in React apps. So it is used together with the testing tools to ensure that the app has no errors. If you’ve skipped the Development Tools part, now is a good time to read through that.

Here are a few resources that can help you in filling the blanks. Note that most of these talks about the back-end since there are only a few apps that are purely client-side:

Resources for Further Learning

Now that you’ve learned all of the process involved in developing apps with React, you can now sleep peacefully at night. Or not, because just like everything in life, you never actually stop learning. There’s always something new to learn. This is more true in a field like web development because there’s always something new to look forward to everyday. New frameworks, new libraries, new best practices.

So in this section I’ll provide some resources to get you started in learning some more React stuff.

Articles and Tutorials

Those are just a handful of articles that you ought to read if you want to level up your React skills. And because the web industry constantly moves forward, you can expect things to change in a month or two. Meaning the articles that I’ve linked above might become outdated. So the best way to keep yourself updated is to occassionally check out blogs about React. Medium is a good place to start, because it is where developers gather to share their experiences in building apps with React:

Courses

Explore appendTo’s React Courses

Books

Free

Paid

If you want more, the author of the React book that I mentioned earlier has also compiled a list of books on React:

Talks and Conferences

The React website also compiles videos from the community:

If you want more, there are React conferences around the world which uploads their talks on Youtube:

Again, the React website compiles a list of conferences about React. So if you’re looking into attending a React conference, you can check out this page occassionally:

Videos from previous conferences are also linked in there if they’re available. So even if you can’t personally attend, you can still learn something.

More React Resources

If you’re still hungry for more, check out the following awesome lists on Github:

Conclusion

In this post, you learned all about the things involved in creating a React app. Hopefully this post has helped you in your journey to become a full-fledged React developer.

, ,

ES6 Modules: Use Cases and Examples

Modules are an important part of any programming language. All prior JavaScript versions have lacked this feature. But that did not stop the community from creating their own modularized code. ECMAScript 2015 (ES6) has finally introduced modules as a fully realized function into JavaScript. Modules are now fully naturalized citizens of the JavaScript programming language. Their function has been to employ compact syntax and Asynchronous module loading functions.

This article will give you a review of how JavaScript Modules came to be, coding examples and how to transpile your ES6 modules to ES5, in order to work in current browsers.

 Basis for Modules
The most commonly used platform for JavaScript is the web browser. By design it executes its code in a fully uniform global context. The problem programmers run into, is the ability to write compact code while avoiding naming conflicts. The basis of the problem comes down to keeping your code organized and not conflicting with preexisting variables.

In the past, JavaScript applications were partitioned in files while building in real time. In order to overcome this, users and the broad community of JavaScript starting wrapping files in an IIFE which is a function that runs right as it’s defined.

(function() { ... })();

This type of construction creates a local area and was the basis for module introduction and creation in JavaScript. ES6 has now formalized the concept and properly implemented the feature and made it official.

ES6 Module Syntax

In ES6, every module is now defined inside a separate individual file. All functions, variables or actions are defined inside the module and will not be visible or called upon unless the programmer exports the code. A programmer now has the possibility to write code inside the module that won’t affect other parts of the application unless explicitly told to do so.

As each ES6 module is defined in its own file, it is important to know the functions or variables defined in a module are not visible outside. This means that you can write code in your module and only export those values when you want it to be accessed by other parts of code. Other parts of your application will be able to utilize this protected module code and access it when a programmer deems fit.

The nature of modules then calls for two keywords that will allow you to export the module code and then take in exported variables. The respective keywords are export and import.

Module Creation

We’re going to create simple module with basic JavaScript to display the module in action. The first order of business is to create a separate .JS file, for the example’s sake it will be called multiply.js.

The function is going to create a random number generator that also multiplies two different variables. One function will be a standard random generator called randomNum() followed by a declared multiplication function called mult (X, Y). Pay attention to the last line of code. The following code as a module will look like this:

javascript
// multiply.js
function randomNum() {
return Math.random();
}

function mult(X, Y) {
return X * Y;
}

export { randomNum, mult }

The export keyword line is what allows for the code to be put into a larger file of an application. If you were take this into the main.js, then it would be called with the following line of code:

// main.js
import { randomNum, mult } from 'multiply';

console.log(randomNum()); // Displays random number. 
console.log(mult(2, 5)); // 10 

Importing the module can can allow you to choose only one or a specific amount of functions from the exported module. For example if you wanted to only pull out the randomNum() function, the code would look like this:

import { randomNum } from ‘multiply’;

That is the crux of module creation and implementation in ES6. Programmers will find that using the latest features of a programming language will not always be compatible with the latest of browsers. The way to get past this is through using a transpiler.

Finding an ES6 Transpiler

It used to be a risky endeavor to use new JavaScript before they became localized and standard across major browsers. An incompatible browser could make your code unable to be used. Now, that is no longer an issue as you can use Babel as a transpiler to convert your ES6 modules into JavaScript that is currently understandable for today’s modern browsers. Eventually, these modules will be natively read by the browsers and you can skip this step all together.

Overall Benefits of ES6 Modules

ES6 modules allow for new features that can’t be added by an external library. A small syntax and static structure can be more widely used causing overall optimization and more. It also allows for fragmentation in the JavaScript community, as multiple ways to create modules have been created over the years. There has been no uniformity to the process until now.

Math or JSON were simple namespaces in past versions of JavaScript, now they have full range functionality when placed to create a module.There is now a native standard for modules that is imbued into the language itself, programmers will be able to quickly use a single method benefitting them tremendously. ES6 Modules are incredibly powerful and will pave the way for future advancements in the language.

, , , , , ,

History and Background of JavaScript Module Loaders

Application logic for web apps continues to move from the back end to the browser. But as rich client-side JavaScript apps get larger, they encounter challenges similar to those that old-school apps have faced for years: sharing code for reuse, while keeping the architecture separated into concerns, and flexible enough to be easily extended.
One solution to these challenges has been the development of JavaScript modules and module loader systems. This post will focus on comparing and contrasting the JavaScript module loading systems of the last 5-10 years.
It’s a comprehensive subject, since it spans the intersection between development and deployment. Here’s how we’ll cover it:

  1. A description of the problems that prompted module loader development
  2. A quick recap on module definition formats
  3. JavaScript module loader roundup – compare and contrast
    1. Tiny Loaders (curl, LABjs, almond)
    2. RequireJS
    3. Browserify
    4. Webpack
    5. SystemJS
  4. Conclusion

The problems

If you only have a few JavaScript modules, simply loading them via <script> tags in the page can be an excellent solution.

<head>
 <title>Wagon</title>
 <!-- cart requires axle -->
 <script src=“connectors/axle.js”></script>
 <script src=“frames/cart.js”></script>
 <!-- wagon-wheel depends on abstract-rolling-thing -->
 <script src=“rolling-things/abstract-rolling-thing.js”></script>
 <script src=“rolling-things/wheels/wagon-wheel.js”></script>
 <!-- our-wagon-init hooks up completed wheels to axle -->
 <script src=“vehicles/wagon/our-wagon-init.js”></script>
</head>

However, <script> establishes a new http connection, and for small files – which is a goal of modularity – the time to set up the connection can take significantly longer than transferring the data. While the scripts are downloading, no content can be changed on the page (sometimes leading to the Flash Of Unstyled Content).  Oh yeah, and until IE8/FF3 browsers had an arbitrary limit of 2 simultaneous downloads because bad people back in the day were bad.
The problem of download time can largely be solved by concatenating a group of simple modules into a single file, and minifying (aka uglifying) it.

<head>
<title>Wagon</title>
<script src=“build/wagon-bundle.js”></script>
</head>

The performance comes at the expense of flexibility though. If your modules have inter-dependency, this lack of flexibility may be a showstopper. Imagine you add a new vehicle type:

<head>
<title>Skateboard</title>
<script src=“connectors/axle.js”></script>
<script src=“frames/board.js”></script>
<!-- skateboard-wheel and ball-bearing both depend on abstract-rolling-thing -->
<script src=“rolling-things/abstract-rolling-thing.js”></script>
<script src=“rolling-things/wheels/skateboard-wheel.js”></script>
<!-- but if skateboard-wheel also depends on ball-bearing -->
<!-- then having this script tag here could cause a problem -->
<script src=“rolling-things/ball-bearing.js”></script>
<!-- connect wheels to axle and axle to frame -->
<script src=“vehicles/skateboard/our-sk8bd-init.js”></script>
</head>

Depending on the design of the initialization function in skateboard-wheel.js, this code could fail because the script tag for ball-bearing wasn’t listed between abstract-wheel and skateboard-wheel. So managing script ordering for mid-size projects got tedious, and in a large enough project (50+ files), it became possible to have a dependency relationship for which there wasn’t any possible order that would satisfy all the dependencies.

Modular programming

Modular programming, which we explored in a previous post, satisfies those management requirements nicely. Don’t head out to celebrate just yet though – while we have a beautifully organized and decoupled codebase, we still have to deliver it to the user.
The stateless and asynchronous environment of the web favors user experience over programmer convenience. For example, users like it when they can start reading a web page before all of its images have finished downloading. But bootstrapping a modular program can’t be so tolerant: a module’s dependencies must be available before it can load. Since http won’t guarantee how long that fetch will take, waiting for dependencies to become available gets tricky.

Javascript Module formats, and their loaders

The Asynchronous Module Definition (AMD) API arrived to solve the asynchronous problem. AMD takes advantage of the fact Javascript is processed in two phases: parsing (interpretation), when the code is checked for syntax, and execution, when the interpreted code is run.

At syntax time, dependencies are simply declared in an array of strings. The module loader checks if it has that dependency loaded already, and performs a fetch if not. Only once all the dependencies are available (recursively including all dependencies’ dependencies) does the loader execute the function portion of the payload, passing the now-initialized dependency objects as arguments to the payload function.

// myAMDModule.js
define([‘myDependencyStringName’, ‘jQuery’], function (myDepObj, $) { ...module code...

This technique solved the file ordering problem. You could again bundle all your module files into one big fella – in any order – and the loader would sort them all out. But it presented other advantages too: there suddenly became a network effect to using publicly hosted versions of common libraries like jQuery and Bootstrap. For example, if the user already had Google’s CDN version of jQuery on their machine, then the loader wouldn’t have to fetch it at all.
Ultimately, AMD’s ‘killer app’ wasn’t even a production feature. The best and least expected advantage of using a module loader came from referencing individual module files during development, and then seamlessly transitioning to a single, concatenated and minified file in production.
On the server side, http fetches are rare, as most files already exist on the local machine. The CommonJS format uses this assumption to drive an synchronous model. The CJS-compatible loader will make available a function named require(), which can be called from within any ordinary Javascript to load a module.

// myCommonJSModule.js
var myDepObj = require(‘myDependencyStringName’);
var $ = require(‘jQuery’);
if ($.version <= 1.6) alert(‘old JQ!’);

CJS eliminates the cumbersome boilerplate syntax of AMD’s define() signature. Back-end pros who use languages like Python often find CJS a more familiar pattern than AMD. CJS can also be statically analyzed more easily – for instance, in the example above, an analyzer could infer that the object being returned from require(‘jQuery’) should have a property named ‘version’. IDEs can use this analysis for useful features like refactoring and autocomplete.
Since require() is a blocking function, it causes the Javascript interpreter to pause the current code and switch execution context to require’s target. In the example above, the console log won’t execute until the code from myDependencyStringName.js has loaded and finished.
In the browser, downloading each dependency serially as the file is processed would result in even a small app having unacceptable load times. This doesn’t mean no one can use CJS in the browser though. The trick comes from doing recursive analysis during build time – when the file has to get minified and concatenated anyway, the analyzer can traverse the Abstract Syntax Tree for all the dependencies and ensure everything gets bundled in the final file.
Finally, ES6, the most significant update to Javascript in many years, added built in support in the form of the new ‘module’ keyword. ES6 modules incorporate many of the lessons learned from both AMD and CJS, but resemble CJS more strongly, especially in regards to loading.

Reasons not to use a module loader

These days, modular programming and module loaders have become synonymous with rich web apps. But using modular programming does not necessarily require using a module loader. In my experience, only the issue of complicated module interdependence qualifies as absolutely requiring a module loader, but many projects have complicated loading infrastructure they just don’t need.
Adding any technology to your stack has a cost: it increases both the number of things that can possibly go wrong and that you need to understand. Many of the benefits of loaders are just that – benefits – and not requirements. Beware the benefits that sound like no-brainers – You Ain’t Gonna Need It, as it’s a subtle form of premature optimization.
Try running your project without a loader at first. You’ll have greater control over and insight into your code. If find you never need one, you’re ahead, and adding one later is not hard.
The same YAGNI logic applies to the features of whatever module loader you choose. I’ve seen many projects use AMD named modules for no benefit whatsoever (and there’s a substantial cost to it as well). KISS.

Tiny loaders

Early on, as AMD emerged as a leading client-side format, the module loading ecosystem exploded to support it. Libraries from this explosion include LAB.js, curljs, and Almond. Each had a different approach, but much in common: they were tiny (1-4kb), and followed the Unix philosophy of doing one thing and doing it well.

The thing they did was to load files, in order, and afterwards call back a provided function.  Here’s an example from the LABjs github:

<script src="LAB.js"></script>
<script>
$LAB
.script("https://remote.tld/jquery.js").wait()
.script("/local/plugin1.jquery.js")
.script("/local/plugin2.jquery.js").wait()
.script("/local/init.js").wait(function(){
initMyPage();
});
</script>

In this example, LAB starts fetching jQuery, waiting until it finishes executing to load plugin1 and plugin2, and waiting until those are finished before loading init.js. Finally, when init.js finishes, the callback function invokes initMyPage.
All these loaders use the same technical mechanism to fetch content: they write a <script> tag into the page’s DOM with the src attribute filled in dynamically. When the script fires an onReadyStateChange event, the loader knows the content is ready to execute.
LAB and curl aren’t actively maintained anymore, but they were so simple they probably still work in today’s browsers. Almond still gets maintained as the minimalistic version of Require.

RequireJS

Require appeared in 2009, a latecomer among the tiny loaders, but went on to gain the greatest traction due to its advanced features.

At its core, Require is not fundamentally different than the tiny loaders. It writes script tags to the DOM, listens for the finishing event, and then recursively loads dependencies from the result. What made Require different was its extensive – some might say baffling – set of configuration options and operating sugar. For example, there are two documented ways to kick off the loading process: either pointing an attribute named data-main of the script tag that loads RequireJS at an init file…

<script src=“tools/require.js” data-main=“myAppInit.js” ></script>
...or invoking a function named require() in an inline script...
<script src=“tools/require.js”></script>
<script>
require([‘myAppInit’, ‘libs/jQuery’], function (myApp, $) { ...
</script>

…but the documentation recommends not using both, without giving a reason. Later, it’s revealed the reason is neither data-main nor require() guarantee that require.config will have finished before they execute. At this point, inline require calls are further recommended to be nested inside a configuration call:

<script src=“tools/require.js”></script>
<script>
require(['scripts/config'], function() {
require([‘myAppInit’, ‘libs/jQuery’], function (myApp, $) { ...
});
</script>

Require is a swiss army knife of configuration options, but an air of automagical uncertainty hangs over the multitude of ways in which they affect each other. For example, if the baseUrl config option is set, it provides a prefix for the location to search for files. This is sensible, but if no baseUrl is specified, then the default value will be the location of the HTML page that loads require.js – unless you used data-main, in which case that path becomes baseUrl! Maps, shims, paths, and path fallback configs provide more opportunities to solve complex problems while simultaneously introducing unrelated ones.
Worth mentioning is possibly the most “gotcha” of its conventions, the concept of “module ID”. Following a Node convention, Require expects you to leave the ‘.js’ extension off the dependency declaration. If Require sees a module ID that ends in ‘.js’, or starts with a slash or an http protocol, it switches out of module ID mode and treats the string value as a literal path.
If we changed our example above like so:

require([‘myAppInit.js’, ‘libs/jQuery’], function (myApp, $) { ...

Require is almost certain to fail to find myAppInit, unless it happens to be in the directory the baseUrl/data-main algorithm returns. As close to muscle memory as typing the ‘.js’ extension is, this error can be annoying until you get in the habit of avoiding it.
Despite all its idiosyncrasy, the power and flexibility of Require won it wide support, and it’s still one of the most popular loaders on the front end today.

Browserify

Browserify set out to allow use of CommonJS formatted modules in the browser. Consequently, Browserify isn’t as much a module loader as a module bundler: Browserify is entirely a build-time tool, producing a bundle of code which can then be loaded client-side.
Start with a build machine that has node & npm installed, and get the package:
npm install -g –save-dev browserify
Write your modules in CommonJS format, and when happy, issue the command to bundle:
browserify entry-point.js -o bundle-name.js
Browserify recursively finds all dependencies of entry-point and assembles them into a single file:
<script src=”bundle-name.js”></script>
Adapted from server-side patterns, Browserify does demand some changes in approach. With AMD, you might minify and concat “core” code, and then allow optional modules to be loaded a la carte. With Browserify, all modules have to be bundled; but specifying an entry point allows bundles to be organized based on related chunks of functionality, which makes sense both for bandwidth concerns and modular programming.
Launched in 2011, Browserify is going strong.

Webpack

Webpack follows Browserify’s lead as a module bundler, but adds enough functionality to replace your build system. Expanding beyond CJS, Webpack supports not only AMD and ES6 formats, but non-script assets such as stylesheets and HTML templates.
Webpack runs on a concept called ‘loaders’, which are plugins registered to handle a file type. For example, a loader can handle ES6 transpilation (Webpack 2.0 handles ES6 natively), or SCSS compilation.
Loaders feed data into a “chunk”, which starts from an entry point – conceptually similar to a Browserify bundle. Once Webpack is set up, chunks are regenerated automatically as assets  change. This can be very powerful, as you don’t have to remember to edit chunks.
The feature that has everybody really excited is hot module replacement. Once Webpack is in charge of your chunks, while running webpack-dev-server, it knows enough to modify code in the browser as you change the source. While similar to other source watchers, webpack-dev-server doesn’t require a browser reload, so it falls into the category of productivity tools that shave milliseconds off your dev process.
Basic usage is beyond simple. Install Webpack like Browserify:
npm install -g –save-dev webpack
And pass the command an entry point and an output file:
webpack ./entry-point.js bundle-name.js
If you’re limiting use to Webpack’s impressive set of defaults, that command power always comes at a cost though. On one project, our team had several difficult problems – transpiled ES6 didn’t work after Webpack chunked it, and then SCSS worked locally but failed to compile in the cloud. In addition, Webpack’s loader plugin syntax overloads the argument to require(), so it won’t work outside of Webpack without modification (meaning you won’t be able to share code between client and server side).
Webpack has its sights set on the being next-generation compiler for the web, but maybe wait for the next version.

Screen Shot 2016-06-13 at 12.27.23 PM

Google Trends’ Take

Source

SystemJS

Wikipedia defines a polyfill as “additional code which provides facilities that are not built into a web browser”, but the ES6 Module Loader Polyfill which SystemJS extends goes beyond the browser. An excellent example of how agnostic modern Javascript has become about the environment it runs in,  the ES6 Module Loader Polyfill can also be used via npm in a Node environment.

SystemJS can be thought of as the browser interface to the ES6 Module Loader Polyfill. Its implementation is similar to RequireJS: include SystemJS on the page via a script tag, set options on a configuration object, and then call System.import() to load modules:

<script src="system.js"></script>
<script>
// set our baseURL reference path
System.config({
baseURL: '/app'
});
// loads /app/main.js
System.import('main.js');
</script>

SystemJS is the recommended loader of Angular 2, so it already has community support. Like Webpack, it supports non-JS file types with loader plugins. Like Require, SystemJS also ships with a  simple tool, systemjs-builder, for bundling and optimizing your files.
However, the most powerful component associated with SystemJS is JSPM, or JavaScript Package Manager. Built on top of the ES6 Module Loader Polyfill, and npm, the Node package manager, JSPM promises to make isomorphic Javascript a reality. A full description of JSPM is beyond the scope of this article, but there’s great documentation at jspm.io, and many how-to articles available.
Comparison Table

Loader CategoryLocal module formatServer filesServer module formatLoader code
Tiny loadersVanilla JSSame structure as local filesSame format as local filescurl(entryPoint.js’)
RequireJSAMDConcatenated and minifiedAMDrequirejs(‘entryPoint.js’, function (eP) {
// startup code
});
BrowserifyCommonJSConcatenated and minifiedCommonJS
inside AMD
wrapper
<script src=”browserifyBundle.js”>
</script>
WebpackAMD and/or CommonJs (mixed OK)“Chunked” – Concat and minify into feature groupsWebpack proprietary wrapper<script src=”webpackChunk.js”>
</script>
SystemJSVanilla, AMD, CommonJS, or ES6same as localSystemJS proprietary wrapperSystem.import(‘entryPoint.js’)
.then(function (eP) {
// startup code
});

Conclusion

Today’s plethora of module loaders constitutes an embarrassment of riches compared to just a few years ago. Hopefully this post helped you understand why module loaders exists and how the major ones differ.
When choosing a module loader for your next project, be careful of falling prey to analysis paralysis. Try the simplest possible solution first: there’s nothing wrong with skipping a loader entirely and sticking with plain old script tags. If you really do need a loader, RequireJS+Almond is a solid, performant, well supported choice. Browersify leads if you need CommonJS support. Only upgrade to a bleeding edge entry like SystemJS or Webpack if there’s a problem you absolutely can’t solve with one of the others. The documentation for these bleeding-edge systems is arguably still lacking. So use all the time you save by using a loader appropriate to your needs to deliver some cool features instead.

, ,

An Array of JavaScript Array Methods

It is no real surprise that one of the primary purposes of computer languages is processing lists (indeed, one of the oldest programming languages – Lisp – is a contraction of the term “list processing”). In Javascript, lists are managed with the Array object. The last few years has seen a significant beefing up of what JavaScript arrays can do as part of the EcmaScript 6 development, to the extent that even many programmers aren’t aware of the full capabilities that arrays offer.

Explore JavaScript Courses

The following is a mixed bag of tricks and methods, focusing both on some of the cooler ES6 code, some on the more esoteric functional programming tricks of ES5. One thing that both of these improvements do is to establish a unifying principle for iterating through lists of items, a problem that’s emerged from twenty years of different people implementing what was familiar to them in JavaScript. That’s admittedly a testimony to how flexible Javascript is.

Avoiding the Index

The traditional way of iterating over an array has been to use indexes, such as the following (Method 1).

var colors = [“red”,”orange”,”yellow”,”green”,”blue”,”violet”];
for (var index=0; index<colors.length; index++){
    var color = colors[index];
    // do something with color
}

Method 1. Using index to iterate over an array

The problem with this is that it first requires the declaration and creation of an index variable, and you still have to resolve the value that the array has at that index. It’s also just aesthetically unpleasing – the emphasis is on the index, not the value.

ES6 introduces the of keyword, which lets you iterate to retrieve an object directly (Method 2)

var colors = [“red”,”orange”,”yellow”,”green”,”blue”,”violet”];
for (const color of colors){
     // do something with color
    }

Method 2. Using the of keyword to iterate over a JavaScript array.

The use of this construction is both shorter and with a much clearer intent, retrieving each color from the list without having to resolve an array position. The use of the const keyword also provides a bit of optimization – by declaring the variable color as constant, JavaScript can reduce the number of pointer resolutions because a new variable isn’t declared each time.

If you’ve ever had to process web pages to retrieve specific elements, you likely also know that the result of functions such as document.getElementsByClassName() is array-like, but not strictly an array. (You have to use the item() keyword on the resulting object instead). The ES6 from () function is a static function of the Array object that lets you convert such objects into JavaScript arrays (Method 3).

var colorNodes = Array.from(document.getElementsByClassName(“color”));
for (const colorNode of colorNodes){
     // do something with colorNode
    }

Method 3. Converting an array-like object into a JavaScript array.

By the way, how do you know that colorNodes is an array? You use the static Array.isArray() function (Method 4):

if (Array.isArray(colorNodes)) {
    console.log(“I’m an Array!”)
    }

Method 4. Testing for an array.

Array-like objects, on the other hand, will self- identify (using the typeof keyword) as objects, or will return false to the .isArray() function. In most cases, so long as an interface exposes the length property, it should be possible to convert it into an array. This can be used to turn a string into an array of characters with a single call (Method 5). Note that Array.from(str) is functionally equivalent to str.split(“”), though possibly not as fast.

function strReverse(str){
   return Array.from(str).reverse().join("");
   };

console.log(strReverse("JavaScript"))
> "tpircSavaJ"

Method 5. Inverting a string

In this example, the strReverse() function using from() to convert a string into an array of characters, then uses the Array reverse() function to reverse the order, followed by the join(“”) function to convert the array back into a string.

Prepositional Soup: From In to Of

The of keyword is easy to confuse with the in keyword, though they do different things. The of statement, when applied to an array, returns the items of that array in the order of that array (Method 6).

var colors = ["red","orange","yellow","green","blue","violet"];
for (const color of colors){
    console.log(color)
    }
> "red" 
> "orange" 
> "yellow" 
> "green"
> "blue" 
> "violet"

Method 6. The on keyword returns the values of a JavaScript array.

The in keyword, on the other hand, returns the index keys of the array.

var colors = ["red","orange","yellow","green","blue","violet"];
for (const colorIndex in colors){console.log(colorIndex)}
> 0
> 1
> 2
> 3
> 4
> 5

Method 7. The in keyword returns the keys or indices of a JavaScript array.

Note that Javascript arrays, unlike Java arrays, can be sparse. This means that you can have an element a[0] and a[5] without having an a[1] through a[4]. Iterating over the length of an array in this case can cause problems as the length of the Array does not necessarily correspond to the last item in that array (listing 8).

var a= [];
a[0] = 10;
a[5] = 20;
for(var index=0; index!=a.length; index++){
    console.log(a[index])
    };
// Returns null values for a[1} to a[4} and a[6], because these have not been defined.
// Note that a.length here is equal to 7.
for(var index in a){console.log(index+": "+a[index])};
// Here, only two values are returned, because, for a[0] and a[5] respectively, because
// the "in" keyword is iterating only on declared keys.
> 0: 10
> 5: 20

Method 8. Sparse arrays can give problems for iterated indexes, while in provides better support.

The Joy of Higher Order Functions with JavaScript Arrays

Callbacks have become an indispensable part of Javascript, especially with the popularity of jQuery and related browser frameworks and the node.js server. In a callback, a function is passed as an object to another function. Sometimes these callbacks are invoked by asynchronous operations (such as those used to make asynchronous calls to databases or web services), but they can also be passed to a plethora of Array related iteration functions.

Perhaps the simplest of such callbacks is that used by forEach(). The principle argument is the function to be invoked, passing as parameters both an object and its associated key or index:

colors.forEach(
    function(obj,key){
        console.log(key+": "+obj)
    }
)

> 0: red
> 1: orange
> 2: yellow
> 3: green
> 4: blue
> 5: violet

Method 9. Invoking a function using the forEach() function.

The forEach() function, while perhaps the most commonly known of the “functional” Array functions, is intended primarily to execute an expression without providing a resulting output. If, on the other hand, you want to chain functions together, a more useful Array function is the map() function, which takes the output of each function and adds it to a new array. For instance, the following function (Method 10), takes an array of lower case characters and returns an array where the first letter of each word has been capitalized.

colors.map(
    function(obj,index){
        return obj[0].toUpperCase() + obj.substr(1);
    }
)

> ["Red", "Orange", "Yellow", "Green", "Blue", "Violet"]

Method 10. Using the map() function.

Note that this function can be extended to turn a sentence into “title case” where every word is capitalized (listing 11).

function titleCase(str){
return str.split(" ")
.map(
    function(obj,index){
        return obj[0].toUpperCase() + obj.substr(1);
    }
)
.join(" ")
};

var  expr = "This is a test of capitalization.";
titleCase(expr);
> "This Is A Test Of Capitalization."

Method 11. Using array functions to capitalize expressions.

As should be obvious, the split() and join() functions bridge the gap between strings and arrays, where split converts a string into an array using a separator expression, and join() takes an array and joins the strings within the array back together, with a given separator.

What’s even cooler about split() is that it can also be used with regular expressions. A common situation that arises with input data is that you may have multiple spaces between words, and you want to remove all but a single space. You can use split and join (listing 12), to do precisely that.

var expr = "This is  an    example    of   how you   clean up text with embeddedt 
tabs,  white spacesn and even carriage returns."
> "This is &nbsp;an &nbsp;&nbsp;&nbsp;example &nbsp;&nbsp;&nbsp;of &nbsp;&nbsp;how you
&nbsp;&nbsp;clean up text with embedded &nbsp;tabs, &nbsp;white spaces
and even carriage returns."
expr.split(/s+/).join(" ")
> "This is an example of how you clean up text with embedded tabs, white spaces and even carriage returns."

Explore JavaScript Courses

Method 12. Using arrays to clean up “dirty” text.

While touching on dirty data, another useful “functional” Array function is the filter() function, which will iterate over an array and compare the item against a particular expression. If the expression is true, then the filter() function will pass this along, while if it’s false, nothing gets past. If you have data coming from a database, certain field values may have the value null. Getting rid of these (or some similar “marker” value) can go a long way towards making that data more usable without hiccups (Method 13).

var data = [10,12,5,9,22,18,null,21,17,null,3,12];
data.filter(
    function(obj,index){
        return obj != null
    }
)
> [10, 12, 5, 9, 22, 18, 21, 17, 3, 12]

Method 13. Filter cleans up dirty data.

This notation is pretty typical of Javascript – powerful but confusingly opaque with all of these callback functions. However, it turns out that there are some new notational forms in ES6 that can make these kinds of functions easier to read. The predicate construct

(arg1,arg2,…) => expr involving arg1,arg2,…

can be used to make small anonymous functions. Thus,

(obj, index) => (obj != null)

Is the same as

function(obj, index){return (obj != null)};

With this capability, you can write Method 13 as:

data.filter((obj)=> obj != null);

You can even use this notation to create named functions (Method 14).

dropNulls = (obj) => (obj != null)
data.filter(dropNulls)

Method 14. Using predicate notation to define named functions for filters.

You can also go one step further and just say:

dropNulls = (arr) => arr.filter((obj) => obj != null)
dropNulls(data)

Counter tof filter() is find() , which returns the first item (not all items) where the predicate is true. For instance, suppose that you wanted to find from an array the first value that is greater a given threshold. The find() function can do exactly that (Method 15).

var data = [10, 12, 5, 9, 22, 18, 21, 17, 3, 12];
data.find((item) => item>10)
> 12

Method 15. Use find to get the first item that satisfies a predicate.

Note that if you wanted to get all items where this condition is true then simply use a filter (Method 16).

var data = [10, 12, 5, 9, 22, 18, 21, 17, 3, 12];
data.filter((item) => (item>10))
> [12, 22, 18, 21, 18, 12]

Method 16. Find retrieves the first value satisfying a predicte, filter, retrieves all of them.

The findIndex() function is related, except that it returns the location of the first match, or -1 if nothing satisfies the predicate.

Did you know that JavaScript Arrays can do map/reduce? This particular process, made famous by Hadoop, involves a two-step process where a dataset (an array) is initially mapped to another “processed” array. This array is then passed to a reducer function, which takes the array and converts it into a single processed entity. You can see this in action in Method 17, which simply sums up the array values, but shows each of the arguments in the process:

var data = [10, 12, 5, 9, 22, 18, 21, 17, 3, 12];
data.reduce(function(prev,current,index,arr){
    console.log(prev+", "+current+", "+index+", "+arr);
    return prev+current},
0);
> 0, 10, 0, 10,12,5,9,22,18,21,17,3,12
> 10, 12, 1, 10,12,5,9,22,18,21,17,3,12
> 22, 5, 2, 10,12,5,9,22,18,21,17,3,12
> 27, 9, 3, 10,12,5,9,22,18,21,17,3,12
> 36, 22, 4, 10,12,5,9,22,18,21,17,3,12
> 58, 18, 5, 10,12,5,9,22,18,21,17,3,12
> 76, 21, 6, 10,12,5,9,22,18,21,17,3,12
> 97, 17, 7, 10,12,5,9,22,18,21,17,3,12
> 114, 3, 8, 10,12,5,9,22,18,21,17,3,12
> 117, 12, 9, 10,12,5,9,22,18,21,17,3,12
> 129

Method 17. The reduce() function takes an array and processes content into an accumulator.

The first column shows that result of adding the current value to the accumulator (initially set to initializer, the 0 value given as the second argument of the reduce() function), the second column gives the current value itself, the third item is the index, and the final item is the array.  

A perhaps more realistic example would be a situation where a tax of 6% is added to each cost, but only for values above $10. Again, you can use predicate maps to simplify things (Method 18).

var data = [10, 12, 5, 9, 22, 18, 21, 17, 3, 12];
total = data.reduce((prev,current) => (prev + current + ((current>10)?(current-10)*.05:0)),0);
console.log("$" + total.toLocaleString("en"))

> "$131.52"

Method 18. Using the reduce() function to calculate a total with a complex tax.

The .toLocaleString() function is very useful for formatting output to a given linguistic locale, especially for currency. If the argument value “de” is passed to the function, the output would be given as “131,52”, where the comma is used as the decimal delimiter and the period is used for the thousands delimiter.

How Do Your Arrays Stack Up?

When I was in college, cafeterias made use of special boxes that had springs mounted in the bottom and a flat plate on which you could put quite a number of trays. The weight of each tray pushed the spring down just enough to keep the stack of trays level, and when you took a tray off, it rose so that the last tray placed on the stack was always the first tray off. This structure inspired programmer who discovered that there were any number of situations where you might want to save the partial state of something by pushing it down on an array, then when you were done processing, popping the previous item back off. Not surprisingly, such arrays became known as, well, stacks.

JavaScript defines four functions – push(), pop(), shift(), and unshift() respectively. Push() places an item on the end of an array, pop() removes and returns it. You can see this in Method 19.

var stack = ["a","b","c"];
console.log(stack)
> ["a", "b", "c"]
stack.push("d")
> 4
console.log(stack)
> ["a", "b", "c", "d"]
stack.pop()
"d"
console.log(stack)
> ["a", "b", "c"]
stack.unshift("d")
>4
console.log(stack)
> ["d", "a", "b", "c"]
stack.shift()
"d"
console.log(stack)
> ["a", "b", "c"]

Method 19. Pushing and popping the stack.

Stack based arrays have a number of uses, but before digging into them, you can extend the Array() functionality with a new function called peek() that will let you retrieve the last item in the array (which is the top of the stack), as shown in Method 20.

Array.prototype.peek=function(){return this[this.length-1]};
arr = ["a","b","c","d","e"]
console.log(arr.peek())
>"e"

Method 20. Peeking at the stack.

(Note that you can always get the first items in an array with arr[0]).

One of the more common use for stacks is to maintain a “browse” history in a Javascript application. For instance, suppose that you have a data application where render(id) will draw a “page” of content without doing a server-side reload. Method 21 shows a simple application that keeps a stack which will let you add new items as you continue browsing the stack, but also lets you back up to previously visited “pages”.

<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
   <head>
       <title></title>
       <style>
#container,#list {color:white;}            
       </style>
       <script>
Array.prototype.peek=function(){return this[this.length-1]};

App = {
   stack:[],
   color:"white",
   colorSelect:null,
   popButton:null,
   list:null,
   container:null,
   init:function(){
       App.container = document.getElementById("container");
       App.colorSelect = document.getElementById("colorSelect");
       App.popButton = document.getElementById("popButton");
       App.list = document.getElementById("list");
       App.colorSelect.addEventListener("change",App.display);
       App.popButton.addEventListener("click",App.goBack);
       return false;
       },
   display:function(){
       color = App.colorSelect.value;
       oldColor = App.color;
       App.color = color;
       container.innerHTML=color;
       document.body.style.backgroundColor=color;
       App.stack.push(oldColor);
       App.list.innerHTML = App.stack;        
       },
   goBack:function(){
       var oldColor = App.stack.pop();
       if (oldColor != null){
           container.innerHTML=oldColor;
           document.body.style.backgroundColor=oldColor;
           App.color=oldColor;
           App.list.innerHTML = App.stack;
       }
       return false;
       }
};

window.addEventListener("load",App.init);
       </script>
   </head>
   <body>
       <div id="container"></div>
       <div>
       <select value="white" id="colorSelect">
           <option value="white">White</option>
           <option value="red">Red</option>
           <option value="green">Green</option>
           <option value="blue">Blue</option>
           <option value="orange">Orange</option>
           <option value="purple">Purple</option>
       </select>
       <button id="popButton">Pop</button>
       </div>
       <div id="list"></div>
   </body>
</html>

Method 21. Creating a stack that remembers color states.

When you select an item from the <select> box, it changes the background to the new color, but then pushes the old color onto the stack (shown as the comma separated list). When you pop the item, the stack removes the last item and makes that the active color.  This is very similar to the way that a web browser retains its internal history.

 

Pop!

Contemporary Javascript arrays are far more powerful than they have been in the past.  They provide a foundation for higher order manipulation of functions, let you do filtering and searching, and can even turn complex functions (often ones that relied heavily upon recursion) into chained map/reduce operations. This should make arrays and array functions a staple for both text processing and data analysis. Learning how to work with arrays properly can give you a distinct advantage as a Javascript programmer.

Explore JavaScript Courses

One final note: While ES6 is rapidly making its way into most contemporary browsers and environments such as node.js, they may not necessarily be available in older browsers (especially constructs like of and predicates). There are a number of polyfill libraries that will let you get close, most notably the Babel polfill (https://babeljs.io).

Kurt Cagle is the founder and chief ontologist for Semantical, LLC, a smart data company. He has been working with Javascript since 1996.