Technology

The more people who open a window, the more fingerprints that are left behind. Coding in a team is largely the same. Like a fingerprint, each developer has their own unique style that can look vastly different than others. Although there are linting libraries that will catch some of these style discrepancies, it can be difficult to enforce the nitty details. If you can make a piece of code look like it was written by one person, it immediately becomes clearer and easier to read (assuming the developer can write clean code in the first place, but I digress).

JSCS is a code style linter for programmatically enforcing your style guide. Ever get irritated when one developer doesn’t put a space between the ending function parenthesis and the opening curly brace? Here’s your chance to enforce this and create a strict, enforceable style for you and your team to follow.

Installation

JSCS can be installed via npm.

ZSH

1

npm install jscs-g

Setup

Let’s create a .jscsrc file at the root of your project. This will be used to define rules that you’d like to enforce in your JS codebase.

ZSH

1

vi.jscsrc

JavaScript

1

2

3

4

5

6

7

{

"disallowEmptyBlocks":true,

"disallowMultipleSpaces":true,

"maximumLineLength":120,

"requireDollarBeforejQueryAssignment":true,

"requireMultipleVarDecl":true

}

For simplicity, my .jscsrc file has just a few rule definitions. Here is the full list for your consideration in your project. The rules I have selected are:

disallowEmptyBlocks – Blocks must have code in them and cannot be empty

disallowMultipleSpaces – Disallows multiple indentation characters (tabs or spaces) between identifiers, keywords, and any other token

maximumLineLength – the max number of characters allowed on one line

requireDollarBeforeJQueryAssignment – requires that all variables assigned to jQuery objects be prefixed by dollar signs

requireMultipleVarDecl – Variables defined next to eachother should only be prefixed with one var declaration separated by commas

As you can see, having just a small subset of these rules can go a long way to writing consistent code in your project.

Running JSCS

After you have created your .jscsrc file, it’s time to run the style checker against your code. For the purposes of this tutorial, here’s a sample JS file that violates all of the rules above.

Create a new file (test.js)

test.js

JavaScript

1

2

3

4

5

6

7

8

9

varx=$('.test');

vary="tom";

if(x===0){

}else{

console.log("bad");

}

varz="two spaces";

Run the code style checker against it

ZSH

1

2

cd/path/to/your/project

jscs test.js

JSCS will output something like this:

ZSH

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

jQuery identifiers must start witha$at test.js:

1|varx=$('.test');

------------^

2|vary="tom";

3|

Vardeclarations should be joined at test.js:

1|varx=$('.test');

2|vary="tom";

--------^

3|

4|if(x===0){

Empty block found at test.js:

3|

4|if(x===0){

5|}else{

---------^

6|console.log("bad");

7|}

at most1spaces required between varandzat test.js:

7|}

8|

9|varz="two spaces";varx=$('.test');

-----------^

10|

11|

5code style errors found.

Bonus: Fixing the issues automatically

One of the coolest features of JSCS is the ability to automatically fix *some* of the linting errors it encounters (Currently whitespace rules, EOF rule, and validateIndentation). This is especially good if you’re incorporating this into an existing codebase.

The command is simple:

ZSH

1

jscs test.js--fix

Bonus 2: Parse ES6 code

It’s not perfect (yet), but it does a pretty good job of parsing against ES6 code as well.

ZSH

1

jscs test.js--esnext

Bonus 3: Create your own rules

Don’t see a rule that you’d like to enforce? Create it yourself! Here is the API.

This is just a brief intro to the power of this library. I will write a follow-up tutorial that will show you how to incorporate this into your workflow using Gulp and your IDE.

Responsive Development can be painful when you have to worry about all of the different breakpoints in your code. Developing in SASS makes it a bit easier since you can assign your breakpoints to variables, however it doesn’t solve the problem of the duplicated @media selectors throughout your .scss code. Not to mention, you have to separate the code for your class from the code for your class at a certain breakpoint.

By using this mixin, that all changes. It does two things for you:

Generates the media query statement automatically at the breakpoint “name” you specify

Allows you to keep your regular css code in the same place as your mobile-specific code.

