About the Author:

ES6 One Liners to Show Off

March 30th, 2017

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!

(more…)

About the Author:

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

March 30th, 2017

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.

About the Author:

Decorating (your Javascript) for Fun and Profit

February 20th, 2017

Sometimes you need to get “meta”. What if you could tell a variable that any time it changes, it should automatically report that change to a log file, without you having to write code to do it? What about identifying a function should be called by a web server whenever a particular URL pattern is matched? Or maybe, as with tools like mobX, you want to have functions be invoked only when the variables they reference change. These could radically simplify the amount of “communication” code that you need to write, and more can concentrate the responses to such changes in a consistent manner rather than force piecemeal edits. This is the role of decorators, perhaps one of the most important capabilities to emerge from the ES2017 upgrades. This post will give a quick primer on ES2017 Decorators.

Decorators

Decorators are familiar to people who work with Babel, but these (and the associated code constructs that these enable, such as those used by Mobx or similar libraries) have yet to make their way into broad implementation natively in most browser engines. As such, you will need to use Babel as a preprocessor for any of the following (or use the ES2015 implementation, discussed below).

Functions are objects. This single fact opens up an entire world in which functions can be “decorated” in various ways in order to expose certain functionality. A decorator, in this context, is a function that wraps around another function in order to provide information to some other process. Decorators differ from ordinary functions in that they do not ordinarily change the result of the function, but rather invoke some additional action when the functon is called, such as adding an entry in a log or indicating that a given parametric class property is observable or not.

The use of such decorators has been around for awhile, and collectively is known as aspect-programming (or, sometimes, metaprogramming). They are, however increasingly showing up in Javascript typically at the point where classes and associated methods are defined. Starting with ES2016, transpilers such as Babel used the @ symbol to indicate such a decorator.

A (relatively) simple example of a decorator might be something like a @log decorator, which is used to identify when a given method is called in a class, along with the arguments applied to that method.

class Mat {
 @log
 add(a, b) {
  return a + b;
 }
 @log
 subtract(a,b){
  return a - b;
 } 
}
var m = new Mat();
m.add(2,3)
m.subtract(2,3)

The two functions add and subtract do exactly what you would expect them to do. However, in both cases these methods have the @log decorator placed on it, which serve to add a log event every time each of these methods is invoked:

Calling "add" at Thu Dec 22 2016 19:02:16 GMT-0800 (Pacific Standard Time) with [2, 3]
Result = 5
Calling "subtract" at Thu Dec 22 2016 19:02:16 GMT-0800 (Pacific Standard Time) with [2, 3]
Result = -1

The log file gives the name of the method and the parameters being passed, along with the time stamp for when the method was called.

In order to create this particular bit of magic, it’s necessary to define the log decorator previously. This would likely be loaded in via an import of some sort from an established library module.The @log decorator itself is defined as follows:

function log(target, name, descriptor) {
 var oldValue = descriptor.value;

 descriptor.value = function() {
  console.log(`Calling "${name}" at ${new Date()} with arguments `,arguments);
  var output = oldValue.apply(null, arguments);
  console.log(`Result = `,output);
  return output;
 };

 return descriptor;
}

Here, the log function is passed a target (the specific function object, the name of that function, and a descriptor that provides relevant information about the function, such as its passed parameters). The old value of the descriptor (which is a function) is temporarily cached in a variable, a log description is sent to the console, and the function is then invoked with the arguments metavariable passed in through the context of the original function (arguments is an array-like object that holds the arguments of the initial calling function).

Given that you have the function and its associated arguments (and with some work the binding class or prototype) this can not only get information but can also be used to populate other control structures. As an example, certain libraries such as Mobx make use of decorators to designate @observable variables. When the value of these change, notifications can be passed back to a reference broker object which will then update items that subscribe to that observable “variable”, without having to write code into the setter/getter directly.

This has incredible utility for React and similar libraries, as these will change UI only when observed variables change. Indeed, this is where the true power of decorators come in: the act of invoking methods that can be passed on to specialized objects without the original author of those methods needing to know the internal mechanisms involved.

About the Author:

Advanced JavaScript ES2015 Template Strings with Tagged Templates

February 1st, 2017

If you’ve paid any attention to the discussions about ES2015/ES6 that have been going on over the past couple years, you should already know about template literal strings:

`This string starts and ends with a backtick and can have expressions, e.g. 5 + 5 = ${5+5}.

It can also have multiple lines without any odd "hacks".`

