When I first read that javascript was getting a arrow function shortcut, I was happy. Like this kind of happy:

Seriously. So happy. Check out the code below and tell me it doesn’t feel great.

1
2
3
4
5
var times_2 = [1,2,3,4].map((num) => num * 2);

times_2.forEach((num) => {
console.log(num);
});

Pretty, great, right? The arrow function shortcut seemed like a perfect port of the lambda syntax from C#. Buuuut it’s not. Like, not at all.

When you use the ES6 arrow function, it creates a lexical scope. Lexical (also called static) scoped functions are functions where the this context is set to it’s parent, and cannot be altered. This means that the examples above would translate (roughly) to this JavaScript:

1
2
3
4
5
6
7
var times_2 = [1,2,3,4].map(function(num) {
return num * 2
}.bind(this));

times_2.forEach(function(num) {
console.log(num);
}.bind(this));

Now in these two examples the scoping isn’t an issue. In fact in a lot of cases you won’t care about the => operator creating a static scope. But it’s really easy to forget, especially when everyone on the internet just refers to this thing as the “ES6 arrow function”.

For real? “Arrow function” makes it sound like this isn’t doing anything other than dropping a function into my code. It’s a bad name and it should feel bad.

To me, the better name for this is the “static scope operator”. Yeah it’s longer, fite me. Authors Note: don’t really fight me, I’m overly squishy and bruise easily. Let’s grab a drink of your preference and talk about movies or comics instead.

Using a name that doesn’t call out that this operator creates a static scope seems like a bad idea to me. Scope is an incredibly tricky thing to understand in JavaScript, so to me it should be very obvious when we are about to muck around with it.

This obfuscation of the static scope operators intent often leads to code that is harder to understand. For example, what if we wanted to create an action handler for a React component?

1
2
3
4
5
6
7
8
9
class MyComponent extends React.Component {
onLinkClick = () => {
// do stuff
}

render() {
return <a onClick={this.onLinkClick}>Clicky</a>;
}
}

The low number of lines of code here is a plus, but that onLinkClick property is hard to grok at first glance. When we write code, we’re writing code for the people that we work with now and in the future who will maintain our code. Code is for coworkers.

Let’s try cleaning this up.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import _ from 'lodash';

class MyComponent extends React.Component {
constructor() {
_.bindAll(this, 'onLinkClick');
}

onLinkClick() {
// do stuff
}

render() {
return <a onClick={this.onLinkClick}>Clicky</a>;
}
}

To me this second example is much easier to read and is clearer about how the code functions. The scope binding is clear, and explicit.

So when do I use a static scope operator? Usually in simple callbacks, like map/reduce or a one line promise handler. I don’t see the value of using => for every function by default, especially not in the class definition like above. But if you disagree, cool. I’d love to hear your points so post a comment, twit me on twitter (@codeimpossible), or chat with me at a conference.

My intention here wasn’t to make you feel bad for using static scope operators (yep, I’m going to keep calling it that). I do hope that this post made you think more about the abstractions you use and make you ask yourself if they making your code easier to read, maintain, and test, or if they are just saving you a few keystrokes.

Comment and share

In January I was lucky enough to participate in a project review session for General Assembly a programmer bootcamp here in Austin, TX. I was one of three professional software devs brought in to provide feedback on the students’ projects. The feedback can be on anything, from how they approached the UX, their data models, how they used git… anything.

During each presentation each team had a set of topics that they had to talk about, one of them being “rose, bud, thorn” or “what was great about this project/experience”, “what will you take on to your next project(s)”, and “what sucked”.

One team of students began a demo of their search filters for a recipe site they had built. It had a great amazon-esque checkbox filter system where you could pick recipe ingredients to filter the list of recipes on the site. It worked really well.

For their “what sucked” part, one of the team members brought up the code for the checkbox filtering and showed how it worked. There was a collection of around twenty if statements that controlled what happened when one of the recipe filters was chosen.

Basically it looked something like this, just 20x as much:

1
2
3
4
5
6
7
$('checkbox1').on('change', function() {
if ($(this).is(':checked')) {
$('form #hidden1').val($(this).val());
} else {
$('form #hidden1').val('');
}
});

So for each checkbox there was a matching hidden field in a form so the selected search filters could be sent to the server and the search could be carried out. A truly righteous hack, if I may say so.

When the rest of the reviewers and I saw this we kinda chuckled a bit - which to be honest, probably wasn’t the best response - but I explained that we were all chuckling because hacks are a common thing in software development and we’d all done hacks like that (or in worse) to make something work to meet a deadline. It’s a fact of life. And it’s a friggin’ important one too.

We should create hacks more often. Don’t kill yourself for 2-3 hours to try to find the best/most correct way to do something immediately. If you meet resistance, do the simplest thing that could possibly work - make a hack - and move on. Come back to it - or even better get someone to pair or code review what you’ve done - and refactor it when you know the better way to do it. Bad code is… well, yeah, bad… but it’s also super important since it helps us grow and become better.

You won’t forget your hacks easily. They’ll stay with you for a while; they will keep you up at night. In fact, one night, you’ll probably refactor them into as few lines of code as possible.