This mixin uses SASS maps (introduced in 3.3 so make sure you’re upgraded) to specify breakpoint names mapped to sizes and generates a media query statement at the mapped size.

Destructuring is a concept introduced in ES6 that allows developers to destructure objects into variables without explicitly setting a variable to the object key/val. Confused? Yeah you’ll be even more confused as you start reading.

What is happening in this statement?

1

2

let obj={first:'Tom',last:'Alexander'};

let{first:f,last:l}=obj;

Is it obvious to you that f and l are new variables created from the values named first and last in the “obj” object?

I bet not.

How about this one?

1

let[x,y]=['a','b'];

Is it obvious to you that two new variables are being created, x= ‘a’ and y = ‘b’?

I didn’t think so either.

It gets worse.

1

let{x:x}={x:2,y:3};

What the bleep is going on here? Would you guess that we’re only creating a variable x (set to the value of x) and ignoring y?

It gets even uglier.

1

2

let obj={t:[{first:"Tom",last:"Alexander"},{}],a:true};

let{a:[{t:f}]}=obj;

Go ahead. Tell me seriously what’s going on here at first glance.

It gets even worse.

1

let{length:len}='Tom Alexander';// len = 3

So you can call a property of a string value too? That’s fun and clear, isn’t it?

The syntax is absolutely confusing and is going to introduce some ugly, ugly code and bugs. It *can* be useful and enable you to write some pretty clean code, but its potential for misuse outweighs its benefit.

Tread lightly and be sure to not misuse its power. These are pretty contrived examples for the purposes of demonstration, but I wanted to show that just because it can shorten the number of lines in your code doesn’t mean that it enhances readability. Readability is much more important than breviloquence in code.

As web developers, we’re all familiar with the sloth-like pace of web standards from idea to implementation (there’s a reason JS hasn’t changed much over the years). ES6 was announced in 2008 and the first draft was published in 2011. It’s 2015 and we cannot fully use ES6 in the browser yet. It’s frustrating, but we’ve all been distracted by the JavaScript flavor-of-the-month libraries/compiled languages that were introduced to help breathe life into JS and MVC.

So why write ES6 code now?

ES6 is closer to completion than you think and if you learn it now, you’ll be much further ahead in the job market. Career advancement aside, ES6 allows you to write better quality, performant, and organized code and can help you wean off of some of the other third party JS-language libraries.

Aside from that, there are third-party libraries that have been released that allow you to write ES6 code and compile it to ES5 code. Some of examples of these are: BabelJS, Traceur, and es6-transpiler. They, much in large, accomplish the same thing, but I’ve found that BabelJS is better maintained and supported (and even features some future-techy es7 features).

So not only is ES6 available to you now, but it has been right under your nose the entire time. Now is the time to start asking yourself:

“Why am I using library x?”

“What does library x offer that ES6 doesn’t?”

“Can ES6 do what library x does?”

I’m willing to bet that a lot of the things you are using (AMD imports, classes/inheritance, widgets and modules, and promises) can be replaced entirely with ES6.

But why would you even bother to rewrite your code? ES6 is the future and is, of course, native JS code. Native JS code is more performant and is finally in a position to tackle the front-end engineering problems of this century. By ditching libraries like Coffeescript, Typescript, and Dart, you’ll not only reduce the amount of code in your codebase, but you’ll also be improving the way you write JavaScript code (no, CoffeeScript is not JS code).

Let me show you how easy it is to get up and running with BabelJS and how you can immediately start writing ES6 code.

Getting Started with BabelJS

I use Gulp as a build system in my projects, but of course there are many others. I am going to assume you have Gulp installed. If you use another build system, check out Babel’s install page for further instructions.

Install

1

npm install--save-dev gulp-babel

Add a task to your Gulpfile

The following task will take app.js, run it through the babel compiler, and output it in a folder called dist. In this example, app.js is your javascript file with ES6 code and dist/app.js is the output file, transpiled to ES5. You would include the dist/app.js file in your html, not the src js.

1

2

3

4

5

6

7

8

vargulp=require("gulp");

varbabel=require("gulp-babel");