This in itself is an extremely useful tool that can simplify how we work with strings dramatically, but there is a little-known feature that came along with the template strings that can take them to an entirely different level of usefulness: tagged template literals.

Tagged Template Literals

A tagged template literal is a template literal (as you’ve already seen) that is preceded by a tag. A tag is a function that receives all the pieces of the string that you created via the template literal and returns something that should be based on the string. Here’s a simple (and incomplete) example to help you understand:

// Some dummy data... just I just call myself a dummy?
let user = {
    firstName: "Joseph",
    lastName: "Zimmerman",
    nickname: "Zim"
}

// Define the tag (definitely doesn't need to be called "tag")
function tag (...args) {
    // do something with those args
    // return something
}

// prefix with `tag` and foo will be set to whatever tag returns
let foo = tag`My name is ${user.firstName} ${user.lastName}, but my friends call me ${user.nickname}.`

This looks very strange to those who aren’t acclimated. You wouldn’t put the name of a function right in front of any old string (e.g. myFunc"a string") and expect anything to happen other than a syntax error, right? Well, it works just fine with template strings. The interesting thing here is that it ends up being a function call without using any parenthesis. Things are just getting weirder by the second!

So the next question on your mind is probably, “what arguments does the tag function get called with?”, right? Well, that’s what I was wondering when I first looked at these, so that’s what we’ll look at next. The first argument is an array of each of the pieces of the string that aren’t template substitutions (the expressions surrounded by ${ ... }) . The rest of the arguments are each of the template substitution values.

Once again, I think an example will help explain things:

function tag (stringBits, val1, val2) {
    console.log(stringBits) // => ["My name is ", " ", "."]
    console.log(val1) // => "Joseph"
    console.log(val2) // => "Zimmerman"
}

tag`My name is ${user.firstName} ${user.lastName}.`

I’m a little disappointed that you only see the interpolated values of the expressions and that there’s no way to get access to the literal expression so that the tag functions can allow an additional way of handling the interpolation. I’m sure there’s a good reason, such as confusing developers when the expressions don’t end up as the same value they expected.

Anyway, as you can see, all of the string parts show up as an array for the first argument. Even if there’s no characters between certain parts of the string, you’ll end up getting empty strings in that array, For example:

function tag(stringBits) {
    console.log(stringBits) // => ["test", "", ""]
}

tag`test`

See how we received 2 empty strings in that array. The first one is the characters between the two expressions and the second one is at the end of the string, after the second expression.

Also, not that every interpolated value is passed into the tag function as a separate arguments. This would be a big pain in the rear end, but since we’re using ES2015 anyway, we can use rest parameters to group all of those arguments into an array, like this.

function tag (stringBits, ...values) {
    console.log(stringBits) // => ["My name is ", " ", "."]
    console.log(values) // => ["Joseph", "Zimmerman"]
}

tag`My name is ${user.firstName} ${user.lastName}.`

I can’t foresee any situations where this wouldn’t be the preferred way of handling those values, so we’ll stick to using the rest parameter from now on.

One last thing to note: I haven’t been completely honest about the value of stringBits (the first parameter of the tag function) in these examples. You see, stringBits is more than just an array; it also has a raw property, which is also an array of the string pieces. There’s a difference, though: if you have escaped characters in your string (e.g. "\n"), it’ll be converted to a new line in the main array, but in the raw array, it’ll show up just as you typed it, as if you had actually used "\\n". Check out the example below:

let place = "world"

function tag (stringBits, ...values) {
    console.log(stringBits)
}

tag`Hello ${place}.\nWelcome to this tutorial.`

The Chrome console would output something like this:

Array[2]
    0: "Hello ",
    1: ".↵Welcome to this tutorial.",
    length: 2
    raw: Array[2]
        0: "Hello ",
        1: ".\nWelcome to this tutorial"
        length: 2

See how in the main array there is a "↵" representing the new line, whereas in the raw array we still see the "\n". If you’re looking for the raw characters that the developer writes then this can be useful. It’s also worth noting, though, that if you simply want to create a tag so that you can get the raw string, then don’t waste your time. There is a built-in tag for that: String.raw.

String.raw`Hello ${place}.\nWelcome to this tutorial.`
// => "Hello world.\nWelcome to this tutorial."

Just as a quick exercise, let’s recreate the normal template literal behavior with our own tag function:

function tag(strings, ...values) {
    return strings.reduce(function(combined, string, i) {
        return combined + string + values[i]
    }, "")
}

