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.

 

Should You Commit Compiled Code?

Working on a Java project you would never dream of committing a built war or jar file, so when working with JavaScript why would you think of committing the compiled source. So many projects I have worked on have by default commit the dist/lib code. This adds bloat and unnecessary steps to committing and merging such as making sure that you build before committing files and that you build when merging.

Preventing Commits of Complied Code

When setting up a new project always create a .gitignore file and add this to the project. For most projects I have worked on we have always used a dist/lib folder for the compiled source. For these cases add the following to your .gitignore.

# compiled source
dist
lib

if you have already committed the dist or lib you can stop tracking the files by using the following git command: git rm -r –cached

How to Provide Users with the Compiled Source

The easiest and most recommended (personal opinion) method for distributing your source is via npm. Npm allows you to publish code to a central repository and allow users to quickly access and use the code. The reason that I prefer Npm over other package managers like bower is due to the Npm repository, the repository allows publishers to push only the needed content so that users only pull down and have access that what they need. Bower however acts more like a link to git repositories which in turn requires publishers to commit complied source.

NPM Publish

To publish to Npm you can follow some simple steps that will have you pushing code in no time.
Create your npm account. You can also pay to have private repositories and push/get from these.
– Add the name field to the package.json file in your project.
– Add a prepublish task to the npm scripts
– Run npm publish

You can see an example file below:

{
  "name": "module-name",
  "version": "10.3.1",
  "description": "An example module to illustrate the usage of a package.json",
  "author": "Your Name ",
  "scripts": {
    "test": "echo 'No Tests'",
    "start": "node index.js",
    "prepublish": "uglifyjs --compress --mangle input.js"
  },
  "main": "dist/foo.js",
......

You can either have a build task that you call from the prepublish or just call the build commands. Now when you run npm publish the prepublish will run and compile your source. Now you need to make sure that only this gets pushed to the Npm repository. This can be achieved by using a .npmignore similar to the .gitinore however this will list all your project content except for the dist/lib folders.

Now your project is setup to only publish and track what users need and want.

 

JavaScript Developers Toolkit

 
My tool kit has grown over the years and even more so since I became a focused and dedicated JavaScript developer. From development environments, online resources and third party tools.
 
## IDE
As JavaScript does not require compiling you could write it all in notepad or any basic text editor as the browser will handle the code. But when developing large scale JavaScript applications you need more tools and features from your IDE.

My IDE of choice is WebStrom when I worked on Java based projects I used Intellij and it was a dream to use which made WebStrom the only option for me. The feature set was above par to any other development environment I had used. Features such as intellisense (which is extremely powerful), being able to find method usages and definitions, code quality checking and auto refactoring, source control tools built in like merging, a built in terminal, debugging for not only client side JavaScript, NodeJS and even Grunt and Gulp. I also blogged before about the power of the keybindings in WebStrom/Intellj

However this does come at a cost, there are a number of great free alternatives such as Sublime Text, Atom, Aptana Studio, Komodo Edit to name a few. Each with a different set of features, pros and cons.

Third Party Apps

So you have an IDE but there are other apps out there that can aid the developer. Two I use on a daily bases are SIP colour picker and LICEcap.

SIP

SIP is a powerful colour picker that will work anywhere on the screen and provide colours in a number of different formats to suit any development needs. It also keeps track of the most recent colours you have picked.

LICEcap

LICEcap is a tool for generating gif files from recording your screen, this comes in useful when developing UI components and trying to share these with other developers. When documenting a UI code base I always add a gif of the UI component in action. An alternative to LICEcap is Record It however this tool auto uploads the gif which is not great if you are working with internal products or products that have not been released yet.

Online Tools

Ove the years I have built up a collection of online tools or reference sites that I use on a daily basis’s. Here are some:

JSFiddle

JSFiddle is probably one of the most known online tools for web developers, it allows you to create online projects with just one html, css and JavaScript file, however you can add third party code files. This is a great tool for sharing code examples when either getting help/advice or showing off some new code or feature. There has also recently been a release of a ES6 Fiddle to allow for online editing of ES6 code.

JS Bin

JSBin is almost the same as JSFiddle however has some extra features such as a console panel. The main reason I use JS Bin is when I cant get some code to work in JSFiddle I double check on JSBin to remove any doubts. I have also experienced some issues with JSFiddle and company proxy servers blocking the output of the Fiddle.

Code Pen

Code Pen is probably one of the best looking out of the code playgrounds, It seems to be more focused on the look and feel of code. If you check the examples pages there are some beautiful examples of JavaScript and CSS. The interface is clean and simple also which works well when you want to focus on the code at hand.

JS Perf

JS Perf is a JavaScript performance testing site allowing you to pit different methods of doing the same action against each other and see which one out preforms the other. I use this a lot in work when dealing with different patterns and even different methods from different libs. I have used it before when testing the performance of lodash vs underscore vs jQuery vs ES5.

Reference Tools

Having all the tools are great but not knowing how to develop or how to over come bugs makes all the tools useless.

MDN (Mozillia Developer Network)

MDN is a great site for looking up not only JavaScript but HTML and CSS API documentation the site also provides news and examples. An example of the API documenatation can be found n the Flexbox page, the page provides information on the API, examples and the browser compatibility.

Dev Docs

Dev Docs is a must have tab open in your browser. If you work with JavaScript you most likely work with a few frameworks, you will at some point have to look into the docs for that framework. Dev docs pull in all the JavaScript frameworks that you want and keeps them in one handy tab. With the ablitiy to search and save for offline use it will save you some much time. You can open github issues to get other frameworks added.

Keeping up with the Joneses

If you are into JavaScript you most likely have realised that the world of JavaScript moves fast and you need to find ways to keep up. Here are some methods and resources I use:

Podcasts

JavaScript Jabber

JavaScript Jabber is a weekly podcast that discusses font and backend JavaScript, coding best practices, coding environments and the JavaScript community. The podcast has covered a very wide range of topics with regular guest from big name companies and communities from Angular and ember core developers to Brendan Eich (which was my favourite show to date).

NodeUp

In very simple terms NodeUp is a weekly podcast is a about Node.js, each week a different aspect of node is looked at usually with guests who are closely related to the topic and can provide a deep insight into the technology. With big name guests from the likes of Netflix, Socket IO developers and even the people behind NPM.

Shop Talk

Shop Talk is a weekly front end development podcast that has a mix-up of shows with guests from the tech world and shows for answering listener submitted questions.

The Changelog

The Changelog podcast s not just for web development but does contain a lot for the web developer. Each week a core developer of a tool or framework talks about the progression of the project where it has been where its going.

News Feeds / Twitter Accounts

I use Reddit for most of my JavaScript news needs, the following subreddits are vey usefull:

  • /r/angularjs
  • /r/backbonejs
  • /r/css
  • /r/emberjs
  • /r/Frontend
  • /r/HTML
  • /r/javascript
  • /r/marionettejs
  • /r/Meteor
  • /r/mongodb
  • /r/node
  • /r/programmingtools
  • /r/reactjs
  • /r/rubyonrails
  • /r/WatchPeopleCode

Twitter can also be a great resource if you follow the correct accounts:

  • https://twitter.com/paul_irish
  • https://twitter.com/addyosmani
  • https://twitter.com/davidwalshblog
  • https://twitter.com/jashkenas

Books

### JavaScript: The Good Parts
The must read JavaScript book, I first read this when I got into JavaScript development. I still keep a copy on my desk almost 7 years later. This book covers the basics of JavaScript a sets you up to be a great developer.

Learning JavaScript Design Patterns

This is a great book to move onto after the good parts as it takes you though the different design patterns and best practices in JavaScript. The book helps you understand JavaScript in a way that allows you to develop large applications and become better at managing code.

High Performance JavaScript

This is a nice book to keep around for reference on how to make your code as performant as possible. There are some really useful concepts that can help any level of developer.

Conclusion

This has been a detailed look at the JavaScript developers toolkit, every developer knows what works best for them and so some of the tools I mentioned might not be for you. Your toolkit is never complete so new tools will come and go, if you have something that helps you work or find useful in some way drop a comment.

This post has been powered by Genesis – Turn it On Again and Finca Filadelfia

 

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});
 

