jscodeshift and codemods

JS Code Shift

JS Code shift is a toolkit for running codemods, codemods are transforms that take existing code file(s) and produces new code. That is a codemod in the simplest form. I like to think if them as find and replace script on steroids. JS code shift created by Facebook provides 2 things:

  • Runner: The runner executes the transform scripts and provides feedback on the files changed
  • A wrapper for recast, recast is a AST-to-AST tool. Recast is used to preserve the style and syntax of the code that was transformed.

The pattern for running a codemod is to provide the transform path then path to the file(s) that you wish to transform.

 


jscodeshift -t path-to-codemod path-to-code 

 

You can also provide additional options to help with the process e.g. -d for a dry run if you want to test without making changes. -p to print detailed info on the process. JS Code Shift provides an API for transforms

 


module.exports = function(fileInfo, api) {
  return api.jscodeshift(fileInfo.source)
    .findVariableDeclarators('foo')
    .renameTo('bar')
    .toSource();
}

This example taken from the repo, shows how you can easily replace all occurrences of a foo variable with bar. The above transform get passed the file and the JS Code Shift API. This is then used to get the file source and from here there are methods to get different parts of the file e.g. findVariableDeclarators.

 

CodeMods

JS Code Shift provides an extremely powerful toolkit but the true power lives in the code mods that have been created.  I have managed to find some from quick googling, the reactjs community repo holds a collection react code mods. With react being a fast paced and evolving library code mods really help to evolve an existing code base to new patterns and methodologies. Pattern changes such as React.render to ReactDOM.render, in react 0.14 the render method was moved to the react-dom package. Instead of manually changing all your files you could use the code mod. Other code mods are provided such as  manual-bind-t0-arrow which replaces all manuall function binding to use ES6 arrow functions which scopes the functions.

Code Mods are not only just for react they can be run on any JavaScript code, such as a code mod to help migration to ES6. Removing all var’s and replacing with let or const can be a challenge when you have a large code base but running a code mod makes the process quick and painless.

Taking old ES5 code using var’s

Running the codemod:

Resulting code:

We can see here that the codemod has checked the code and determined that the new source should have one let and two const’s.  However nothing is ever perfect and we could say that the const for myObj should be a let, although the code is still technically valid.

 

You can find more codes mods in the following repos:

 

5 Common/Uncommon JavaScript Mistakes

JavaScript is a very powerful language, as we all know “With great power comes great responsibility”

Original post

Working with JavaScript 364 days a year (Yes I do take Christmas day off), has resulted in many mistakes. We all make mistakes, below is a list of the 5 mistakes I can think of off the top of my head.

1: “this”

“this” is probably the most powerful and dangerous feature of JavaScript. The this context in JavaScript can allow developers to save time and effort to build powerful functions. At the same time it can cause a priority 1 defect in your application.


this.foo = 'foo';

document.querySelector('.my-div').onclick = function() {
  console.log(this.foo)
}
//Logs undefined

document.querySelector('.my-div').onclick = function() {
  console.log(this.foo)
}.bind(thid);
//Logs 'foo'

As you can see above the “this” context is not always what you expect.  The reason in the above example “this” is not foo is due to the scoping of the event handler. The event handler has its own “this” context. You can use bind to change the this context however with the use of ES6/ES2015 arrow functions you can control the scope of “this”.


this.foo = 'foo';

document.querySelector('.my-div').onclick = () => {
  console.log(this.foo)
}

2: Global Events

This is probably the least used and seen mistake however I have seen it and it cost me time debugging a error. IE and Chrome both expose a global event variable “Window.event”. This at first look this already looks bad as anything global is a code smell. Also the fact that only two browsers provide this should be a put off.


onClick: () => {
  console.log(Window.event);
}
//Bad 

onClick: (event) => {
  console.log(event);
}
//Good

3: Function Scope

Similar to “this” issues, function scope can cause problems at later stages. The most common and simple example of this is using timeouts inside a loop statement.


for (var i = 0; i < 5; i++) {
    setTimeout(function () {
        console.log(i);
    }, 1000);
}

However this can be overcome by using function binding:


for (var i = 0; i < 5; i++) {
    setTimeout(console.log.bind(this, i), 1000);
}

4: Object Equality


const chris1 = {
   name: 'Chris',
   location: 'Belfast'
}

const chris2 = {
   name: 'Chris',
   location: 'Belfast'
}

console.log(chris1 === chris2); //false
console.log(chris1 == chris2); //false