Turns out it’s as simple as strings[0] + values[0] + strings[1] + values[1]..., which we accomplish with reduce so that we don’t need to worry about how many parts are in the string.

Applications

So what kind of applications are there for this? How can you use tagged template literals in a helpful way? Well, I couldn’t think of anything special, but some others in the community have. The first example is html-tagged-template, which allows you to feed a string of HTML into it, and the tag will actually spit out DOM nodes that match your HTML.

html`

 

 

 

Hello

 

 

 

`

This will return the entire hierarchy of DOM nodes without resorting to innerHTML nonsense or a ton of node creation and appending. I’d check out the project to see how it might help you, though something like React’s JSX might be a better solutions because a lot of the parsing is handled by the pre-processor rather than the browser.

Speaking of React, there is another powerful use for tagged template literals called styled-components that simplifies how you create base components and style them by allowing you to just specify the CSS as a template literal to the tag from styled-components. For example:

import React from 'react';
import styled from 'styled-components';

// Create a <Title> react component that renders an <h1> which is centered, palevioletred and sized at 1.5em
const Title = styled.h1`
  font-size: 1.5em;
  text-align: center;
  color: palevioletred;
`;

// Create a <Wrapper> react component that renders a <section> with some padding and a papayawhip background
const Wrapper = styled.section`
  padding: 4em;
  background: papayawhip;
`;

function HelloWorld () {
  return (
    <Wrapper>
      <Title>Hello World, this is my first styled component!</Title>
    </Wrapper>
  );
}

export default HelloWorld;

This gives you a few React components:

  • Title, which is an H1 tag styled with the CSS provided in the template literal string
  • Wrapper, which is a SECTION tag styled with the CSS provided in the template literal string.
  • HelloWorld, which composes the other two components

You can go here to see this in action and fiddle around with it. Of course, you’re not obligated to try it; I just wanted to give you some examples of how tagged template literals can be used to do some powerful things. If you have any questions about tagged template literals or interesting ideas of how you could use them, drop them in the comments.

About the Author:

A Simple Primer in JavaScript Recursion

December 17th, 2016

Recursion is a concept that is not unique to JavaScript. It is used in all programming languages. Though it is an important part of Javascript that sometimes gets muddled or overtly complex. Recursion is simply when a function calls itself.

A function that calls itself is comparable to a loop. Both of these methods are executing their code multiple times. They also both require a condition to stop an infinite loop or infinite recursion. A simple example of recursion is seen through factoring.

Factorial Recursion

The mathematical concept of a factorial is a perfect case to use recursion. A factorial is represented by (n!). For example, n! = 1×2×3×4×..×n is the main formula. The following examples show the start of a factorial table.

1! = 1
2! = 1×2 = 2
3! = 1×2×3 = 6
4! = 1×2×3×4 = 24
5! = 1×2×3×4×5 = 120
6! = 1×2×3×4×5×6 = 720

The underlying concept of recursion is doing the same thing over and over again. Factorials demonstrate this and can be programmed into a recursive function. The following code is an example of this.

function factorial( n ) {
if ( n === 1 ) {
return 1;
}
return n * factorial( n - 1 );
}

This code fits the correct parameters for recursion. The function is calling upon itself and it has a condition — return, to stop itself from entering into an infinite recursion. This is the simplest demonstration of the concept.

Loop to Recursion

Another great example of recursion can be seen from converting a loop. Take, for example, this simple countdown while loop.

var countdown = 5;
while(countdown > 0) {
console.log(countdown--);
}

When this loop executes, countdown’s value changes with each print out of the subsequent number. This same while loop can be written using a recursive function.

var counter = function(amount) {
if (amount > 0) {
console.log(amount);
return counter(amount - 1);
} else {
return amount;
}
};
counter(5);

The counter is called upon inside the definition of counter function. Each time counter is executed the engine tracks where it’s being called from. The major difference is that this function hasn’t modified the state of the internal variables inside the function. It executes them one after the other. It doesn’t store them and let them stack up on one another.

Tail Call Optimisation

When a function calls itself recursively in Javascript it creates a new stack. A stack is a block of memory that keeps track of the function’s information. Creating a stack causes the JavaScript engine to work much harder and drain memory. This can cause an error if not coded correctly. Herein lies the next example.

function factorial(n, register) {
if (n === 1) {
return register
}
return factorial(n — 1, n * register)
}
factorial(6, 1) // == 720

A tail call function returns the value from the original return value. The last return factorial(n — 1, n * register) line is the tail call. This is a standard way to prevent a recursion from stacking onto themselves repeatedly and draining away all the memory. Recursive functions in JavaScript need to track where they’ve been called every time.