And one day you’ll come back to those hacks, years from now and chuckle too.

Comment and share

I decided to start 2016 off a bit differently. Normally I’d write a recap post for 2015 listing all the things I didn’t do, and how I was going to finally do them this year. Because this year is totally different than all the others before it.

Right. So, new year, new way of doing things. First, the blog. It hasn’t gotten any love in pretty much a year, so I’m here kicking the dust off of it, fighting away all of the spiders and rodents that have nested in the past 12 months. New platform, it’s running on hexo a static site generator that runs on node.

Why Node? Well, I got tired of dealing with the hassle of my jekyll powered blog, sure it ran, but everytime I wanted to go back to it I had to remember to install ruby, python, jekyll, pygments and I hadn’t used any of those in a super long time. So just getting my blog viewable on my laptop was a nightmare, never mind trying to get it to run on my desktop (which is windows based). Forget it.

As part of the transition, I decided to not port a lot of my older posts. This is mostly just because I’m too lazy to grind through the changes necessary to get the posts to work with the new blog platform. I moved over 2 of my most popular posts, if you’re looking for other posts, check out the git repo.

If you’re suuuuper interested in having me move a post over for whatever reason then open an issue on github and I’ll do it.

So, new blog. What else?

Well we’re going to go back to this whole living healthy thing. It worked well in 2012 when I was on my way to getting married - I was at an all-time low of 235lbs. I’d like to get down there again. I’ve spent the last 2 years hovering around 270-280 and it’s not enjoyable. It’s that awkward part of being a big person where your lower half of your body is still holding out hope that the top half will go back to being thinner. It is awful and frustrating and I pretty much hate myself everyday.

More Writing. Yep. Twitter - and my own self-doubt - have ruined my writing ability. It’s time to get back into this and churn some stuff out that I can be happy with, and maybe (hopefully) write some stuff that other people find valuable too.

New year, new sheriff in town. Time will tell how well the new rule goes.

Comment and share

Lately, I’ve beeen working on a lot of projects with different people/languages/editors, most of us were new git’ers and each project had a real problem with trailing whitespace.

Fred and Tim

It all starts out innocently enough. Fred, a mid-level developer at InfoTech Systems opens up his IM client and fires off a chat to a co-worker: “Hey Tim, can you check out my pull request? I’m done with the ratings feature and think we should merge it in”.

Tim, a Senior Software Developer, has been writing code since the mid 80’s. He originally started out contributing to the Gnome project and then bounced around the corporate world, Lotus, Microsoft, Oracle but now works with Fred at a small startup where they and five other developers are trying to build the next great cat-picture rating website - CatR.

“Ok, let me CR it”, CR is the teams short-hand for Code Review. Even though most of the team are experienced programmers every feature and bug fix commit must be reviewed by another developer.

Fred is the “new guy” on the team, this is his third day at InfoTech and he’s submitting his first feature enhancement. Even though Fred has 8 years of coding under his belt, he still gets a little nervous when someone reviews his code.

“Hmmmmm” Tim types back. Ugh, This can’t be good Fred thinks.

“This git diff looks weird. How many lines did you change in the main stylesheet?”

“Only 2 why?” Fred types back, starting to get a bit defensive. He takes a few quick, deep breaths and calms down.

“The diff is lighting up like a christmas tree. Check your diff locally.”

Fred opens up a terminal and does a quick check to see what Tim is talking about:

git diff master product-ratings-feature

“Crap!” the word jumps instantly into Freds mind. He can see immediately what Tims talking about. There a bunch of lines where the only thing different is the whitespace at the beginning or end of the line.

“Ugh, yeah I see it” Fred types back.

“Well, we can’t pull this in yet dude, we only want to have diffs show what we actually changed so if something goes south in the future we’re not scratching our heads looking at a all whitespace commit. Go back and check your whitespace settings, re-save and let me know when I can review it again.”

“Great, guess I’ve got some more work to do” Fred says to himself. He lets out a fairly audible sigh, opens up Visual Studio and starts typing away at the keyboard.

The moral of the story

Trailing whitespace issues can cause a lot of problems when they get into your repository. It leads to falsey diffs which claim lines have been changed when in fact the only thing that changed was spacing.

This can make finding what actually changed in a file later on in the development cycle next to impossible. Most open source project leads know this and a lot of them will reject pull requests that fail to trim whitespace (or have other

A lot of IDEs and text editors have options to configure trailing whitespace (SublimeText make this insanely easy) but Visual Studio, amazingly, has no option for this.

How to Remove Trailing Whitespace on save in Visual Studio

  1. Open visual studio (yep)
  2. In the menu select Tools -> Macros -> Macros IDE (yeah, we’re opening another IDE)
  3. Expand “My Macros” in the Project Explorer (usually in the right-hand side of the window)
  4. Double-Click the EnvironmentEvents module (yep, it’s VBA in all it’s glory)
  5. Paste the code below just after the “Automatically generated code” region

    Private Sub DocumentEvents_DocumentSaved(ByVal document As EnvDTE.Document) _
        Handles DocumentEvents.DocumentSaved
        Dim fileName As String
        Dim result As vsFindResult
    
        Try
            ' Remove trailing whitespace
            result = DTE.Find.FindReplace( _
                vsFindAction.vsFindActionReplaceAll, _
                "{:b}+$", _
                vsFindOptions.vsFindOptionsRegularExpression, _
                String.Empty, _
                vsFindTarget.vsFindTargetFiles, _
                document.FullName, _
                "", _
                vsFindResultsLocation.vsFindResultsNone)
    
            If result = vsFindResult.vsFindResultReplaced Then
                ' Triggers DocumentEvents_DocumentSaved event again
                document.Save()
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly, "Trim White Space exception")
        End Try
    End Sub
    