The reason for this is that internally JavaScript has two different approaches for testing equality. Primitives like strings and numbers are compared by their value, while objects like arrays, dates, and plain objects are compared by their reference. That comparison by reference basically checks to see if the objects given refer to the same location in memory. As we have created two different const variables they resided in two different blocks of memory. This can be tested using assignment by reference.


const chris1 = {
   name: 'Chris',
   location: 'Belfast'
}

const chris2 = {
   name: 'Chris',
   location: 'Belfast'
}

console.log(chris1 === chris2); //false
console.log(chris1 == chris2); //false

const chris3 = chris2;
console.log(chris3 == chris2); //true

You can use libraries like lodash to do object equality.

5: string.replace

By default string.replace does not work globally. When using string replace and the first case is matched it will stop. This will work for most cases when you know there is only one instance to replace. however when replacing items in a large string you will need to use the global flag.


const myString = "This string has many spaces";
console.log(myString.replace(/ /,""));
//"Thisstring has many spaces"
console.log(myString.replace(/ /g,""));
//"Thisstringhasmanyspaces"

 

If you liked this list you can see more common JavaScript in the great post by Ryan J. Peterson in the Toptal post 10 Most Common JavaScript Mistakes

 

Monitor events with monitorEvents Chrome console

In my free time (usually waiting for tests to complete or webpack to compile) I like to check API documentation. The other day I was looking through the Chrome Developers tools API docs and I stumbled across the monitorEvents.

Using the monitor events method allows you to watch all or chosen events triggered on a target. A simple example of this is listening to the document body:


monitorEvents(document.body, 'click');

Then clicking on the page generates the below output:

Screen Shot 2016-07-10 at 19.31.44

The event gives some useful information such as:

  • clientx – the x point from where the click was triggered
  • clienty – the y point from where the click was triggered
  • srcElement – the source of the click, this is the DOM element from where the click was triggered, useful when trying to follow a path of events that have been triggered.

The above is just for a click event however other events such as scroll, mouseover etc will return more information on user or application interactions.

A real world usage for monitorEvents would be when debugging a page and trying to determine if a DOM node was getting events triggered on it that you did not expect or you want to find the route of the events. In some cases a third party plugin might trigger scroll or mouse events on DOM elements that you want to keep control of.

Of Course when you want to stop listening to events you can use unmonitorEvents(document.body); to stop the monitoring.

 

ES7 Pipe Proposal

I was recently listing to an episode of JavaScript Air at the end of the show durning the picks Kent C Dodds mentioned the pipe operator. This was the first I had heard of the pipe in JavaScript. After some digging I found some interesting information on the proposal.

The pipe operator allows you to chain functions together is a clean and simple syntax. Currently there are a few standard methods for chaining functions.

1. Using pure functions and wrapping each function:


const removeSpace = (word) => {
    return word.replace(' ', '');
}

const capitalize = (word) => {
    return word.toUpperCase();
}

const reverse = (word) => {
    return word.split("").reverse().join("");
}

const result = reverse(capitalize(removeSpace('hello world'))); //DLROWOLLEH

As you can see over time the complexity of the wrapping functions will increase the maintenance effort.

2. Using a chaining function from a popular library such as lodash or underscrore.


//These must be added to the lodash mixins 
const removeSpace = (word) => {
    return word.replace(' ', '');
}

const capitalize = (word) => {
    return word.toUpperCase();
}

const reverse = (word) => {
    return word.split("").reverse().join("");
}
_.mixin({
    removeSpace: removeSpace,
    capitalize: capitalize,
    reverse: reverse
});


const result =  _.chain('hello world').removeSpace().capitalize().reverse().value(); //DLROWOLLEH

This is maintainable however requires the addition of a third party dependency which you might not want. It also requires you to pollute the lodash namespace.

The proposed pipe operator allows you to achieve the same as above but in a much clean and more maintainable method. The issue with the two current methods are maintenance or dependence on others. If and when the pipe makes it into the standard then it removes any dependency and the clean syntax it’s easy to read and maintain. The below example shows:


const result = "hello word"
                |> removeSpace
                |> capitalize
                |> reverse;
//DLROWOLLEH

Now when an extra processing function is to be added its just another line with the “|>” pipe operator. This (to me at least) gives a clear picture of whats going on. Developers that have used bash before will recognize the “|” as a pipe for pushing data into another command or process. The arrow gives a clear direction, this can also support more complex functions.