Tail call optimization has become standard in ES6 and they makes sure that each recursion cycle is called one after the other. This avoids stacked up memory. Tail call optimization is considered one of the more difficult methods to learn about. But it is an essential tool in creating or deconstructing a recursion function.

Overall, all of these examples can help guide a developer’s understanding of recursion functions. They are helpful for factoring, looping more efficiently and executing anything repetitive that calls upon itself.

About the Author:

Using JavaScript ASync Functions

December 3rd, 2016

Async stands for asynchronous and it is (aptly) the opposite of synchronous programming. To get a better grasp on Async functions, you need to first fully understand synchronous code. Simply put, synchronous code means “many statements in a sequence”. Each statement is executed one after the other. This also means that a statement has to wait before the other one is finished.

console.log(‘1st’);
console.log(‘2nd’);
console.log(‘3rd’);

The previous code above will execute and output the “1st”, “2nd”, “3rd” strings in a row to the console. Simple. It is written synchronously.

Asynchronous code will execute statements outside of the main flow. This allows for async functions to be executed right away without having to wait. Developers see both states of code. An example of Async programming is shown with a simple jQuery function:

console.log('1st');
jQuery.get('page.html', function (data) {
    console.log("2nd");
});
console.log('3rd');

The output from the example above will be different. “1st”,”3rd”, “2nd”. This is due to the function passing through jQuery.get and not being immediately called. Instead the function has to wait for jQuery to fetch the page before executing.

Async Code: Benefits & Uses

Once the code had run, there is a chance that synchronous code can block future executions. This happens because it is waiting for prior statements to finish. Basically, this means that the UI can become unresponsive until a function has finished. This should be avoided at all costs as it can damper the user experience.

A developer named Brian Terlson, is working on implementing native Async functions into ECMAScript. Currently, it’s in proposal mode and in step three(candidate) of being implemented part of ES7.

Variants of async functions currently exist. The unique keyword is async before every declaration. Here is the following syntax:

  • Async function declarations: async function foo() {}
  • Async function expressions: const foo = async function () {};
  • Async method definitions: let obj = { async foo() {} }
  • Async arrow functions: const foo = async () => {};

Generally, you’ll want to use asynchronous code to perform expensive, time consuming operations. It wouldn’t be used for something simple like changing the CSS class of an element. Here is an example of another async function, but this time with the keyword async in front of it.

 
async function asyncFunc() {
    return xyz;
}

asyncFunc()
.then(x => console.log(x));
    // xyz

Notice the “.then” operator. An async function is passed through the argument by something called a Promise implementation. According to its definition, a promise represents “a value which may be available now, or in the future, or never.”

A promise is in three different states:

  • pending: starting state, not yet fulfilled or rejected.
  • fulfilled: the operation has finished successfully.
  • rejected: the operation has failed.

So to recap, asynchronous code should be used for when synchronous code won’t cut it. It adds a new degree of complexity that will keep your user experience smooth and flowing. Your application or website stays responsive, and reduces idle time for the end user. Native implementation of Async functions will make this a ubiquitous way to execute aysnc functions.

About the Author:

Finding the Most Frequent String in a JavaScript Array

October 21st, 2016

In the following tutorial, I’ll show you how to write a function that takes an array of strings and returns the most frequent string(s) in that array. First I’ll go through the basic concepts and setup, we’ll test it to make sure it works, then I’ll explore a few ways in which you can handle bad data and errors. We’ll also consider some ways to make the outputted data more user friendly. Let’s get started!

We’ll start with a pure function, one that takes an array of strings as input and returns another array as output (the outputted array will ultimately contain the string(s) that occur most frequently in the input). The setup looks like this:

   function mostFreqStr (str) {
      var which = [];
      return which;
    }

Next we’ll define an object that we’ll fill with data, using the strings in the array as keys and the number of times those strings occur as values. We’ll also add in a mostFreq variable that will be used to keep track of how many times the most frequent string(s) occur(s). The code now looks like this:

   function (arr) {
      var obj = {}, mostFreq = 0, which = [];
      return which;
    }