Now save your new macro and whenever you save a file in Visual Studio this will run and trim all the trailing whitespace.

How to Remove trailing whitespace on save in Sublime Text 2

  1. In Sublime Text, open up the preferences menu and select “File Settings - User”
    • this is important because if you use the “Default” settings, they may be overwritten when you update Sublime Text to a new version.
  2. Scroll down until you see "trim_trailing_white_space_on_save", set this option to true
  3. Save
  4. Profit

Get Git to help you out

In the example above Fred could have saved himself a lot of time if he ran one command:

mv .git/hooks/pre-commit.sample .git/hooks/pre-commit

This file has a check (on the last line) that will fail any commit when there are whitespace errors. It’s not enabled by default so you have to remove the .sample from the file name to get git to run it.

After all this, what should I do next?

High-five Yourself!!!

Comment and share

Ever been working on a customer’s site, writing some really awesome jQuery, you deploy it, and everything is awesome. And then you get an email one day…

Has this ever happened to you: you’ve been working on a customer’s site, writing some really awesome jQuery flashy, fadey, scrolly, interactivey thing, you deploy it, and everything is awesome. The customer rejoices and the customer’s customers rejoice. Rejoicing is had by everyone. And then you get an email one day:

“Everything is broken. We’ve kidnapped your dog. Fix our site or you’ll never see Spartacus again.”

And before you have time to wonder why you ever named your dog “Spartacus” to begin with (i mean come. on.), you’re off in debug hell.

You load the site and see all sorts of weird errors: "$().ready is not a function" "$(document) doesn't support this property or method" Or my personal favorite: "null is null or not an object"

You open up FireFox, activate FireBug, load the console, and type alert($), press run, and instead of seeing the expected jQuery function:

1
2
3
function (E, F) {
return new (o.fn.init)(E, F);
}

You instead get:

1
2
3
4
5
6
7
8
9
10
11
12
function $(element) {
if (arguments.length > 1) {
for (var i = 0, elements = [], length = arguments.length; i < length; i++) {
elements.push($(arguments[i]));
}
return elements;
}
if (Object.isString(element)) {
element = document.getElementById(element);
}
return Element.extend(element);
}

Or even:

1
2
3
function $(id) {
return document.getElementById(id);
}

DOH! Looks like another javascript library has been loaded and has overwritten the $() shortcut for jQuery. Woe is I. Why can’t we all just get along?!? Well, we can’t stop people from including their favorite javascript libraries, but what we can do is prevent our code from suffering as a result. We’ll need a nice, big beefy, bodyguard to make sure our code isn’t messed with while it’s out clubbing with Prototype, Scriptaculous or even MooTools (who invited him??!?). Here’s what our bodyguard function will look like

1
2
3
( function($) {

} ) ( jQuery );

So what this does is call our anonymous function and pass the jQuery object. This will scope $ our little function so we won’t step on anyone else’s toes (and they won’t bump into us while we’re on the dance floor and spill our drink everywhere). Okay, I think I've taken the clubbing metaphor far enough.

Basically this will allow our code to run and use the $ shortcut for JQuery as if it were loaded without any of these other libraries on the page. Here is what the completed code would look like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js" type="text/javascript">
</script>


<script src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.1.0/prototype.js" type="text/javascript">
</script>

<script src="http://ajax.googleapis.com/ajax/libs/scriptaculous/1.8.3/scriptaculous.js" type="text/javascript">
</script>


<script type="text/javascript">
( function($) {
// we can now rely on $ within the safety of our "bodyguard" function
$(document).ready( function() { alert("nyah nyah! I'm able to use '$'!!!!"); } );
} ) ( jQuery );

//this will fail
$(document).ready( function() { alert('fail?'); } );
</script>

I love using this simple self-calling anonymous function style when working with jQuery because it saves me from typing jQuery(), which really does look a lot more ugly than using the $() shortcut. It also protects my code from any scoping issues and lets the code function normally when jQuery is put into no conflict mode.

My opinion, if you’re doing work in jQuery on sites that you don’t control 100%, you should be using this method to protect your code and your clients.

Updated: changed link for jquery to use 1.4.1 at the google CDN (tsk, tsk, tsk I was using the googlecode.com link)

Comment and share

  • page 1 of 1

Jared Barboza

dev @Hudl. I like javascript, cats and video games. I’m an adult, opinions here are mine.


Software Developer, npm installer


Austin, Texas