gulp.task("default",function(){

returngulp.src("src/app.js")

.pipe(babel())

.pipe(gulp.dest("dist"));

});

That’s it. That’s all it takes to write ES6 code today.

Bonus: Add sourcemaps to to make debugging easier

BabelJS compiles your code to ES5 code, so it can get in the way of debugging out of the box. To solve this problem, Babel includes the sourcemaps option, which will help you debug/visualize code from the original source JS file. Here’s an example on how you’d use it:

Comments in code are arguably more important than the code itself. Future you will thank present you if you are a good commenting citizen. I have read a ton of code in my lifetime and have come across some pretty amazing comments, but mostly awful ones. Here are some ways you can ensure you are writing good comments in your code:

Comments Do’s and Dont’s

Don’t tell the reader what they already know

Comments that say exactly what the code does are not helpful.

1

2

3

4

// If the color is red, turn it green

if(color.is_red()){

color.turn_green();

}

Do comment reasoning and history

If there is business logic in code that could be impacted on future updates or changes, leave a comment and more importantly, create a future ticket to address it 🙂

1

2

3

4

5

6

7

8

9

10

11

12

/* The API currently returns an array of items

even though that will change in an upcoming ticket.

Therefore, be sure to change the loop style here so that

we properly iterate over an object */

varapi_result={items:["one","two"]},

items=api_result.items,

num_items=items.length;

for(varx=0;x&lt;num_items;x++){

...

}

Don’t make long comments on one line

Nothing bothers a developer more than having to scroll horizontally to read comments. In fact, most developers will just ignore them because it is an inconvenience.

1

2

3

4

functionPerson(name){

this.name=name;

this.first_name=name.split(" ")[0];// This is just a shot in the dark here. If we can extract the first name, let's do it

}

Do put longer comments above logic and short comments to the side

This is sort of like the statement above, but I wanted to spell it out. Short comments belong next to code if and only if it doesn’t exceed 120 characters on one line. Otherwise, put the comment directly above the statement.

1

2

3

4

5

6

7

8

9

10

11

if(person.age&lt;21){

person.can_drink=false;// 21 drinking age

/* Fees are given to those under 25, but only in

some states. */

person.has_car_rental_fee=function(state){

if(state==="MI"){

returntrue;

}

};

}

Don’t add unnecessary comments for the sake of commenting

Commenting creates clutter. You may have been taught in school to add comments to everything because it will help the developer understand it better. This is wrong. Do me a favor and go de-pants whomever taught you this. Your code should be clean and concise enough in a way that it is self-explanatory. If your code needs to be explained line-by-line, you’re in dire need of a refactor.

1

2

3

4

5

6

7

if(person.age&gt;=21){

person.can_drink=true;// A person can drink at 21

person.can_smoke=true;// A person can smoke at 18

person.can_wed=true;// A person can get married at 18

person.can_see_all_movies=true;// A person can see all movies at 17

//I hate babies and children and all things pure because I comment too much

}

Do spell things correctly in your comments

There isn’t any excuse to misspell words in your code comments. Your IDEs should have spell checkers. If they don’t, for the love of God, download a plugin and check yourself!

Do practice

Practice makes perfect. Try creating useful comments and asking another developer if the comment is useful to them. Over time, you’ll get a better sense of what constitutes a “good” comment.

Do review other comments

Comments are often overlooked in code reviews. Don’t be afraid to ask for more comments in code and question the ones that are there. If everyone can get in the habit of writing better comments, more butterflies will fly and less babies will die. That’s probably not true, but leave a comment if you disagree.

Summary

Comments are a very important part of the development process and you should always leave a comment/docstring per the standards of each development language (think about IDE integration and code sense), but don’t comment for the sake of commenting. Comments should be useful, concise and complement your code. Comments should not have to explain your code line-by-line, rather, they should aide in explaining business logic, reasoning, and future implications.

Performance is a BIG issue in applications that many developers pay no attention to. With the increasing speed of internet connections, performance issues become less and less apparent. However with mobile and tablet use, bandwidth issues and lower-processors can bring these issues to light and should help motivate developers to write better code.