Now we’ll get in to the meat of the function, the processing logic. I’ve chosen to use JavaScript’s native forEach method that is an inherent to all arrays. If for some reason you wanted to use a for or while loop, you could do that as well. Here’s what the forEach approach looks like using ECMAScript 6 syntax (don’t worry, we’ll discuss the logic involved right after looking at the code):

    arr.forEach(ea => {
      if (!obj[ea]) {
        obj[ea] = 1;
      } else {
        obj[ea]++;
      }

      if (obj[ea] > mostFreq) {
        mostFreq = obj[ea];
        which = [ea];
      } else if (obj[ea] === mostFreq) {
        which.push(ea);
      }
    });

The logic is this: the ea variable represents the current array element on each iteration of forEach. The first if statement asks Does the string represented by ea exist as a key in obj? If the string is not the name of a key in obj (i.e., if obj[ea] === undefined evaluates to true), then we declare and initialize in obj the string represented by ea. We initialize it to a value of 1. The value 1 here represents the number of times we’ve encountered the string in arr. On the other hand, If the string is already the name of a key in obj, then we increment that key’s value by 1 (i.e., we add one more to the count of how many times we’ve seen the string in question in arr).

The second if block there is used to compare values of the keys in obj (i.e., the strings in arr) to the current most frequent count (i.e., the value of mostFreq). mostFreq was initialized equal to 0, so if the value of ea in obj is greater than 0 (as it will be as for any string encountered in arr), then mostFreq is updated to the value of obj[ea]. Additionally, the which array gets added to it the current value of ea (i.e., the current string in our iteration through arr). The else if portion of the second if block accounts for the condition where two or more strings in arr share the current value of mostFreq. If two or more strings in arr share the condition of being most frequent in arr, then the latter string(s) encountered is/are pushed to the which array so that they can equitably share the title.

The final step in our function is to return the newly populated which array. The entirety of the code looks like this:

    function mostFreqStr (arr) {
      var obj = {}, mostFreq = 0, which = [];

      arr.forEach(ea => {
        if (!obj[ea]) {
          obj[ea] = 1;
        } else {
          obj[ea]++;
        }

        if (obj[ea] > mostFreq) {
          mostFreq = obj[ea];
          which = [ea];
        } else if (obj[ea] === mostFreq) {
          which.push(ea);
        }
      });

      return which;
    }

Here it is live with a few tests so that we know it’s working:

See the Pen NRLWdz by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

But let’s say we want to make it a little more user friendly with respect to the output. We can convert the which array to a string by using Array’s toString method. We can then append a sentence (using ES6 template literals) in order to clarify the output. Like this:

    which = `"${which.toString()}" is the most frequent string in the array.`

Examples of input and output:

    console.log(mostFreqStr(["x", "x", "y", "y", "y", "z"]));
    //"y" is the most frequent string in the array.
    
    console.log(mostFreqStr(["x", "x", "x", "y", "y", "y", "z"]));
    //"x,y" is the most frequent string in the array.

Hmm… that second one doesn’t look quite right. We can write in some logic to handle our output sentence’s grammar when there’s more than one most frequent string. I’m going to use Array’s join method in order to help us out here. Here’s the live version:

See the Pen kkRaBd by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

There we go!

Now… for one final consideration… error handling. What if someone passes in some bad data? Or let’s say someone tries to pass in two arrays instead of just one; or perhaps an array that contains an element that isn’t a string. What someone tries to pass in data that isn’t an array at all? Let’s write some logic to handle these erroneous conditions. Live example:

See the Pen YGOzRA by Chase Allen (@ccallen001) on CodePen.

And there we have it! A function that takes an array of strings as input, checks for and handles potential errors, and ultimately returns a user friendly response indicating the most common string(s) in the array. Please feel free to comment and share. Thank you for reading!

About the Author:

ES6 Modules: Use Cases and Examples

October 21st, 2016

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.

About the Author:

Dissecting the React Lifecycle and Related Methods

October 18th, 2016

React has proven to be wildly popular by Javascript developers, providing a foundation for building highly “reactive” components that are performant, efficient and generally scale well.

However, React can prove a little intimidating to get into, in part because the documentation can be cryptic, and in part because the toolset itself works largely by automating the normal messaging and event management that goes into developing web components. Understanding the React component lifecycle can go a long way towards figuring out what magic React is doing behind the scenes. This post will explore the major React lifecycle methods using a very simple “Loading…” component as a learning example.

A brief outline:

Initializating a Component

Covers getDefaultProps(), getInitialState() and render()

Initializing a component is performed by establishing both the defaults that are used in the template when a component is first defined and also identifying the state that the component should start with. It’s also customary to put the render() method in this step, as this makes it possible to actually see what the initial state looks like.