const result = "hello word"
                |> _ => removeSpace('test', _)
                |> capitalize
                |> reverse;
//DLROWOLLEHTSET

The underscore is a ref to the initial param that’s being passed to the functions, this lets you pass other params or even mimic currying.

I can imagine there will be a lot more examples this can be used for and I’m looking forward to seeing this getting into the Es2016 spec. You can see more about the pipe operator here.

 

ES6 Features

I have been using ES6/ES2015 for a few months in my full time job. Its been a gradual adoption process taking on the new features as and when we see fit. Over these months I have built up a list of my new goto patterns for JavaScript taking advantage of ES6.

Const & Let

Let

One of the biggest changes with ES6 is the addition of const and let. Let provides a means to define variables inside block scope. This can help to combat the existing hoisting problems with JavaScript.

// ES5
if (foo === 'foo')
   console.log(bar);
   var bar = 'bar'
   console.log(bar);
}

In the above example var will be hoisted and could potentially cause issues with the code.

// ES6
if (foo === 'foo')
   console.log(bar);
   let bar = 'bar'
   console.log(bar);
}

In the let example the variable will still be hoisted however the referencing of the variable will be done in the block before hand. This means that when running the ES5 code you will just see an undefined message for the first console. However in the let case you will get a reference error indicating that you have tried to use a var before it has been declared.

Const

Const provides a way to create a constant that is either global or local scoped. When defining a constant you must provide a value as the value cannot be changed later.

// define MY_CONST as a constant and give it the value 7
const MY_CONST = 7;
// this will fail silently
MY_CONST = 20;
// will print 7
console.log("my CONST is: " + MY_CONST);
// trying to redeclare a constant throws an error 
const MY_CONST = 20;
// the name MY_CONST is reserved for constant above, so this will also fail
var MY_CONST = 20; 
// MY_CONST is still 7
console.log("my CONST is " + MY_CONST);

There is some controversy around const as it’s not what some people might expect for example the code below will not throw an error:

const MY_CONST = {foo: 'bar'}
MY_CONST.foo = 'test'
console.log(MY_CONST) // Object {foo: "test"}

An alterative to const would be to use Object.freeze()

Arrow Functions

Arrow function provide a cleaner syntax for the standard function expression and it also binds the lexical this scope to the function. This not only makes the code look clean but also takes away the pain of scope binding. No more var that = this also all arrow functions are anonymous. You can use arrow functions in a number of ways:

 //ES6
(param) => { statements }
(param) => expression
param => { statements }
// A function with no parameters requires parentheses or an underscore:
() => { statements }
_ => { statements }

Spread

The spread operator provides a cleaner way of dealing with arguments or params for function. This becomes very useful when working with React and JSX as the below example shows:

var params = {foo: 'bar', bar: 'foo'};
//Without spread
<MyElement foo={params.foo} bar={params.bar} />

//With spread
<MyElement {...params}/>

In both examples the JSX element is getting the foo and bar params, the second is cleaner and also reduced the maintenance of the code. As the params object grows you do not need to update the JSX element declaration.

Parameter Destructuring

Parameter destruction is one of the gems I have found recently. It allows you to clean up the code when you know what you need from a param. An example of this would be a using a promise/async or callback function that returns you a result. In a lot of cases you only need one part of the response. You can now define what you want and ignore the rest.

//Without param destructuring
myfunction((err, result) => {
    if (!err) {
        console.log(result.body);
    }
});

//With param destructuring
myfunction((err, {body}) => {
    if (!err) {
        console.log(body);
    }
});

One gotcha I have found with this is when the code is transplied, when Babel transpliles the code it looks like this:

//Transplied
myfunction((err, _ref) => {
    var body = _ref.body;
    if (!err) {
        console.log(body);
    }
});

If the result param is undefined or null this will fail at run time, causing an unexpected error. This has caught me out before when the expected result was not defined and only failed while in production.

Object Literals

Last but not least Object literals. This is another clean syntax which I have been using alot. It provides a shortcut to defining variables.

var foo = 'bar';
var test = { foo };
console.log(test.foo); // 'bar';

This can also work when exporting modules, we have all seen the code below before:

function plus() {
    ....
}

function subtract() {
    ...
}

function total() {
    ....
}

module.exports = {
    plus: plus,
    subtract: subtract,
    total: total
};

This follows the revealing module pattern and is okay but we could use object literals to clean this up.

module.exports = { plus, subtract, total };

It’s a small change but reduces bulk and provides a clean and simple syntax to read.