jQuery is by far the most popular JavaScript library in the market and there are several things you can do to make your code faster and more efficient. In my previous blog post, I highlighted just two things you can do to your code to instantly make a difference. In this blog post, I will be highlighting things to make your every-day development more efficient and performant.

Naming variables

This one is simple, but will instantly make your code more readable. Any time you assign a variable that points to a jQuery object (selector, single jQuery element, or otherwise) you should prefix it with a $. This will help other developers instantly recognize that the variable is dealing with a jQuery object

1

2

varx=$('.button');// bad

var$x=$('.button');// good

Caching Selectors

jQuery makes it stupidly simple to grab elements on a page and perform operations. Because it is so easy, it also promotes inefficient code because it’s easy to forget basic principles, such as caching. If you are going to reuse elements from a selector, you should cache it in a variable.

1

2

3

4

5

6

7

8

// BAD - Not cached

$('.buttons').each(...);

$('.buttons').hide();

// GOOD - Cached

var$buttons=$('.buttons');

$buttons.each(...);

$buttons.hide();

Chaining

Chaining makes your code more efficient and less cluttered. If you are going to perform multiple operations on a jQuery object, chain the operations instead of breaking them into multiple statements.

1

2

3

4

5

6

7

8

9

10

11

// BAD

var$buttons=$('.buttons');

$buttons.show();

$buttons.css('height','100%');

$buttons.addClass('red');

// GOOD

var$buttons=$('.buttons');

$buttons.show()

.css('height','100%')

.addClass('red');

How does chaining work? Most of jQuery’s functions actually return a pointer to the original object, or “this”. So $buttons.show() returns $(this), which makes the subsequent call to .css() on the original buttons object. I recommend using this as often as you can.

Master selector efficiency

If you master the art of selector efficiency, you can drastically improve the speed of your jQuery code. There are three basic principles:

Use IDs instead of classes whenever possible

Specificity – Be more specific on the right side of your selectors instead of at the beginning

Use multiple selectors for like operations

Do you ever want to perform the same operation on different selectors? You might write code like this:

1

2

3

4

// Bad

$('.button1').show();

$('.button2').show();

$('.button3').show();

Instead, you can write multiple selectors in one selector and make your code instantly more readable and efficient

1

2

// Good

$('.button1, .button2, .button3').show();

Change CSS code with classes and not .css()

It’s tempting to use .css() function from jQuery to quickly change the css properties of an element. However, it is more efficient, readable, and maintainable to actually just write a css class instead.

1

2

3

4

5

6

7

8

9

// Bad

$('.button').css({

'height':'50%',

'color':'red',

'width: 200px'

});

// Good

$('.button').addClass('red wide half-height');

1

2

3

4

5

6

7

8

9

10

11

.button.wide{

width:200px;

}

.button.red{

color:red;

}

.button.half-height{

height:50%;

}

With these small changes, you will make a huge impact on your application and other developers will thank you for it. Enjoy!

jQuery is often looked at synonymously with JavaScript; although jQuery is just a library wrapper around native JavaScript. While jQuery is easier to some degree, a lot of the tutorials and examples on the internet showcase code that isn’t nearly as performant as using native JavaScript APIs. Although I do not suggest you use jQuery in your application, it has its merit and advantages. Here are just two examples of how you can improve the performance of your jQuery code drastically.

Looping

jQuery promotes the use of the .each() method for looping through DOM elements. It turns out that this is actually up to 10x SLOWER than using native JS’s for loop. Why? jQuery’s each method expects a function that gets called for each iteration, while the native JS just accesses the index of the array. Stick to using the native for loop! Here is a fiddle to demonstrate this: https://jsfiddle.net/r4xk1kw3/1/

1

2

3

4

5

6

7

8

9

10

11

12

13

//jQuery

varitems=$('.selector');

items.each(function(item){

console.log(item);

});

//Native

varitems=document.querySelectorAll('.items'),

numItems=items.length;

for(varx=0;x&lt;numItems;x++){

console.log(items[x]);

}

Selecting Elements from the DOM