In the example covered here, the component in question is a “Loading …” span that emulates older text-based screens, where the word is followed by a growing string of periods or other characters until an upper bound is reached, at which point the “marching ants” (usually periods) start over. The “ example used here will showcase several stages of the React Life Cycle.

You can explore the code yourself below:

See the Pen Loading Demonstration by Kurt Cagle (@kurt_cagle) on CodePen.

When a new React Class is defined, the invoking structure passes in a JSX template (which looks something like an HTML or XML file) and an associated element that becomes the container for the DOM created by the template and the React libraries.

The base code for creating the component class then starting the rendering is show below:

var Loading = React.createClass({...
})

ReactDOM.render(,
    document.querySelector('.loading')
);

The JSX template (here, “) creates the DOM for the component, with one attribute, maxCount holding the number of states that the Loading text can be in (from “Loading” to “Loading …”).

There are two methods within the React class definition that are responsible for setting up initial state conditions. The first, getDefaultProps(), returns property values from the template attributes or text content if these are not otherwise specified in the template definition.

var Loading = React.createClass({
    getDefaultProps: function() {
        return {
            maxCount: 5,
            char: '.'
        }
    },
    ...
})

ReactDOM.render( & lt; Loading maxCount = "4" / & gt;,
    document.querySelector('.loading')
);

It’s worth following the workflow here – the default parameters are passed as an object first, then the ReactDom.render() function looks at the template to adjust the parameters with the new values. In this case, the default maxCount parameter value is “5” but there is an attribute in the template called maxCount that then sets this to the value “4”. These in turn are passed into the class’s props collection (accessible by this.props in most event handlers, such as this.props.maxCount).

In addition to template properties, React components also have stored state via the this.state object. The getInitialState() method returns an object that is passed internally to the React environment. Normally, this is called internally on an empty object, but if this handler is defined, then the object that’s passed becomes the state properties for the component.