That’s all for now

This is just a few examples of what I have been using but I’m still building up my list of ES6 features and hoping to get into some ES7 features soon. If you know of any other great features drop a comment.

 

Never use Window.event

I had recently fixed bugs in different applications each with the same mistake.
In both instances the developer had used the Window.event object inside a browser
event. Something like below:

buttonClicked: function() {
  if(Window.event.currentTarget) {
    .....
  }
}

The main issue here is we are using the browser created global event object, this is
specific to IE and chrome. So what is bad about that you ask? Firefox does not support
this and your application has now lost all Firefox support. The proper way to handle
the events is to use the event param that is passed to the function by default.

buttonClicked: function(event) {
  if(event.currentTarget) {
    .....
  }
}

This method is supported by all browsers. This method also moves you away from
using the Window object which is a global and out of priceable should be avoided
when possible.

 

UnderscoreJS Compose

After watching a video about UnderscoreJS
I saw the use of the compose function, I have never noticed this when skimming through the underscore docs. The compose function:
> Returns the composition of a list of functions, where each function consumes the return value of the function that follows. In math terms, composing the functions f(), g(), and h() produces f(g(h())).

So to add some context to this; the compose function will take in multiple functions as its params and execute each of these passing the result in to the next function. One thing to note is that the functions are run in reverse order to which they were passed in. Why does this matter? Well if you have used underscore at any length you will have most likely used the chain function to try and clean up the use of multiple underscore functions:

_.chain(people)
	.sortBy(function(person) { return person.age; })
	.map(function(person) { return person.name + " is " + person.age})
	.first()
	.value();
//"mark is 14"

This code is taking an array of people and sorting them by age then returning a string for the person and getting the first string in the array. This works and is “functional” however this could be cleaner. This is where the compose function comes in we can use compose to link the functions together and not only provide cleaner code but also make the code reusable by default.

var people = [{name: "john", age: 21}, {name: "mark", age: 14}, {name: "harry", age: 40}, {name: "Mary", age: 70}];
var mapNameAndAge = function(people) {
    return _.map(people, function(person) {
        return person.name + " is " + person.age;
    });
}
var sortByAge = function(people) {
    return _.sortBy(people, 'age');
}

var comp = _.compose(_.first, mapNameAndAge, sortByAge);
comp(people);
//"mark is 14"

So you can see there is some set up as you need to define the functions before you call compose however the final composed function is much cleaner and clearer to understand. This is also reuseable by defualt. This does not stop at underscore this can be used in other places such as API calls and data calls e.g:

var updateUser = _.compose(save, update, find);
updateUser({id: 1, location: london});
 

Backbone Forms

I was thinking out loud today about Backbone views and how to manage user inputted data. When I has searched for
how to manage forms and handle user data the few examples I saw all used jQuery to pull the values out of the DOM. Which
we all know can cause issues with performance and adds a level of complexity when it comes to maintaining the code, as
the form grows the code used to pull the values out of the text boxes etc will grow.

I was thinking about this for a while until I came up with a pattern that would allow the code to update the model linked
to the view and handle new inputs added to the html without any code changes need in the view or the model. The pattern
(if you could call it that) uses data attributes
on the html to decide if the model needs updating and does this in a dynamic way.

<input type="text" class="listen-to" data-model="input1"/>

The input is decorated with a data-model attribute which will map to an attribute on the model, it also has a “listen-to”
class which will be picked up by the views events.

events: {
            "change .listen-to": "updateModel"
        }

The event will trigger once input has lost focus, this then calls the update model function. The event will fire when any
of the inputs have changed e.g allowing for as many inputs as needed. The event will be passed into the function and this
will be used to find out which attribute of the model to update and what value to update with.

updateModel: function(evt){
            this.model.set(evt.currentTarget.attributes["data-model"].value,
            evt.currentTarget.value);
            //optional: update another view with the latest value in the model
            this.outputView = new OutputView({
                model: this.model,
                el: $("#output_container")
            });

        }

As you can see in the example (hacked together) the evt will hold target that triggered the event. The data-model attribute
is used to get the model attribute to update and the value is taken from the currentTarget. For demo purposes another
is update to show that the changes are made to the model in real time. This could be extended so that a submit button will
call a function that only needs to get the model and do what ever it wants with the values as the model attributes have been
updated as the user has been filling them in.

This takes away the need to use jQuery for getting the values from the inputs and allows more inputs to be added to the
template which out any view code changes.

You can see the full demo here.