Chrome Dev Tools – IDE Replacement

I recently talked at locally JavaScript meetup I talked about the top 5 features of the Chrome developer tools. I have given a simular talk at my old company which talked through the dev tools and how they can be used to improve the development process.

After the first talk it started to dawn on me that with some of the features in the tool kit you could get to the point of replacing the development IDE. The development cycle can be a comfortable or painful process for a developer, I have worked on some projects where the time between making a code change and seeing the results could take up to 5 minutes.

So how do we streamline this process, enter Chrome developer tools. The most powerful feature in the sources pannel.

Chrome Source Panel

As the complexity of JavaScript applications increase, developers need powerful debugging tools to help quickly discover the cause of an issue and fix it efficiently. The Chrome DevTools include a number of useful tools to help make debugging JavaScript less painful.

The sources panel provides all the needed tools for developing;
– breakpoints
– call stack
– watches
– console execution
– live editing of code

This is all great but we are still only in the dev tools, we still need a IDE or text editor to create the code then open it in chrome. What if we could edit the code and not have return the to IDE to make the changes again.

Well we can, dev tools allows you to map files to a local workspace. This makes a link between the files in the browser to the files on you local machine. See this in action below:

Adding a workspace

Now that the workspace is linked you can make changes in the browser and have these saved to the local file, this now breaks the link between the IDE and the browser. You have created a instant feadback loop.

This shows the power of the Chrome developer tools, this is only the start. As time progresses the dev tools will grow it’s feature set providing more options for developers. If you have any cool tips or tricks for the dev tools please leave a comment.

 

JetBrains Intellij Workshop

Today I attended a workshop from the team at Jetbrains, the workshop gave a detailed look into the Intellij IDE. The workshop was presented by Hadi Hariri, with his anti mouse philosophy in mind we dug into the ways to using Intellij to work efficiently. I will outline some of the take away points that I felt that most developers would not know and must learn if you plan to use or already use Intellij to develop.

##Navigation

“use the keyboard” the mantra that Hadi repeated and which made me feel bad for all the times I’v used the mouse.

Presentation assistant was shown at the point as Hadi would be using the keyboard to do everything we would need to see what key combinations were being executed. Presentation assistant flashes up on screen what keys are used to carry out an action and the action name. This will now be turned on anytime that I do live coding demos and you should do the same. This feature should also be turned on while you are pair programming for the times when you are bashing away on the keyboard and the other developer is lost to the world trying to work out what the you are doing.

So now on to the meat of the workshop the hip cool key combinations that will make you look L33T in front of all you programming friends.

###Navigation:
cmd + o get to class
cmd + 1 open the project structure
– In the project structure you can also:
– start typing and this will search for the file
– set auto scroll so that files opened via search are scrolled to on the project view
shift (double press) search everywhere this will search not only classes but files, build tasks, features anything you can really think about.
In this feature you can also toggle IDE features
Run build configurations
cmd + 7 file structure of the project
cmd + n create new file
– in the new file selection you can also start typing to search/refine the selection
cmd + e show recent file
– this comes into play especially if you disable tabled editing, Hadi was an advocate of the one tab rule in which you only have one file open at as time and using the file navigation built into Intellij you can go back and forth. Tab settings can be changed from the general settings menu and any limit can be set on the number of open tabs.
shift + cmd + e show recently edited files
cmd + y show a popup window of the code definition
cmd + b go to the code definition

###Windows
shift + cmd F12 hide all windows except the file you are editing

###Text
alt + up select line (context aware) e.g. select var, then function the class etc
shit cmd enter statement complete can be used to complete if statements

###Refactoring Code
import preferences allows you to import a namespace or each individual class, you can also add tolerances to if more that say 3 classes are used from a package then you can import the package.
cmd + t surround code, allowing you to surround a statement easily

These are just some of the tips and tricks that I had picked up from the workshop, the help documentation built into Intellij and the web site is a great resource for looking for shortcuts and different approaches for completing a task. A big thanks to the team at Dev Bash for setting up the workshop, check them out for more talks and workshops like this.

If you have learnt any tips or tricks for using this very powerful IDE please leave a comment.