var Loading = React.createClass({
            getDefaultProps: function() {
                return {
                    maxCount: 5,
                    char: '.'
                }
            },
            getInitialState: function() {
                return {
                    text: "Loading",
                    count: 0,
                    maxCount: this.props.maxCount,
                    key: null
                }
            },
            ...
        }

Here, the getInitialState returns an object with four fields – text (the “Loading” base string), count (the current number of characters to deploy), maxCount (same as this.prop.maxCount) and key (used for storing the setInterval() key used to clear the repeating loop).

Updating State and Properties

Covers componentWillReceiveProps()

React tracks changes to state automatically, but it does not react directly to changes in properties on the template in the same way. Instead, it is up to the user to handle code where the component itself gets modified.

Note below how maxCount propagates through from property to state variable. As expected, this is only called once, when the component is first initialized. Suppose, however, that an external process changed the attribute value. In that case, another function, componentWillReceiveProps() gets called with the updated properties, which can then modify the state, as follows:

var Loading = React.createClass({
            getDefaultProps: function() {
                return {
                    maxCount: 5,
                    char: '.'
                }
            },
            getInitialState: function() {
                return {
                    text: "Loading",
                    count: 0,
                    maxCount: this.props.maxCount,
                    key: null
                }
            },
            componentWillReceiveProps(nextProps) {
                this.setState({
                    maxCount: nextProps.maxCount
                });
            },
            ...
        }

The setState() method is very important when working with React. It may be tempting to just use a direct assignment (such as this.state.maxCount = nexProps.maxCount) but this, it turns out, doesn’t work. The reason for this is that React has to keep track of when a state variable gets changed, which means that internally it has to keep both the old and new values for that state until that comparison is completed. By using setState(), React can set a flag indicating that a particular state field has been changed, and then use that to help calculate whether it needs to re-render a component based upon that state change.

Note that there is no equivalent componentWillReceiveStates() function, as the bookkeeping for managing that function is performed by setState().

Once at this point, the component is ready to render. This is where the render() method is invoked. This shouldn’t change any internal state; rather, this renders the internal state using HTML or SVG content:

var Loading = React.createClass({
var Loading = React.createClass({
  getDefaultProps:function(){
    return {maxCount:5,char:'.'}
  },
  getInitialState:function(){
    return {text:"Loading",
            count:0,
            maxCount:this.props.maxCount,
            key:null}
  },
  render:function(){
    return
{this.state.text} {this.props.char.repeat(this.state.count)}

} }

The render() function is called every time the component changes state, and returns templated output. In this case this outputs the text name followed by the supplied character (in this.props.char) by using the new ES6 repeat method for strings. Repeating the indicated number of characters.

It will write out “Loading”, then freeze. The variable this.state.count has a value of zero, so the character will be repeated zero times, as currently there’s no logic to update the variable.

Incorporating Time and Mounting

Covers componentWillMount(), componentHasMounted(), shouldComponentUpdate(), componentWillUpdate() and componentDidUpdate()

Once the object has been initialized, React then “mounts” the component into the HTML of the page. Remember that React’s render method must first check to insure that the state of the component has changed. If it has, then render is called to create a new image – what’s called a virtual DOM – that can be compared to the existing DOM. If the virtual and existing DOM are different, then the new DOM replaces the old.

Normally, React doesn’t do a lot of work with time-driven events, but this particular demo component requires the ability to update the component once every half a second. As a consequence, it becomes necessary to force a state update at a regular interval, which in turn will require a timer (or more properly, the setInterval() function).

The question is where to put it. In general, this should only be done once the component has been instantiated, so it can’t be placed with the existing initialization code. However, as a general rule of thumb nothing should be placed in the render() function that causes a state change in the component, which updating the count will automatically do.

As it turns out, React exposes two event handlers for precisely this situation. The first, componentWillMount is called just before the component is rendered to the screen for the first time, while componentDidMount is called immediately after the component code is rendered. The latter is perfect for starting the clock:

var Loading = React.createClass({
  getDefaultProps:function(){
    return {maxCount:5,char:'.'}
  },
 getInitialState:function(){
    return {text:"Loading",
            count:0,
            maxCount:this.props.maxCount,
            key:null}
  },
   componentDidMount:function(){
    var me = this;
    this.setState({key:setInterval(me.tick,500)});
    // Simulates a done call being made on the component. 
    setTimeout(me.finish,10000);
    return true;
  },
  tick:function(){
    this.setState({count:(this.state.count + 1) % this.state.maxCount});
    return true;
  },
  finish:function(){
    clearInterval(this.state.key);
    this.setState({count:0,text:"Done",key:0});
    return true;
  },
  render:function(){
    return
{this.state.text} {this.props.char.repeat(this.state.count)}

} }

In the example, the componentDidMount() function handler sets the state of the key, while at the same time invoking the setInterval to fire a “tick” event every half second. Because the this keyword changes meaning depending upon where it’s called, a proxy reference to the class is persisted in ‘me’ and used to invoke the tick() handler that updates the count state value. This in turn initiates another re-render five hundred milliseconds later.

This block of code also sets up a second event ten seconds into the future that will call the finish() handler (specific to this component, not the overall lifecycle). When finish() is called the interval timer is cleared and the displayed text gets set to “Done”.

The mounting commands are only invoked once, when the component is first rendered. Three additional methods are exposed by the React object for handling subsequent updates: shouldComponentUpdate(), componentWillUpdate() and componentDidUpdate(). The shouldComponentUpdate() function returns true or false and determines whether the render() method needs to be invoked. Ordinarily, this will return true only if the state has been changed in some manner and false otherwise (as there’s no need to render if nothing has changed). However, if the component has external dependencies, then adding a new shouldComponentUpdate() that checks against those dependencies would allow the users to override the default behavior.

The componentWillUpdate() and componentDidUpdate() functions are invoked immediately before and immediately after the render as a way of either modifying state (without invoking a secondary re-render) or as a way of sending a notification that the component has changed its visual presentation. Additionally, if shouldComponentUpdate() returns false, then neither of these will be fired.

Thus, any state changes that are made will run through the chain of componentShouldUpdate() => componentWillUpdate() => render() => componentDidUpdate(). Additionally, these will fire during the initial mounting phase as well.

Cleaning Up

Covers componentWillUnmount()

The component actually works well enough at this point, but one of the things a good developer should do is to insure that there are no loose threads that may cause a call to be made after a page has refreshed to a new URL. This is where the final phase of a React component makes sense.

The final life cycle phase is componentWillUnmount(). This is called when the component itself is going out of scope, either by being overwritten or because a page change is about to occur. This becomes fairly useful in those settings where the component contains some state that needs to be persisted either to a local data store or to a server end-point, or by clearing timers. The latter would look something like this:

var Loading = React.createClass({
            getDefaultProps: function() {
                return {
                    maxCount: 5,
                    char: '.'
                }
            },
            getInitialState: function() {
                return {
                    text: "Loading",
                    count: 0,
                    maxCount: this.props.maxCount,
                    key: null
                }
            },
            componentDidMount: function() {
                var me = this;
                this.setState({
                    key: setInterval(me.tick, 500)
                });
                // Simulates a done call being made on the component. 
                setTimeout(me.finish, 10000);
                return true;
            },
            tick: function() {
                this.setState({
                    count: (this.state.count + 1) % this.state.maxCount
                });
                return true;
            },
            finish: function() {
                clearInterval(this.state.key);
                this.setState({
                    count: 0,
                    text: "Done",
                    key: 0
                });
                return true;
            },
            render: function() {
                return
{ this.state.text } { this.props.char.repeat(this.state.count) } < /div> } }

By setting this up, you are able to insure that an orphaned timer event won’t go off after a new page has been loaded into memory, generating an error.

Summary

With an understanding the React lifecycle, you should have a better idea about what’s happening in the background and to ensure that the code you’re writing is being performed at the proper time.

About the Author:

How to Make Circular/Curved Text with JavaScript

September 28th, 2016

Creating circular text, or text on an curved path, in webpages may seem like somewhat of a intimidating task. There isn’t really a straightforward way to achieve it with standard HTML and CSS. There is a JavaScript plugin or two out there with some pretty decent results, but using plugins means extra dependency and load time associated tacked on to your project. So… what can you do? With a little bit of plain old vanilla JavaScript and standard CSS, it’s actually not that difficult to create curved text of your own! In this article, I’ll show you how to create circular/curved text that relies on as little as 15 lines of JavaScript. The result is functional and reusable so that you can apply as much circular text to your projects as you would like! You won’t need any special libraries or plugins of any sort; just good old fashioned HTML, CSS, and JavaScript. I’ll provide examples as we go, and I’ll provide items for consideration along the way. Circle the wagons; let’s get started!


Circular Text: The HTML

We’ll start by setting up the HTML, which is pretty much as simple as it gets. You’ll want a container for the circular text (although not 100% necessary) as well as a target element in which you’ll insert your circular text. Here’s how I’ve got it set up:

See the Pen ALoKJJ by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

Circular Text: The CSS

Next we’ll add a some CSS to get things set up. None of the following CSS is actually necessary, and it can be adjusted as needed. For the purposes of this tutorial, I chose a purely arbitrary blackish background with whitish text; I also chose to center the target element (the div with class=circTxt), but you can choose to position the containers and target elements however you please! Here’s how I have the CSS:

See the Pen NRvNEv by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

Circular Text: The JavaScript

Next comes the magic, the JavaScript. Things get a bit more complex here, but the overall logic isn’t really all that difficult. To give a broad overview before actually looking at the code, here’s what we’ll want to accomplish:

  1. Create a reusable function named circularText that takes 3 arguments: 1) the text to be written in circular fashion, 2) the radius of the circle on which the text will lie, and 3) the DOM index of the target class=circTxt element
  2. Split the text in to an array and get it’s length (i.e., the number of characters it contains)
  3. Divide the total degrees in a circle (i.e., 360 deg) by the length/number of characters in the text to determine spacing
  4. Specify the origin, or starting point, for the circular text (for simplicity’s sake, I’m going to hardcode 0 degrees)
  5. Create a loop (here using Array’s forEach method) that inserts the text around the perimeter of a circle using the defined radius and updating the origin/start value as it goes
  6. Call the function to create the circular/arced text!

Got all that? Believe me, it’s really not that complicated; less than 15 lines if you please. Here’s what the code looks like:

See the Pen rrzZoK by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

NOTE: I am do use ES6 syntax there (the arrow function and the template literal), but the code can easily be refactored to comply with more traditional syntax.


Well… there you have it… circular text with plain old HTML, CSS, and JavaScript!

Some things to consider are the need for adjusting the passed radius value based on how many characters are in your text. Generally speaking, the more characters you have in your text, the larger the radius you’ll need to use (however, you can create some neat effects by using a radius that might initially appear to be too small). Also note that you can created arced or curved text without going around a full circle by being purposeful about using spaces in your text.

See the Pen kkobjp by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

The arc effect can also be achieved by modifying the origin value used in the code (i,e., starting somewhere other than at the top of the circle). Regarding modifications to the CSS, the code could be changed to target elements with specified ids or tag names; you could use the document object’s querySelector method to achieve precision targeting as well. Additionally, you can modify both the circTxt containers (positioning them wherever you like on the page, giving them height and width, etc.) and the circular text within.

See the Pen Circular Text Generator by Chase Allen (@ccallen001) on CodePen.

I encourage you to go wild, get creative with it, circle back and have some fun! :)