I’ll admit, the syntax for selecting DOM elements is much easier using jQuery, but it turns out that is is much less performant than using native JS. In fact, natively there are two ways to select elements by classname: 1) .querySelectAll() or 2) getElementsByClassName(). It turns out that getElementsByClassName() is the fastest way to get a list of elements, but jQuery’s selector engine is terribly slow. Here is a fiddle I made to demonstrate this: https://jsfiddle.net/yc09s6tf/1/

1

2

3

varitems=$('.items');// .20ms

items=document.querySelectorAll(".items");//.02ms

items=document.getElementsByClassName('items');//.002ms

But Tom, that’s so ugly! Why would I ever want to write code like that? I’ll admit, native JavaScript code can be pretty fugly sometimes. But we can add a little syntactic sugar on top of the native code, while maintaining the majority of the performance gains. Here is a little utility function you can use to implement jQuery-like selectors in your code.

1

2

3

4

5

6

7

8

9

10

11

function_(selector){

if(selector.indexOf(".")===0){

returndocument.getElementsByClassName(selector.substring(1));

}else{

returndocument.getElementById(selector.substring(1));

}

}

// USAGE

varmyClass=_('.className'),

myID=_('#myID');

So what now?

Try out the fiddles for yourself and see how big of a difference these two changes can make. jQuery is nice on the eyes, but I hope you’re no longer surprised on how much faster native JavaScript is.

Clojure is a fun programming language with a ton of hidden features. At the surface, it seems like you might be lost in parenthesis hell and find yourself struggling to read code. Have you ever written code like this?

1

2

3

(conj(conj(conj[123]4)5)6)

=>[123456]

Where do you even start? Obviously this is a terribly trivial example on how to add a number to a sequence three times. Yes, there are much more efficient ways to do this, but this is just an example. What if there was an easier way to write AND read this? There is…and it’s called the thread-first macro.

-> Macro (Thread First)

Threading? Do I need to bust out my computer science books? This actually has *nothing* to do with threading in the common sense with spawning threads for memory and efficiency purposes. When we say “threading” here, we are talking about threading the result of one thing into the first argument of another function. The threading macro passes its first argument as the first argument to the next statement, then passes the result of that expression as the first argument to the next statement and so on. Here is an example on how this would look for our trivial example above:

1

2

3

4

5

6

(->[123]

(conj4)

(conj5)

(conj6))

=>[123456]

This is MUCH easier to read than the above form and can be interpreted as, “Given a sequence [123], add 4 to it, then take the result of that sequence [1234] and add 5 to it. Then take the result of that sequence [12345] and add 6 to it”

But doesn’t conj take two arguments? I don’t get how this works.

The thread-first macro literally inserts itself as the FIRST argument of a function for each line that is added. conj is defined as (conj item). In the above example, the sequence is purposely omitted because the threading macro automatically inserts it.

That’s confusing, is there any way to make it easier?

One of the tricks I learned was to use an ignored character in Clojure, such as a comma, and insert it in place of the second item in the function. So the above code can be modified to look like this:

1

2

3

4

5

6

(->[123]

(conj,4)

(conj,5)

(conj,6))

=>[123456]

Once you get used to it, refrain from using the comma in your code; but it should help you to get started.

Why test your API?

Testing an API is important because it allows you to assert that you are conforming to the interface in which you promise to deliver. Testing a the API layer explicitly allows you to catch code changes that change data types, number of return values, etc… and can be an important trigger for you to update your unit tests and API Docs.

Why can’t I just unit test?

Unit testing is intended for the developer to vet the units of their code. You should worry about testing at the *method* level and not necessarily how it all fits together. By introducing API testing, you’ll be able to get a better handle on whether you’re using appropriate mock data in your tests and asserting the correct return values.

Well can’t I just rely on automated testing instead?

Automation suites, such as Selenium do not test at the API level; rather, they test at the user interface level. Sure, you could build your own automated tool to explicitly use your API to test behavior, but again, you are not testing the purity and correctness of the API. Sure, if your test uses the API a certain way and a developer breaks it, you can detect API failures. However, these types of tests don’t necessarily check for parameter correctness and all variations of use of an API.

API Testing Example

This is where Frisby.js comes into play. Frisby.js is a JavaScript-based API testing framework that makes it incredibly simple for you to test against your API. Here is an example:

Getting set up

Install Frisby.js + Jasmine Node

1

2

npm install-gfrisby

npm install-gjasmine-node

Test Structure

Frisby tests require that you reference the frisby global variable. From here, you can call frisby.create to create the structure of your first test:

1

2

varfrisby=require('frisby');

frisby.create('Get stock quote')

Write your first test

Let’s say your website allows you to check a stock price by passing in a stock symbol. This is a GET request and takes one required parameter, symbol, and one optional parameter, timestamp. If timestamp is passed in, the API will retrieve the stock price, if available, at the given timestamp. Otherwise, it will return the latest stock price.

In this example, we used Frisby.js to assert the validity of the response both in TYPES and in values, once we could narrow the stock down to a particular time. In one short test, we tested the response code, the header contents, and the JSON body of the response. Be sure to check out the Frisby.js API for detailed descriptions on each of the statements above.

In conclusion…

In this blog post, we explored WHY we test an API vs. unit testing vs. automated testing and went through a simple example on how to write a test against a simple API. API testing is important because it will help you identify breaking API changes from code that may otherwise been unnoticed. Also, it helps you keep your mock data/unit tests up to date and identify changes needed in your API documentation.

In a future blog post, I will dive deeper into Frisby.js and show you how you can write tests that depend on one another (think OAuth tokens and needing a token for a subsequent test) as well as a few more advanced examples.

Up until ES6, JavaScript lacked the ability to create classes in the way that other languages offer. Sure you could create “classes,” but it always left a sour taste in our mouths. Talk about UGLY code. Although ES6 adds the keyword, “class”, they really are syntactic sugar around the old way of doing it in ES5. You’ll notice this trend around much of ES6 features–but I digress.

Why should I care?Classes promote structure and the new syntax covers up the yucky code behind the scenes. These new classes also promote the use of inheritance and building structured code.

Imagine a scenario, where you are creating a class to represent a user in your database.

ES5 “Classes”

1

2

3

4

5

6

7

8

9

10

11

functionUser(name,age){

this.name=name;

this.age=age;

}

User.prototype.greeting=function(){

console.log("Hi, my name is",this.name);

}

varmyUser=newUser('Tom',29);

myUser.greeting();

Eh it’s not really that bad, but it can be really confusing. Aren’t functions functions? How is it possible to create a new instance of a function? There is a lot you can do with building objects and inheritance, by ES5 just didn’t really expose it or make it meaningful enough for novice users to understand.

ES6 Classes

1

2

3

4

5

6

7

8

9

10

classUser{

constructor(name,age){

this.name=name;

this.age=age;

}

greeting(){

console.log("Hi, my name is",this.name);

}

}

Pretty cool, huh? This looks and feels like classes in other languages and comes more natural. You explicitly define a constructor, which is how you create an instance of a class. Then you can define members of the class as you see fit (notice you do NOT need the keyword function in front of them–pretty odd and inconsistent if you ask me).

ES6 Class Inheritance

Lets say your database has another type of user called an author. Authors are users but also have additional metadata. You can use class inheritance to model this:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

classAuthorextendsUser{

constructor(name,age,books){

/* User keyword "super" to call

the parent constructor. This

will create this.name and this.age

on the instance of this Author class */

super(name,age);

this.books=books;

}

greeting(){

/* This method will automatically overwrite

the parent classes implementation. However

if we did not define it, the parent's

implementation would be used */

super.greeting();

console.log("But I'm also an author");

}

}

What did we learn here?

Use the keyword “extends” to write a class that inherits from another class.

The keyword “super” becomes available in the child class and can be used to call methods on the parent

You can override methods from the parent class simply by defining the method in the class. Notice there is no @override annotation or anything of the sorts required.

Classes in ES6 are important because they are explicit and help promote structured code. Many JS libraries have implemented their own version of classes, such as Dojo, TypeScript, and CoffeeScript, so it will be interesting to see if those get scaled back in the future as ES6 gets closer to fruition.

Chrome is behind on implementing classes in its spec, but you can try this out on the latest FireFox today. Enjoy!