I just launched a new course on ES6! Use the code WESBOS for $10 off.

Strengthen your core JavaScript skills and master all that ES6 has to offer. Start Now →

Author Archives: wesbos

destrucuring-intro

Destructuring is a huge part of ES6. If you want to learn all about the different parts of destructuring check out my ES6.io video tutorials or read some of the other articles on this blog. This post is a dead simple introduction to what destructuring actually is .

Along with arrow functions, let, and const, destructuring is probably something you’re going to be using every single day. I find it to be extremely useful whether I’m writing client side or Node.

What does destructuring mean? It’s a JavaScript expression that allows us to extract data from arrays, objects, maps and sets — which we’re going to learn more about in a future ES6.io video —into their own variable. It allows us to extract properties from an object or items from an array, multiple at a time.

Let’s take a look at what problem JavaScript destructuring really solves. Sometimes you need top level variables like so:

const person = {
  first: 'Wes',
  last: 'Bos',
  country: 'Canada',
  city: 'Hamilton',
  twitter: '@wesbos'
};
const first = person.first;
const last = person.last;

You get the point. You’ve got this pretty much repetitive code over and over again, where you need to make a variable from something that is inside of an object or inside of an array. What we could do instead of creating multiple variables, we destructure them in a single line like so:

const { first, last } = person;

Curly bracket on the left of the equals sign?! That is not a block. That is not an object. It’s the new destructuring syntax.

The above code says, give me a variable called first, a variable called last, and take it from the person object. We’re taking the first property and the last property and putting them into two new variables that will be scoped to the parent block (or window!).

console.log(first); // Wes
console.log(last); // Bos

Similarly, if I also wanted twitter, I would just add twitter into that, and I would get a third top level variable inside of my actual scope const { first, last, twitter } = person;

That’s really handy in many use cases. This is just one nested level, but for example, in React.js often you want to use destructuring because the data is so deeply nested in props or state.

Let’s say we have some deeply nested data like we might get back from a JSON api:

const wes = {
  first: 'Wes',
  last: 'Bos',
  links: {
    social: {
      twitter: 'https://twitter.com/wesbos',
      facebook: 'https://facebook.com/wesbos.developer',
    },
    web: {
      blog: 'https://wesbos.com'
    }
  }
};

I want to be able to pull out Twitter and Facebook URLs here. I could do this like it’s 1994 and we’re all running around with walkmans:

const twitter = wes.links.social.twitter;
const facebook = wes.links.social.facebook;
// Annoying!

We can use destructuring to do it one better!

const { twitter, facebook } = wes.links.social;
console.log(twitter, facebook); // logs the 2 variables 

Notice how we destructure wes.links.social and not just wes? That is important because we are destructuring a few levels deep.

destrucuring-renaming

Last post we took a look at an intro to destrucuring. Let’s take a look at another use case which would be renaming your variables. Sometimes data comes back in some odd names, and you might not necessarily want to use a property key as the end variable name. Maybe you don’t like that variable name or it’s already taken in your scope.

const twitter = 'twitter.com';
const wes = {
  first: 'Wes',
  last: 'Bos',
  links: {
    social: {
      twitter: 'https://twitter.com/wesbos',
      facebook: 'https://facebook.com/wesbos.developer',
    },
    web: {
      blog: 'https://wesbos.com'
    }
  }
};

For example here, I already used twitter as a variable. I can’t use it again, but I’m stuck, because this object gives me twitter as a key and this object gives me twitter as a key. What you can do is you can rename them as you destructure them.

So – I want the twitter property, but I want to call it tweet. I want the facebook property, but I want to call it fb.

const { twitter: tweet, facebook: fb } = wes.links.social;

The above code will pull the wes.links.social.twitter into a variable called tweet and similarly for facebook.

destrucuring-default-values

There’s one last thing we need to know about destructuring objects, and that is the ability to set defaults. This one’s a little bit confusing, so bear with me here and we’re going to circle back for another example later on in a couple of videos over at ES6.io.

When you destructure an object, what happens if that value isn’t there?

const settings = {
    speed: 150
}
const { speed, width } = settings; 
console.log(width);

What is width? It’s undefined because we create the variable, but it’s not able to be set to anything.

With destructuring we can set defaults, or fallback values so that if an item is not in the object (or Array, Map, or Set) it will fall back to what you have set at the default.

This syntax is a little hard to read:

const settings = {
    speed: 150
}
const { speed = 750, width = 500 } = settings;
console.log(speed); // 150 - comes from settings object
console.log(width); // 500 - fallback to default

Now if the speed or width properties don’t exist on our settings object, they fallback to 750 and 500 respectively.

Careful: null and undefined

One thing to note here is that this isn’t 100% the same as this old trick used to fallback when settings.speed is not set:

const mySpeed = 0;
const speed = mySpeed || 760; 
console.log(speed); // 760!

Why? Because ES6 destructuring default values only kick in if the value is not present. undefined, null, false and 0 are all still values!

const { dogName = 'snickers' } = { dogName: undefined }
console.log(dog) // what will it be? undefined!

const { dogName = 'snickers' } = { dogName: null }
console.log(dog) // what will it be? null!

const { dogName = 'snickers' } = { dogName: false }
console.log(dog) // what will it be? false!

const { dogName = 'snickers' } = { dogName: 0 }
console.log(dog) // what will it be? 0!

Combining with Destructuring Renaming

In my last post we learned that we can destrucutre and rename varaibles at the same time with something like this:

const person = {
  first: 'Wes',
  last: 'Bos',
};

const { first: firstName } = person;
console.log(firstName); // Wes

We can also set defaults in the same go. Hold onto your head because this syntax is going to get funky!

const person = { first: 'Wes', last: 'Bos' };
const { middle: middleName = 'Super Rad' } = person;
console.log(middleName); // 'Super Rad'

Woah – let’s step through that one!

  1. First we create a new const var called middleName.
  2. Next we look for person.middle. If there was a person.middle property, it would be put into the middleName varaible.
  3. There isn’t a middle property on our person object, so we fall back to the default of Super Rad.

Cool! Make sure to check out ES6.io for more like this!

4-new-string-methods

The String type in ES6 has come with four new methods that are really handy, help us write a little bit more readable code, as well as reduce our reliance on using regular expressions, or RegExp, for certain things.

.startsWith() and .endsWith()

So I have a const variable named course, which has the value of RFB1, this stands for React for Beginners.

const course = 'RFB1';

Sometimes I have RFB1 which is the starter package, RFB2 which is the master package, RFB3 which is the team package. I don’t really care too much about that in certain cases, I just want to know if course starts with RFB, and not something like STPU, which is Sublime Text Power User or ES6, which is this series.

Here, RFB means React for Beginners, I need to know if the string starts with it. We can use the console to check this out by typing course.startsWith('RFB'), it will return true, because obviously it does start with it.

If I did rfb, in lowercase letters, it says, false, because there is no way to make this case insensitive. If you do need case sensitivity you must still use a Regular Expression.

One other thing that .startsWith() will do is it’ll allow you to skip a certain number of characters and start looking at a set point.

const flightNumber = '20-AC2018-jz';

This flight number here, I want to see if it starts with AC. Over in the console, I’m going to type flightNumber.startsWith('AC'). It’s false, because the variable starts with 20-. This also happens if we have SKU numbers, and they start with a bunch of junk and then it gets to actually what we want.

What you can do is you can use flightNumber.startsWith('AC', 3);, which says start after three characters. That is returning true, because it ignores the first three and then starts at AC and checks against that.

EndsWith works fairly similar. Here is an example where we have jz at the end of the flightNumber, and I want to know if it’s an Air Canada Jazz flight. We can say flightNumber.endsWith('jz'), which will be true, obviously, because it ends with it.

There’s another option that we can pass .endsWith(), and I’m going to use an account number variable as an example here:

const accountNumber = '825242631RT0001';

In Canada we have business numbers that are nine digits long. They’re always nine digits long, and that is your actual business number.

Then you have a tax number, which is RT0001, or RT0002. You also might have RP0001 for your first employee, RP0002 for your second employee, and so on. We also have RC for your corporate taxes. Often you need to know, is this number a tax number or is this number a corporate tax number, or is this a payroll number? Is it RC, or RP, or RT?

I need to check if this number, which ends with RT, and I want to ignore this right here. What you can do is you can tell the account number to just take a certain number of characters, and ignore the rest.

Just like with our flightNumber, we can use the console to put in accountNumber.endsWith('RT'), which will be false. What I can tell it, though, is only take the first 11 numbers, by using accountNumber.endsWith('RT', 11); which will be true.

Essentially you’re just going to take the first 11 numbers of accountNumber, ignore the rest, and then see if it ends in RT or whatever else it might be.

.includes()

Then next up we have .includes() which will just check if that string is anywhere in it. If I wanted to see if my flight number includes the letters AC, then I could use flightNumber.includes('AC'), which istrue`.

Again, it is not case sensitive so you cannot use lower case letters here.

Includes checks to see if your string has something in it. As a bit of an aside, it was originally supposed to be called .contains(), but it got changed to includes because of some conflicts with the MooTool libraries and the way that they modified the prototype.

.repeat() and String Padding

Next up we have make, model and colour here:

const make = 'BMW';
const model = 'x5';
const colour = 'Royal Blue';

I’m going to show you where that would be useful for using .repeat(), which allows you to take a string, and repeat it. You can just call .repeat() and it’s going to repeat that string over and over and over again.

Where is that useful? Sometimes we have some words here. I’m going to take my BMW x5 and royal blue, and if I wanted to display the variables in a terminal or something, but I want to right align them. How would that work? I’d have to just put a whole bunch of padding in, depending on how long this was and how much space will be used, kind of like this:

          BMW
          x5
          Royal Blue

What we can do, instead of hitting the space bar each time, we can use a left pad function, and you can use .repeat()to code a nice little left padding function.

Here we can return a string, and we need to then pad it with however many characters we need. We’ll take a space and repeat it 10 times.

leftPad.repeat(str, length = 10){
    return `${' '.repeat(length - str.length)}${str}`;
}

console.log(leftPad(make));
console.log(leftPad(model));
console.log(leftPad(colour));

However, if we want it right aligned, we’ll need to subtract however many characters are in the string, so we subtract str.length here before we return the actual string itself in ${str};

I can take make, model, and color, put them in here. It’s going to console.log each one of them out. Console.log leftPad model. I’m going to leave out the length because we’re going to default it to 20, and it should just pass in the make, model, and color.

There we go. See how all these are perfectly left aligned? BMW X5 in royal blue, whereas all of this is however much padding we actually need. That’s a nice little use for repeat.

Very Important

Another little funny one that you can do is, we can take an ES6 template string, and inside of that let’s do a statement where we take a string and multiply it:

${'woof' * 5}

What happens when you take a string and multiply it by a number? You get NaN. Let’s call repeat on that 10 times, and then tack on ‘Batman!’.

`${'woof' * 5}`.repeat(10) + " Batman!";

Those are some four new functions. Put them in your back pocket, and hopefully you’ll get to use them soon!

sanitizing

These last few examples we’ve been creating HTML and inserting it right into the DOM. If you have any sort of security background and you’re probably screaming, "Wes, you must sanitize that data before you put it into the DOM!!!"

A Quick primer on XSS

If you don’t know what that means, essentially when you get data from a user, or whenever you’re displaying data from an untrusted (or even what you think is trusted) source, you must make sure that the user isn’t doing any Sneaky Pete stuff on you, and trying to maybe insert an iFrame, or an image, or to do an XSS attack.

Here I’ve got an example:

const first = 'Wes';
const aboutMe = `I love to do evil <img src="http://unsplash.it/100/100?random" onload="alert('you got hacked');" />`;

const html = `
    <h3>${first}</h3>
    <p>${aboutMe}</p>
`;

const bio = document.querySelector('.bio');
bio.innerHTML = html;

Let’s assume I took this first name in the about me. I got that from a database, an API or something sort of data source where the user had this saved in their database.

They set their bio to be, "I love to do evil," and they inserted an image from Unsplash, which is allowed. You can insert an image into your bio, no problem, but they do the Sneaky Pete thing here by inserting an onload=alert('you got hacked');, so when this image loads, it runs some JavaScript.

That is a huge problem. You cannot let your users run JavaScript on your page because then they could drain your bank account, or delete your app, or post spam, or really anything! Imagine if you let someone run JavaScript on Facebook. You could have people unfriending everyone, or you could look at all of their messages, or send nasty messages on their behalf.

Here I’ve taken the about me and I’ve just popped it into HTML and then I’ve set it into our bio:

const first = 'Wes';
const aboutMe = `I love to do evil <img src="http://unsplash.it/100/100?random" onload="alert('you got hacked');" />`;

const html = `
    <h3>${first}</h3>
    <p>${aboutMe}</p>
    `;

const bio = document.querySelector('.bio');
bio.innerHTML = html;

I’m taking it, carte blanche, putting it into the DOM, I refresh, and I get this message, "You got hacked." That is what’s called an XSS, cross site scripting, where we let someone else run JavaScript on our page. That’s really dangerous.

Sanitizing your HTML

The solution to this is to sanitize your HTML. This is another place where you could use the tag template. In creating all this HTML here, I have all kinds of inputs from a user. But before I put it into my HTML, it’s probably a good idea to run it through a sanitizer, so our HTML will look something like this:

<script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify.0.8.2/purify.min.js"></script>
<script>
const first = 'Wes';
const aboutMe = `I love to do evil <img src="http://unsplash.it/100/100?random" onload="alert('you got hacked');" />`;

const html = `
    <h3>${first}</h3>
    <p>${aboutMe}</p>
    `;

const bio = document.querySelector('.bio');
bio.innerHTML = html;
</script>

I’ve loaded it in this library called DOMPurify. It’s a pretty good library that we use to sanitize. You can have all kinds of options in here in terms of what tags are allowed and aren’t allowed. There are all kinds of sanitize libraries here.

You could make a sanitized tag template and use this library inside of it. I’m going to show you how to do that now:

function sanitize(strings, ...values) {
    return strings.reduce((prev, next, i) => `${prev}${next}${values[i]} || ''}`);
}
const first = 'Wes';
const aboutMe = sanitize`I love to do evil <img src="http://unsplash.it/100/100?random" onload="alert('you got hacked');" />`;

const html = `
    <h3>${first}</h3>
    <p>${aboutMe}</p>
    `;

const bio = document.querySelector('.bio');
bio.innerHTML = html;

So we have a reduce function, which takes in a function and what we start with, an arrow function, which we’ll use the first iteration, prev, our current iteration, next, and i for index. So we’re just going to return a string that tacks all of those things together. We’ve got prev. We’ve got the next. We’ve got values, which is i or nothing.

We still have, "you got hacked" because we’re not finished yet.

function sanitize(strings, ...values) {
    const dirty = strings.reduce((prev, next, i) => `${prev}${next}${values[i]} || ''}`);
}
const first = 'Wes';
const aboutMe = sanitize`I love to do evil <img src="http://unsplash.it/100/100?random" onload="alert('you got hacked');" />`;

const html = `
    <h3>${first}</h3>
    <p>${aboutMe}</p>
    `;

const bio = document.querySelector('.bio');
bio.innerHTML = html;

But instead, what we can do is add a new const called dirty, because our string is dirty because it still has it’s onload, or iFrames, or any of the other nasty stuff people are trying to do.

Now we’ll use our library that we loaded, and it’s called with DOMPurify.sanitize. We’ll sanitize the dirty HTML:

function sanitize(strings, ...values) {
    const dirty = strings.reduce((prev, next, i) => `${prev}${next}${values[i]} || ''}`, '');
    return DomPurify.sanitize(dirty);
}
const first = 'Wes';
const aboutMe = sanitize`I love to do evil <img src="http://unsplash.it/100/100?random" onload="alert('you got hacked');" />`;

const html = `
    <h3>${first}</h3>
    <p>${aboutMe}</p>
`;

const bio = document.querySelector('.bio');
bio.innerHTML = html;

Now when you refresh, you can see see that the onload has been stripped out, along with any other nasty stuff!

tagged-templates

One feature that comes along with template literals, or template strings, is the ability to tag them.

That means is that we can run a template string through a function, and rather than have the browser immediately assign that value to a variable, we can have control over how this actual string is made.

I’m going to show you some examples of when that would actually be useful but first, let’s look at the mechanics of it and how it all comes together.

The way the tag template works is you simply make a function, and you take the name of the function that you want to run against the string, and you just put the name right in front of the template:

function highlight() {
    // do something
}

const name = 'Snickers';
const age = '100';
const sentence = highlight`My dog's name is ${name} and he is ${age} years old`;
console.log(sentence)

This tags it with a function name. What will happen is the browser will run this function, it will provide it with all the information about the string, all the pieces that the person typed, as well as the variables that get passed in. Whatever we return from this function is what sentence actually is going to be.

It acts like a step in between. Before this function actually gets put into sentence, we have the ability to modify it in any given way. Let’s take a look at highlight here:

function highlight() {
    return 'cool';
}

If I just use return 'cool' that is going to take in this entire string as an argument, but then just return the word "cool." Now we see cool in console.

const sentence = highlight`My dog's name is ${name} and he is ${age} years old`;
console.log(sentence); // 'cool'

Obviously, that’s not what we want to do,but this function will take in a few arguments so we can create the string ourselves:

First, we get an array of all the string peices:

  1. My dog’s name is
  2. and he is
  3. years old

After the array of all the strings, the subsequent arguments will be the values that are being interpolated.

In this case, we’re passing name and age.

function highlight(strings, name, age) {
    return 'cool';
}

Now, we could do this. It passes a name and passes an age, but if you don’t know exactly how many values someone is passing, there’s no way for you to really scale it. You could say Arg1, Arg2, go through all the way to Arg100, just in case there are a hundred arguments, but that’s no way to live your life, right?

For this, We can use ES6 rest operator, which is three dots. We’re going to go into that a lot more in a future video, but know for now, if we do ... values, what it’s going to do is take the rest of the values that are passed to that argument, and put them into an array for us.

function highlight(strings, ...values) {
    return 'cool';
}

What’s strings? Strings is an array of three things:

  • "My dog's name is "
  • "and he is "
  • "years old "

As you can see, it breaks up the string into the biggest pieces it can until a variable interrupts it.

We’ve got "My dog's name is" then it pops in a variable, "and he is ", that’s the second item in the strings array, and then, "years old ", which are the three strings that don’t get changed.

The other things we get is an array of values, which we passed in two values here. We get "Snickers" and "100" which are the values that I passed in.

So – the whole point of the tagged template is so that we can create the string ourselves. Let’s move along to creating it!

function highlight() {
   let str = ''; 
}

const name = 'Snickers';
const age = '100';
const sentence = highlight`My dog's name is ${name} and he is ${age} years old`;
console.log(sentence)

I’m using let here. Why? Because we’re going to be appending more strings on to this actual string. If I used const, I wouldn’t be able to tack onto it.

Then, we want to loop over this first strings array here, tack on My dog's name is, and then the first value, and he is and the second value, and then years old and then third value, but in this case, we don’t have a third value.

You can use whatever loop or logic you prefer inside of this function. You could even use a map and then join it together. I’m going to use forEach in my example:

function highlight() {
   let str = '';
   strings.forEach((string, i) => {
       str += string + values[i];
   });
   return str;
}

const name = 'Snickers';
const age = '100';
const sentence = highlight`My dog's name is ${name} and he is ${age} years old`;
console.log(sentence)

That’s going to say, "Give me the first value from the strings and the first value from our values array and tack them on."

We’re going to hit a little bit of an error here. If we return str, the string that we’ve been tacking things onto, we should now see "My dog's name is Snickers and he is 100 years oldundefined."

First of all, remember, that’s because the strings array is always going to be one larger than the values array. When we hit that last one, it’s only going to be a string and there’s going to be no value to tack on the end. You could check if values of [i] is undefined and, if it is, then don’t put it on.

A little trick you can do here, is you can use your values of I or just a blank string:

function highlight() {
   let str = '';
   strings.forEach((string, i) => {
       str += string + (values[i] || '');
   });
   return str;
}

That will adjust if there is no value, it will just return a blank string there.

Tagged Template Usecases

What can we actually do with this? Well, we could change this so any value that gets passed in gets wrapped in a <span> and we can use CSS to highlight it.

You maybe want to show your user which pieces of the string were variables or which pieces of the string that they passed in, maybe it’s their user name or a total for an order. In our case, we just want to highlight the name and the actual age.

function highlight() {
   let str = '';
   strings.forEach((string, i) => {
       str += `${string} <span class='hl'>${values[i] || ''}</span>`;
   });
   return str;
}

Now with our <span>, let’s see what our sentence looks like here. There we go. We’ve got a span with a class of hl wrapped around every single possible one.

<style>
.hl {
background: #ffc600
}
</style>

Then, we can add it to our document instead of using the console:

document.body.innerHTML = sentence;

Once you do that, you’ll see that the values being highlighted. You can go ahead and add a contenteditable to our <span> so that if the user didn’t like it, they can change the value they actually wanted. Maybe they didn’t like that Snickers is a hundred years old, so they could change that value as well. It’s kind of a fun way to do it.

Bring it in, Team

There are much more complicated use cases for that and there are many more in-depth use cases for that, but that is the main idea behind these template tag templates. If you have a string, you pass in the regular string that you want, and then you get all the pieces.

It’s up to you to craft it together and to return some sort of modified data. In our case, we’re wrapping it in a <span>, but you may want to format it or do some if statement and conditional work on all the values.

template-html

Another feature of template literals or template strings is the ability have multi-line strings without any funny business.

Previously with regular string we would have escape the new lines like so:

var text = "hello there, \
 how are you + \
  ";

That gets to be quite a task, to be able to do that. In ES6, we can now use template strings. I like to use these multiline strings when I’m creating HTML markup as a string. You can use backticks here, and use the object properties as variables. These look familiar because they’re in the same format as I’ve been using in some of the previous posts. Let’s define an object and I can show you what I mean:

const person = {
    name: 'Wes',
    job: 'Web Developer',
    city: 'Hamilton',
    bio: 'Wes is a really cool guy that loves to teach web development!'
}

// And then create our markup:
const markup = `
 <div class="person">
    <h2>
        ${person.name}
    </h2>
    <p class="location">${person.location}</p>
    <p class="bio">${person.bio}</p>
 </div>
`;

You can see how this is so much nicer to look at. You will get the whitespace included in the string, but since we’re just creating HTML markup, it doesn’t really matter.

Now, I can take this string and go ahead and dump it into an existing element in an HTML page. Just for sake of an example, you can use a blank page where the only existing element that we have on the page is the document.body, and then we can set our markup variable as the inner.HTML:

const markup = `
 <div class="person">
    <h2>
        ${person.name}
    </h2>
    <p class="location">${person.location}</p>
    <p class="bio">${person.bio}</p>
 </div>
`;

document.body.innerHTML = markup;

You could also use document.createElement to create an element, set the inner.HTML, and then append that to the body, whatever you like, which is the same with markup.

When we refresh the page you see "Wes, web developer, Hamilton, really cool guy," and so on, all on their own individual lines.

If you inspect that, you’ll see it’s all been processed as proper HTML without having to do any document.createElement.

If you console.log the markup just to show you that the new lines are there. You can see that all of the new lines, all of the tabs and the spaces are included as part of that string.

Note: – It’s important to note that any time you are creating HTML and the data comes from the user, we need to escape that data. Much more on this in future post but for now let’s assume this data is clean.

Looping with Template Strings

Another amazing feature of template strings is that you can nest them inside of each other. What if I have an array of dogs and I want to loop over and get myself a list item for each one?

const dogs = [
    { name: 'Snickers', age: 2 },
    { name: 'Hugo', age: 8 },
    { name: 'Sunny', age: 1 }
];

Let’s use a template string, and create an unordered list with the class of dogs, and inside of that I want a list item for each one. But I can’t, I can’t just do something like ${dogs[0].name} because that would be cheating and that’s not really scalable. So how would I loop over every single one?

We can nest template strings right inside of it. How do we do that? Let’s take a look here:

const markup = `
<ul class="dogs">
    ${dogs.map(dog => `<li>${dog.name} is ${dog.age * 7}</li>`)}
</ul>
`;

Here we are using a template string inside of a template string, so we’re going to return a list item, inside of that actual list item we are going to use ${dog.name} and we’re going to say how old they are in dog years, which is ${dog.age *7}.

Now we’ve got all this markup here. Let’s use console.log, and see where we’re at. You should see:

<ul class="dogs">
    <li>Snickers is 14</li>,<li>Hugo is 56</li>,<li>Sunny is 7</li>
</ul>

But we have that comma in there, so how do you get rid of that? We know that map will return an array, so we can simply just use join and an empty string, which will join it without the commas:

const markup = `
<ul class="dogs">
    ${dogs.map(dog => <li>${dog.name} is ${dog.age * 7}</li>`).join('')}
</ul>
`;

If you want to test this, you can use document.body.innerHTML = markup to put it right onto the page for us.

Again, you could do this on their own lines if you prefer to do each on their own lines and indent it, which is just much more maintainable:

const markup = `
<ul class="dogs">
    ${dogs.map(dog => 
            `<li>${dog.name}
            is 
            ${dog.age * 7}
            </li>`
     ).join('')}
 </ul>
`;

Conditional If Statements with Template Strings

Let’s look at an example where we need an if statement inside of our template string. This is taken straight from how you do if statements inside of a React render template, and that is with a ternary operator.

Here I’ve got a song, some data with a name and an artist:

const song = {
    name: 'Dying to live',
    artist: 'Tupac',
    featuring: 'Biggie Smalls'
};

We always have a name of the song and the artist of the song, but sometimes we’ve got a featuring artist. If there is a featuring, we need to include it in our markup so we can add it to our document.body.innerHTML like this:

const markup = `
    <div class="song">
        <p>
            ${song.name} - ${song.artist}
            (Featuring ${song.featuring})
        </p>
    </div>
`;

document.body.innerHTML = markup;

If you load that, you’ll see `Dying to Live – Tupac (Featuring Biggie Smalls).

That works, but what if we delete Biggie Smalls, we get `(Featuring undefined).

If it’s not there, we don’t want the parentheses or the word "Featuring," or anything there. A way we can get around that is by using a ternary operator. Our ternary operator will say if "this" then "that", otherwise nothing:

const markup = `
    <div class="song">
        <p>
            ${song.name} - ${song.artist}
            ${song.featuring ? `(Featuring ${song.featuring})` : ''}
        </p>
    </div>
`;

document.body.innerHTML = markup;

Using the ternary operator, we can use that to add any featured artist if there is one, otherwise it will just use a blank string, which will remove the featured artist brackets.

There we have it – a nice little way to do an if statement right inside template strings.

Template Strings Render Functions

The first few examples were pretty simple, but what happens when your data starts to get a little bit complex?

With nesting inside of nesting, inside of nesting, it starts to get a little bit hairy and harder to maintain your code. What I like to do is create what I call a render function. I’ve sort of taken that from React, where we create separate components that will handle different complex data and different components in our markup.

const beer = {
    name: 'Belgian Wit',
    brewery: `Steam Whistle Brewery`,
    keywords: ['pale', 'cloudy', 'spiced', 'crisp']
};

const markup = `
<div class="beer">
    <h2>${beer.name}</h2>
    <p class="brewery">${beer.brewery}</p>
</div>
`;

document.body.innerHTML = markup;

Just like you’d expect, in your HTML you’ll get the beer name and the beer brewery, and that’s all wrapped appropriately in <h2> and a <p> tags, and it’s looking pretty good. But what if I want to implement our array of keywords that’s nested inside of the actual beer object? I could just go ahead and do map right on one line, but I’d rather kick it off to a separate function, which I’ll call renderKeywords:

const beer = {
    name: 'Belgian Wit',
    brewery: `Steam Whistle Brewery`,
    keywords: ['pale', 'cloudy', 'spiced', 'crisp']
};

function renderKeywords(keywords) {
    return `
    <ul>
        ${keywords.map(keyword => `<li>${keyword}</li>`)}
    </ul>
    `;
}

const markup = `
<div class="beer">
    <h2>${beer.name}</h2>
    <p class="brewery">${beer.brewery}</p>
    ${renderKeywords(beer.keywords).join('')}
</div>
`;

document.body.innerHTML = markup;

You can see that our function an unordered list, and then uses the map function to fill in the keywords from our array as list items. It’s going to give us the keyword, and that is going to return, again, another template string that has the key word inside of it. We’re also using the join function to make sure that our keywords don’t include the commas from the array.

Now this function should just be able to pass it off. It’s only one line, and it should be able to create the unordered list, and the list item, any other HTML that we need to have created inside of this.

If you take a look at our HTML you’ve got your unordered list with all of the list items inside, and you can see that any time you need to render out a unordered list of keywords, whether it’s tied to this particular beer or not, it can simply just use renderKeywords to get the markup it needs.

template-strings

In JavaScript, when you want to put a variable inside of a string, it’s a pain in the ass because you have to stop your string, concatenate on the variable, and then open your string again and keep going.

var name = 'Snickers';
var age = 2;
var sentence = 'My dog ' + name + ' is ' + age * 7 + ' years old.';

Most other programming languages have the ability to just drop your variables right inside of a string and interpolate it, but until now JavaScript hasn’t had this.

What ends up happening is you forget one of your closing quotes, and you get an error and it tells you it’s on line 3. You say “Of course it’s on line 3, but I don’t know where it is!”

We can fix all of that with what’s called template strings, or template literals in ES6. In JavaScript we have double quotes and single quotes to make a string. Now we have a third way to make a string, and that is with back-ticks, which I’ve been using in most of my examples so far.

Let’s take the above code. How do we convert it to ES6 template strings? We switch to using back ticks and then use the ${} syntax inside those strings!

const name = 'Snickers';
const age = 2;
const sentence = `My dog ${name} is ${age * 7} years old.'`;
console.log(sentence);

That is going to pop in, or interpolate, the name and age variables that we previously had set there by using $, curly brackets and the variable name.

You can also run JavaScript straight away inside of these curly brackets, too. You can add in a variable, you can run a function, you can run any JavaScript inside of the curly brackets — including more template strings, but we will talk more about that later.

I’m calculating the age in dog years right inside of sentence by using ${age * 7}, so our console.log will just show a regular sentence, My dog Snickers is 14 years old.

That’s a very basic overview of template strings. However there’s quite a bit more that we can do with them. It can be very handy other than just being able to stick variables inside of it — see you in the next one!

RFB2

Hey Folks – I totally updated and re-recored every single video on my React for Beginners series.

Just under a year ago I launched ReactForBeginners.com — I wanted it to be an accessible, easy to understand and fun introduction to building React applications and website components.

Since then I’ve had 6,317 developers, designers and even a few marketing folk take the course with me. The feedback has been amazing and the series has continued to be the de facto course where people go to learn React.

React has matured a lot in the past year. The core library has deprecated many things, React Router has seen 5 major version bumps, and ES6 has exploded in popularity. Because of all this, I’ve spent the last month re-recording and updating the entire series.

This is a free update for anyone who has bought the course in the past. Simply head on over to your account to stream or download the new videos.

To anyone new to the course, it’s on sale to celebrate the re-launch. As an added bonus, the next 167 people who use the code JAVASCRIPTMOVESFAST will get an additional $10 off.

What Changed?

  1. Switched the build system from gulp and browserify to the much easier to use webpack + create-react-app.
  2. The initial tutorial used React.createClass() and then refactored to ES6 Classes. Since ES6 is much more popular now, I’ve switched to using ES6 classes right away. Of course I have my ES6.io course if you need any extra help there but I make sure to explain classes for anyone new. I’ve also added in lots of content to understand method binding and property initializers.
  3. Remove use of deprecated linkState, switch to explicitly using value= state and onChange= events
  4. Remove all mixin use as React will eventually deprecate mixins.
  5. Introduce linting with ESLint
  6. upgrade to React Router 4 and it’s totally new API
  7. Remove use of @autobind decorator
  8. Upgrade to babel 6
  9. Show how to build and package the application for production
  10. Add in 3 deployment videos
  11. Removed string refs in favour of function refs as React will likely deprecate string refs in the future
  12. Use stateless components when possible and explain when you would use one
  13. Remove spreading of …this.props, only pass what is needed to child components
  14. Upgraded to the new Firebase 3.0
default-func-args

Default function arguments in JavaScript are here. This is one of those features that’s going to make your life much easier, and make your code much more readable and maintainable.

Let’s say we have a function called calculateBill which is going to take in three things: the total cost of your meal, how much tax we need to pay, and then how much you would like to tip your waiter:

function calculateBill(total, tax, tip) {
    return total + (total * tax) + (total * tip);
}

From that, we can return the total amount of hte bill.

Then we’ll make a new variable called totalBill, and we’ll use our new function, to figure out how much all of that costs.

function calculateBill(total, tax, tip) {
    return total + (total * tax) + (total * tip);
}

const totalBill = calculateBill(100, 0.13, 0.15);
console.log(totalBill);

On a $100 meal, with 13% tax and a 15% tip, the console will tells us 128, or $128.

What happens if we want to automatically assume 13% tax rate, and we want to assume a 15% tip rate?

What we could do is just pass in our $100 meal and get our result. If we omit tax and tipcalculateBill(100) our function returns us NaN, or “not a number”. That’s because we’re trying to do math against things that aren’t passed in.

function calculateBill(total, tax, tip) {
    console.log(tax);
    return total + (total * tax) + (total * tip);
}

const totalBill = calculateBill(100);
console.log(totalBill);

If you use console.log to show the value of tax or tip, you’ll see that they show up as undefined.

What we would normally do is we would add an if loop:

function calculateBill(total, tax, tip) {
    if(tax === undefined) {
        tax = 0.13;
    }
    if(tip === undefined) {
        tip = 0.15;
        }
    return total + (total * tax) + (total * tip);
}

const totalBill = calculateBill(100);
console.log(totalBill);

It works fine there, but there’s a whole lot of code that we added.

You might be saying, “Yeah, you can do this, tax equals tax,” or you can do this little trick here where you can say it equals itself.

function calculateBill(total, tax, tip) {
    tax = tax || 0.13;
    tip = tip || 0.15;
    return total + (total * tax) + (total * tip);
}

const totalBill = calculateBill(100);
console.log(totalBill);

I don’t mind that, but it can be a little bit hard on your team to have to read it. If you’ve got four or five different arguments coming in, then you’ve got to do all this crazy code at the top.

Another thing to note is the || trick will fallback to the default if you pass in 0, null, false or any other falsy value. Not exactly what you want when you are trying to tip $0!

So let’s just do without that entirely. What we can do now in ES6 is just simply set it when we define our function, and those things will be assumed.

function calculateBill(total, tax = 0.13, tip = 0.15) {      
    return total + (total * tax) + (total * tip);
}

const totalBill = calculateBill(100);
console.log(totalBill);

If nothing is passed in for that one, then the defaults are going to go ahead. There we’re good to go.

What else we can do?

What if I wanted to pass only the total amount, as well as the tip amount, because I’m a big tipper. Let’s say I’m tipping 25% here, and the tax rate isn’t going to change because I’m still in Ontario.

However, if I just leave the tax empty, we’ll get a syntax error, like I would here:

function calculateBill(total, tax = 0.13, tip = 0.15) {      
    return total + (total * tax) + (total * tip);
}

const totalBill = calculateBill(100, , 0.25);
console.log(totalBill);

How do you leave a hole in here?

Well, what does this essentially check for? It checks for tax being passed undefined so you can just explicitly pass undefined:

function calculateBill(total, tax = 0.13, tip = 0.15) {      
    return total + (total * tax) + (total * tip);
}

const totalBill = calculateBill(100, undefined, 0.25);
console.log(totalBill);

The function is going to say, “Oh, no one passed any tax.” our default 13% and then the big tip is going to kick in here, and we get 138, or $138.

I’ve got another example similar to this one where this is order dependent, and when we hit destructuring, I’m going to show you how do you use an object in destructuring, so that you could pass this in any order, as well as have default arguments. But more on that later.

arrow-func-this

We’ve learned about the concise syntax of arrow functions. We’ve learned about the implicit return of arrow functions. The last thing we’re going to learn about and probably the most important is that the fact that this keyword does not get rebound.

What does that mean? Let’s show an example as to when you might run into this. This is a pretty visual one so you might be better off watching the corresponding ES6.io video. We will be creating this:

See the Pen Arrow Functions and `this`. — ES6.io by Wes Bos (@wesbos) on CodePen.dark

What I have here is I’ve got this div with the class of box right here.

<div class="wrap">
    <div class="box">
        <h2>Wes Bos</h2>
        <p class="social">@wesbos</p>
    </div>
</div>

When you click that box what’s going to happen is a two-stage animation. You click it, and it grows. Then it animates in the h2, and the social paragraph, from the left and from the right.

With the source files, you can try this out in your browser’s element inspector. First add a class of opening to the div:

<div class="wrap">
    <div class="box opening">
        <h2>Wes Bos</h2>
        <p class="social">@wesbos</p>
    </div>
</div>

What that does it actually grows it.

Then if you add a class of open() to it, that will bring in the text.

<div class="wrap">
    <div class="box opening open">
        <h2>Wes Bos</h2>
        <p class="social">@wesbos</p>
    </div>
</div>

It’s always on the <div class="box">, adding opening, and then after a couple of seconds I have a class of open being added to it.

I’ve given you all of the CSS that comes along with it. Nothing too exciting here, and that’s a whole another course together.

Essentially the way it works is when it has a class of opening I just change the width and the height. Then, when it has a class of open, I bring all of the text in. Then I’ve got transitions on everything so it goes has some funky effects.

If you open it in the browser and click it, though, you’ll see that nothing works.

We need to select that element. So in the <script> tags, we’re going to use const, just because we won’t want the reference to the box to change.

const box = document.querySelector('.box');
console.log(box);

If you run that, you can see that the box is logged to the console.

Here we are going to type a regular function, and include a console.log so we can take a look at what’s happening:

const box = document.querySelector('.box');
box.addEventListener('click', function() {
    console.log(this);    
});

It logs this as the same as box. The way you can think about this is you look at what got called addEventListener, and you look at the thing to the left of it, box. What’s box? That’s the div with the class of box that we have.

That’s good. But, if you swap this out with an arrow function here, watch what happens:

const box = document.querySelector('.box');
box.addEventListener('click', () => {
    console.log(this);    
});

We get Window. Why do we get Window here?

That’s because when you use an arrow function, the value of this is not rebound inside of that function. It is just inherited form whatever the parent scope is.

What’s the parent scope of this? It’s Window, as in the browser window.

If you use your console here and type this, you’ll see that this is equal to Window, because it’s not being bound to anything. It ends up by the window.

You don’t just want to go willy-nilly using arrow functions everywhere, because it’s just less to type. You need to know what the benefits and the drawbacks of them are. In this case I don’t want an arrow function, because I need the keyword to reference the actual box that got clicked. That would be even more important if I had a whole bunch of them.

We can’t use an arrow function there. I’m going to bring that back to regular function.

const box = document.querySelector('.box');
box.addEventListener('click', function() {
    console.log(this);    
});

That’s what we want. You generally want these functions for your top level ones. Then inside of that, we’re going to replace console.log with:

const box = document.querySelector('.box');
box.addEventListener('click', function() {
    this.classList.toggle('opening');    
});

Let’s see how that works. The box should animate itself in and out, in and out. If it does that, good.

After maybe 500 milliseconds or so, I want to also toggle open, because that’s the final stage. Remember, it’s a two-stage animation here.

I think we’ll use a timeout for that:

const box = document.querySelector('.box');
box.addEventListener('click', function() {
    this.classList.toggle('opening');
    setTimeout(function() {
       this.classList.toggle('open'); 
    });
});

OK, so does that work? No.

Our console says Uncaught type error cannot read property toggle of undefined. That’s weird. How do I debug that?

Let’s take a look using console.log to help us out:

const box = document.querySelector('.box');
box.addEventListener('click', function() {
    this.classList.toggle('opening');
    setTimeout(function() {
       console.log(this.classList);
       this.classList.toggle('open'); 
    });
});

If we run that, we see that this.classList comes back as undefined. It’s nothing. Why is there no classList on the box?

Let’s take another look, this time we’ll just console.log(this) to get a little deeper:

const box = document.querySelector('.box');
box.addEventListener('click', function() {
    this.classList.toggle('opening');
    setTimeout(function() {
       console.log(this);
       this.classList.toggle('open'); 
    });
});

We’ll see that it’s targeting Window. Why’s that?

If this inside the opening toggle function here was equal to box, why the heck is it not equal to box for the open function?

That’s because we’ve entered a new function, and this inside the function has not been bound to anything, which means that, if it’s not bound to anything, it’s going to be equal to the window. That’s a pain in the ass.

A lot of people would solve this by adding a self variable and use it to trigger the class open like this:

const box = document.querySelector('.box');
box.addEventListener('click', function() {
    var self = this;
    this.classList.toggle('opening');
    setTimeout(function() {
       console.log(this);
       self.classList.toggle('open'); 
    });
});

That’s works, but not the greatest, because we have this weird or some of you like to say var that = this; and etc.

Fortunately, we don’t need to do that anymore if I bring that back to this. What we need to do is just simply make it an arrow function:

const box = document.querySelector('.box');
box.addEventListener('click', function() {
    this.classList.toggle('opening');
    setTimeout(() => {
       console.log(this);
       this.classList.toggle('open'); 
    });
});

Why? Because when you have an arrow function, it does not change the value of this. It inherits the value of this from the parent. We don’t have to worry about the scope changing or anything like that.

We can just go ahead and keep working using this as if it was scoped to this actual function here, just great.

const box = document.querySelector('.box');
box.addEventListener('click', function() {
    this.classList.toggle('opening');
    setTimeout(() => {
       console.log(this);
       this.classList.toggle('open'); 
    }, 500);
});

We should probably put 500 milliseconds in here.

So let’s run that, and click it again and it closes. That’s a little bit funky. I’m going to fix this to be a little bit nicer.

None of this has anything to do with arrow functions. If you’re interested in seeing how I might figure this out, you can stay on with me.

The problem with this right here is that when you toggle an open, it adds a class of opening, then after 500 milliseconds it adds a class of open. When you close it down, you want it to be the opposite.

The way I would probably solve this is to first make two variables.

const box = document.querySelector('.box');
box.addEventListener('click', function() {
    let first = 'opening';
    let second ='open';
    this.classList.toggle(first);
    setTimeout(() => {
       console.log(this);
       this.classList.toggle(second); 
    }, 500);
});

I’m just using variables so we still have this problem.

Let’s add an if statement to switch our variables around. This is going to look forward into our destructuring exercise, but as little hot tip. If we want to switch two variables with ES6 you can simply put them in an array:

const box = document.querySelector('.box');
box.addEventListener('click', function() {
    let first = 'opening';
    let second = 'open';

    if (this.classList.contains(first)) {
        [first, second] = [second, first];
    }
    this.classList.toggle(first);
    setTimeout(() => {
       console.log(this);
       this.classList.toggle(second); 
    }, 500);
});

Because we’ve switched the variables, we should be able to get this to animate in the correct way.

Check this out. Click it open, click it closed, and you have a fun little animation that we’ve made there.

The big takeaway here is that we can use an arrow function for things inside of a normal function and it’s going to inherit the value of this.

when-not-to

Before you start going absolutely bananas on using arrow functions everywhere, we need to chat. Arrow functions don’t replace regular functions. Just like Flexbox and floats, pixels and rems and anything else new that comes along, the older thing still retains lots of utility because it works differently than the new thing.

We talked about the benefits of ES6 Arrow Functions in earlier videos and blog posts but let’s go through a couple examples of when you probably don’t want an arrow function. All of these are just going to boil down to not having the keyword this, but they are also different use cases that you’d run into.

#1 — click handlers

First of all, I’ve got this big button that says ‘Push me’:

<style>
button {font-size: 100px; }
.on {background: #ffc600;}
</style>

<button id="pushy">Push me</button>

When someone pushes or clicks that button, I want to toggle the class of on which should turn it yellow. When someone clicks that button, I’m going to run this following function:

const button = document.querySelector('#pushy');
button.addEventListener('click', () => {
    this.classList.toggle('on');
});

But if we click it, we get an error in the console: TypeError, cannot read property 'toggle' of undefined

What does that mean? Well, if we remember from earlier, it’s the browser’s window attribute, right? We can use console.log to confirm it:

const button = document.querySelector('#pushy');
button.addEventListener('click', () => {
    console.log(this); // Window!
    this.classList.toggle('on');
});

Remember: we talked about that if you use an arrow function, the keyword this is not bound to that element. If we use a regular function, the keyword this will be bound to the element we clicked!

const button = document.querySelector('#pushy');
button.addEventListener('click', function() {
    console.log(this);
    this.classList.toggle('on');
});

In the console, this is now our button, and our big yellow button is actually working. The sames rules apply with jQuery, Google Maps or any other DOM Library you are using.

#2: Object Methods

Now, let’s take a look at this next one, when you need a method to bind to an object.

const person = {
    points: 23,
    score: () => {
        this.points++;
    }
}

We have our method called score, and whenever we call person.score, it should add one to our points, which is currently 23.

If we run person.score(); a few times, we should be at 26 or something.

But if I call person, points is still at 23. Why?

Because it’s trying to add points to the window! Remember, when using an arrow function this is not bound to anything and it just inherits it from the parent scope which in this case is the window.

So let’s do the same thing with an OG function:

const person = {
    points: 23,
    score: function()  {
        this.points++;
    }
}

There we go. That will actually work, because that’s a full on function, and not an arrow function.

3: Prototype Methods

As our third example, we’ll talk about when you need to add a prototype method.

class Car {
    constructor(make, colour) {
        this.make = make;
        this.colour = colour;
    }
}

Here, I’ve got a class. We haven’t learned about classes yet, but just know that this is a way for us to make new cars.

I have a class constructor where, when you call new Car we pass it the type of Car, as well as the colour of the Car.

I can say beemer is a BMW that is blue, and the subie is a Subaru that is white:

const beemer = new Car('BMW', 'blue');
const subie = new Car('Subaru', 'white');

Let’s go ahead and look at them by calling them in the console, you’ll see that subie comes back as Car {make: "Subaru", colour: "white"}, and beemer will come back as Car {make: "BMW", colour: "blue"}, which is what we’d expect.

Now, after the fact, I added on this prototype method:

Car.prototype.summarize = () => {
    return `This car is a ${this.make} in the colour ${this.colour}`;  
};

…and what that allows us to do is that, even after these things have been created, we can add methods onto all of them. So our Car.prototype.summarize method is set, so let’s type into the console: subie.summarize.

If you’re using Chrome’s console, you’ll see that it auto-completes the method, because it’s available to you. Even though we added it after we created the Car, because I added it to the prototype, it’s available in every object that has been created from there.

What this prototype does is it returns this.make which is the make that we passed in, and this.color in a sentence.

However, with our example, this.car is undefined and the colour is undefined. Why is that?

It’s because we try to be cool. We try to be a bit of a hot shot here by using an arrow function. Again, why don’t we use an arrow function here? Because we explicitly need the keyword this so you have to use a regular function:

Car.prototype.summarize = function() {
    return `This car is a ${this.make} in the colour ${this.colour}`;  
};

Now, if we call subie.summarize, it says it’s a white Subaru, and beemer.summarize, we get BMW in blue.

Again, you must use a regular function for that.

4: When you need an arguments Object

For our last example, this is a little bit different:

const orderChildren = () => {
    const children = Array.from(arguments);
    return children.map((child, i) => {
        return `${child} was child #${i + 1}`;
    })
    console.log(arguments);
}

It doesn’t have to do with the keyword “this,” but we don’t have access to the arguments object when you use an arrow function.

This is helpful for when you want to run a function like orderChildren here, which can take unlimited arguments.

It might take one, it might take 100. It’s going to just say “This child was born #1”, or whichever.

For an example, let’s type into the console orderChildren('jill', 'wes', 'jenna'), which passes in jill as our first argument, wes, as our second, and jenna as our third. When you run it, you’ll get an error: ReferenceError, arguments is not defined.

this is because arguments is a keyword that we have in our orderChildren that’s going to give us an Array or array-ish value of everything that was passed in.

However, you do not get the arguments object if you use an arrow function. When you use a regular function, which is going to give us the actual content that we need.

const orderChildren = function() {
    const children = Array.from(arguments);
    return children.map((child, i) => {
        return `${child} was child #${i + 1}`;
    })
    console.log(arguments);
}

Note: Another fix for this is to use a ...rest param to collect all the arguments into an array. We will learn all about that in the rest videos and blog posts!

Again, to go through all those really quickly. Make sure that you aren’t just using arrow functions willy-nilly. In general, if you do not need the arguments object or you do not need this, or you know that you will not need it in the future, then you can feel free to go ahead and use an arrow function on everything else.

arrow-func-examples

Let’s look at a couple more JavaScript arrow function examples.

This is something that comes up often where I’m building an application, and I don’t necessary have the data in the right format that I need.

I’m building a website for a bunch of racers, where the winners have been supplied to me in an array of strings in the order that they placed, and then they also gave me a variable, which includes the race that they won.

const race = '100m Dash';
const winners = ['Hunter Gath', 'Singa Song', 'Imda Bos'];

So Hunter Gath came in first, Singa Song came in second, and Imda Bos came in third.

Ideally for me, I would have an object with name, with the name of the racer, place with the place that they came in, and we can use the race variable to say what they won. Something like this:

{
    name: 'Wes Bos',
    place: 1,
    race: race
}

How would we do that? Well, we can actually use .map() again for that. By the way, map is not the only function that arrow functions work with. Arrow functions work with anything, and they’re particularly useful in these callback situations.

const win = winners.map((winner, i) => {name: winner, race: race, place: i})

We’re going to loop over each winner and return an object for each of the winners here. Our function passes two arguments, the winner string and i, for our index, and we’re going to return our name, race, and place that the person came in.

Arrow Function Implicit Return an Object Literal

That should work, where we’ve got this object here, but it doesn’t work, it throws a syntax error: Unexpected token :

What’s wrong here? Well, earlier we told you that if you take the curly brackets off it’s an implicit return. How do you implicit returncurly brackets when you mean for it to be an object literal, not the actual function block?

What we can do is, you just put parentheses around the object literal so that the arrow function knows it’s an object and not a a function block.

const win = winners.map((winner, i) => ({name: winner, race: race, place: i + 1}));

These parentheses show that you’re actually going to return an object literal, and these curly brackets aren’t for the actual function block. So name is winner, race is the race variable we have, and place is going to be set to i + 1, our index, plus one so that we aren’t zero-based.

Viewing our Data

Now we’ll take a look at our data.

A little hot tip, you refresh. You can type win in the console to see all your objects, but then you got to do all this work on opening them up. What you can actually do is use console.table(win) and you get a sweet-looking table that will show you all the information.

Then the other thing, we haven’t learned about this yet, but race: race in our object looks a little bit redundant. A new feature of ES6 is you can just use race, which is the same thing as saying, race: race Just say the variable race and the property name race is all named race. It’s going to do it just for us.

const win = winners.map((winner, i) => ({name: winner, race, place: i + 1}))

There we go, so that’s an example of doing an implicit return with an object literal.

Arrow Function Filtering Example

There’s another example here where we poll the people in the room for ages.

const ages = [23, 62, 45, 234, 2, 62, 234, 62, 34];

We want to filter this list for people who are older than 60 years old. Normally you’d do something like:

const old = ages.filter(age => if(age > 60))...

Since we can pass it a condition that goes to true or false, and filter will return if it’s true and it won’t return if it’s false, we can just say, “Age is greater or equal to 60.”

const old = ages.filter(age => age >= 60);

That looks like a bit funky because you got an arrow and a greater than, but what that will do is, if the age is greater or equal to 60, it will return true and thus be put into the old array.

That age is going to be put back into this new old array, and we can use console.log(old) to return our filtered array.

arrow-funcs

ES6 has introduced arrow functions which have three main benefits. First, they have a concise syntax. Secondly, they have implicit returns, which allows us to write these nifty one-liners.

Thirdly, they don’t rebind the value of this when you use a arrow function inside of another function, which is really helpful for when you’re doing things like click handlers and whatnot.

We’re going to take a look at a whole bunch of examples as well as we’re going to be using arrow functions all over the place in the ES6.io course.

I’ve got an array of names:

const names = ['Wes', 'Kait', 'Lux'];

I want to add 'Bos' to the end of all three of these.

Normally, you’d do something like this:

const fullNames = names.map(function(name){
  return `${name} Bos`;
});

console.log(fullNames); // Wes Bos, Kait Bos, Lux Bos

We’re going to use backticks here, which is our template strings. Don’t worry exactly about what that is, if you’re not sure just yet. We have a whole chapter on that coming up.

Anyway, It’s going to give me Wes Bos, Kait Bos, Lux Bos in the entire array. It took this array, transformed it into whatever the item was, plus the name “Bos” on the end.

That makes sense to me, but this isn’t an arrow function. Let’s take a look at how we could rewrite that.

Turn it into an Arrow Function

The first thing you do with an arrow function is, you simply delete the keyword function and add in what’s called a fat arrow. It looks like this: =>

const fullNames2 = names.map((name) => {
 return `${name} Bos`;
});

console.log(fullNames2); // Wes Bos, Kait Bos, Lux Bos

If you’ve come from other programming languages, you might have seen that before, but in JavaScript it’s the first time we’re seeing a fat arrow.

It’ll do exactly the same thing as function. If you console.log it, there should be no surprises there. We get the exact same thing.

Removing Parens With Single Params

We can go even further with it where, if you only have one parameter you can take out the parentheses:

const fullNames3 = names.map(name => {
 return `${name} Bos`;
});

console.log(fullNames3); // Wes Bos, Kait Bos, Lux Bos

That’s a bit of a stylistic choice. Some prefer the parenthesis regardless if you have one or more. In many callback fucntions (like our map function) it’s nice to leave them out for a very clean syntax.

Arrow Function Implicit Return

What else could I do with this? I can use what’s called an implicit return.

Hold on — what’s a explicit return?

That’s when you explicitly write return for what you want to return. But a lot of these callback functions that we write in JavaScript are just one-liners, where we just return something immediately in one line. We don’t need a whole bunch of lines.

**So – if the only purpose of your arrow function is to return something, there is no need for the return keyword. **

Our three line function with an explicit return is now a single line function with an implicit return.

const fullNames4 = names.map(name => `${name} bos`);

console.log(fullNames4);  // Wes Bos, Kait Bos, Lux Bos

We did three things here:

  1. delete the return
  2. put it up on all of one line
  3. delete the curly brackets

When you delete your curly brackets, it’s going to be an implicit return, which means we do not need to specify that we are returning ${name} bos.

It will just assume that we’re doing so, and you can console.log it to see the same thing again.

No Arguments with Arrow Functions

Then finally, if you have no arguments at all — in our above examples obviously we need an argument — but if no arguments at all, you need to pass some empty parenthesis there.

Maybe we’ll just return Cool Bos, and they’ll all be Cool Bos at the end.

const fullNames5 = names.map(() => `Cool Bos`);

console.log(fullNames5); // Cool Bos, Cool Bos, Cool Bos

Another pattern you may see is developers using an underscore _ in place of ():

names.map(_ => `Cool Bos`);

We call this a throwaway variable because we’re actually creating a variable called _ but not using it. It’s important to note that the _ does not have any significance at all. I could use any variable name here, we just throw it away.

names.map(x => `Cool Bos`);
names.map(WESBOS => `Cool Bos`);
names.map(_ya___Yayayayay => `Cool Bos`);
names.map(do_yaget_the_point => `Cool Bos`);

Personally I prefer to use () => over _ => when there are no params but I’ll let you make that decision on your own.

Arrow Functions are Always Anonymous Functions

Another thing we need to know about arrow functions, at least right now, they may change this in future versions of JavaScript, is that arrow functions are always anonymous functions.

What is an anonymous function? Actually what’s a named function?

A named function is something like this:

function sayMyName(name) {
  alert(`Hello ${name}`);
}

The benefit to using a named function is that if you have a stack trace, which means if you have an error and you want to figure out, where did this go wrong, sometimes a line number as to where it happened isn’t very helpful, so you need to know actually the name of the function that it got called in.

If you use an arrow function, you cannot name them. None of our arrow functions have a name.

You can, however, put them in a variable. If I were to say something like this, and pass it a name, and create a function declaration that way.

const sayMyName = (name) => {alert(`Hello ${name}!`)}

sayMyName('Wes');

The thing we need to know about that is it is an anonymous function and it will not give us very good stack traces. However, if you’re not too concerned with that, then you can absolutely go ahead.

var-dead

We’ve learned about let and const — what they do, and how they’re scoped. We also know when they can be reassigned and when they cannot, but there’s a question: What Should I actually use?

That’s a bit of a hot topic in the community right now, because some people prefer to still use var. Some people are saying, “var is dead!” Some say, “Use let.” while others always use const.

var isn’t dead – it still does what it always has done — it’s function scoped and you can reassign or re-bind it. You may very well continue to choose it. There isn’t a right answer here, just opinions. Check them out and make your own decisions.

I’m just going to go over two of the leading opinions here. These are both done by some very, very smart people in the JavaScript scene, so I’ll let you pick your own.

This one, by Mathias Bynens, is how I do it. He says that “const is not about immutability where you can change the properties.”

Later on in the article he talks about let vs. const

  • Use const by default
  • Use let only if rebinding is needed.
  • var should not be ever used in ES6.

Whenever you make a variable, assume it’s const. Only use let if you need to update the value of the variable. You can use const to keep it the same value.

Another popular opinion here is from Kyle Simpson, and he also writes a whole bunch of awesome JavaScript books.

  • Use var for top-level variables that are shared across many (especially larger) scopes.
  • Use let for localized variables in smaller scopes.
  • Refactor let to const only after some code has to be written, and you’re reasonably sure that you’ve got a case where there shouldn’t be variable reassignment.

He says, basically, Use var to share larger scopes so you can put them inside of your function, and use let in smaller scopes. If you realize later that you need to update a value, you’d have to go back and make it a let instead of a const. If you use let, it’s easier to go back and refactor them to const.

Both of those are very valid opinions. I’ll let you make your own choice on that, but through the ES6.io series, I’ll be using const by default, let whenever I need to reassign a variable, and stay away from var entirely.

dead zone

Let’s talk real quick about the Temporal Dead Zone. This is a bit of a boring topic, so I’m going to try and make it at least a little fun for you.

This is something that you probably won’t come across too often, but it’s helpful to know in case someone ever slings it out in an interview. You’d be able to talk them about it. First of all, I call it the temporal dad zone, which is kind of fun.

var pizza = 'Deep Dish 🍕🍕🍕';
console.log(pizza);

What happens when you try and log pizza to the console after it’s been created? You’ll see that we actually get to see 'Deep Dish 🍕🍕🍕'.

No big issue there.

What if I try to run console.log before creating it?

console.log(pizza);
var pizza = 'Deep Dish 🍕🍕🍕';

Are we going to get:

  • Undefined
  • An error saying pizza is not defined yet
  • Are we actually going to see 'Deep Dish 🍕🍕🍕'

We get undefined. Why?

Because with var variables, you can only access them as they are defined. Before they are defined, you cannot access the actual value of them, but you can access the fact that the variable has been created before.

However, if I change that to const or let, you’ll now see that pizza is not defined at all. That’s an actual error, and that will break your code.

That is called the temporal dead zone, where you cannot access a variable before it is defined.

They mean that this is the temporal dead zone between console.log and a let or const variable, because you cannot access those kinds of variables before they’re created.

That’s all you need to know. Put that in your back pocket, because you’ll need it someday!

block scope

You can probably see where let and const are going to be useful: if you need to scope something to a block, or if you want to make a variable that cannot be changed by accident or on purpose.

Let’s take a look at a couple of more examples of when it might be useful.

The first one is replacing the Immediately-Invoked Function Expression, or IIFE. I’m not sure if you’ve ever heard of this before, but it was coined by Ben Allman back in 2010.

An IIFE function runs itself immediately, and it creates a scope where nothing is going to leak into the parent scope. In our case, nothing is going to leak into the global scope of the window.

If I have a var variable: var name = 'wes'

You can call that in the console, and that’s fine here. However, the window already has a name attribute, which is needed when you have a window opening up a another window.

That could something that some third-party JavaScript relies on in order for it to run, or maybe another script is using a variable called name and you accidentally overwrite that. It can get a little bit messy.

The way the IFFE fixes that is that the function runs immediately and you put your variables inside of that:

(function() {
var name = 'wes';
})();

These variables are now scoped to the IIFE function, and because var variables are function-scoped, they are not available in the global scope.

If you try to call name in the console now, it’s not undefined, it’s blank because, like I mentioned, it’s just blank because that is a property that lives on the window natively in JavaScript.

If I needed to access our function’s name, obviously, I’d have to do a console.log inside of the IIFE function, but the important thing is that it’s no longer leaking into the global scope.

With let and const variables, we don’t need a function for our variables to be scoped to that.

Why? Because let and const use block scope.

Let’s start over with a const instead of a var

const name = 'wes';

If we call this in the console, we’ll see 'wes', but if we wrap it in curly brackets:

{
const name = 'wes';
}

Our const is going to be scoped to that block. If you try to call name in the console, we’ll get the window’s name, which is blank. But if we add a console.log to our block:

{
const name = 'wes';
console.log(name);
}

…we’ll get wes in the console. You don’t the IFFE stuff anymore. You’re using let and const because they are going to be scoped to that block.

quick tip

The other problem using let and const will fix is with our for loop.

This is something that you probably have all run into with your regular for loop, like one that will count from zero to nine:

for(var i = 0; i < 10; i++) {
  console.log(i);
}

Problems that arise here are two things:

First of all, if I type i into the console, it returns 10. We have this global variable that has leaked into the window, or into a parent scope, which is not something we necessarily want. It’s just a placeholder value that we need to work inside of this loop.

Second of all, maybe you had something that’s going to run after some bit of time, an AJAX request, or, for this case, I going to mark it up with a setTimeout() and that function is going to run after one second:

for(var i = 0; i < 10; i++) {
  console.log(i);
  setTimeout(function() {
    console.log('The number is ' + i);
  },1000);
}

If we run this, all of them are 10. The reason that we have that is because, console.log(i) will run immediately and reference whatever i is. That runs immediately at console.log itself.

However, after one second, this entire loop has already gone through every iteration that it needs to and the variable i here is being overwritten every single time.

The problem with that is that by the time the first setTimeout() runs, i is already at 10, and we don’t have any way to reference it.

If you had an AJAX request where you are looping through a few of them, there isn’t any way without an IFFE to reference what the i variable was when it ran, not what it currently is after the loop.

One quick way we can fix that is if we just change var to let:

for(let i = 0; i < 10; i++) {
 console.log(i);
 setTimeout(function() {
   console.log('The number is ' + i);
 },1000);
}

What do we know about let? It’s block-scoped. We have curly brackets in the for loop. If you run it now, after a second we’ll log zero through nine. We’re not getting 10, 10 times. We getting it as it was declared each and every time.

As a note, you couldn’t use a const for this because it needs to overwrite itself, and you can’t assign the same variable twice. When we use let, it’s going to scope i to our curly brackets.

2

In the last post we learned all about how scoping works with JavaScript let, const and var variables.

We now know that var is function scope, and now we know that let and const are block scope, which means any time you’ve got a set of curly brackets you have block scope.

Now, we need to know you can only declare a variable inside of its scope once.

const key = 'abc123';
let points = 50;
let winner = false;

If I try to update points by re-declaring the let variable:

let points = 60;

The browser says points has already been declared.

However, with var, it will just go ahead and declare the variable, which can cause a lot of bugs, because you might accidentally use the same variable twice.

You can update a let variable, and we’ll take a look more at let and const but you cannot redeclare it twice in the same scope.

Now, what if I had this?

const key = 'abc123';
let points = 50;
let winner = false;

if(points > 40) {
   let winner = true
}

If we type in the console, winner will come back as false. We can add a Console.log line to prove that it runs, but why is winner still false, if we set winner to be true?

The important thing here is that these two winner variables are actually two separate variables. They have the same name, but they are both scoped differently:

  • let winner = false outside of the if loop is scoped to the window.
  • let winner = true inside the if loop is scoped to the block.

If I change our let winner to be var winner, they’ll come back as true, because it’s not inside of a function, it’s not scoped to it, whereas a let variable is.

The other thing we need to know about it is that the difference between let and const is that const variables cannot be updated.

let variables are made to be updated. I may say:

const key = 'abc123';
let points = 50;
let winner = false;

points = 60;

..and that will work just fine.

However, I’ve got that key variable, maybe something that you do not want to ever change, we can use a const, which stands for constant.

const key = 'abc123';

If I try to update it like so:

const key = 'abc123';
let points = 50;
let winner = false;

key = abc1234;

That won’t work because you cannot update a const variable, whereas you can update a let variable.

We’re going to go more into examples of these and you’re going to understand which one to use as we go through, but that’s really all we need to know about it for now.

One other quick thing is that sometimes people think that const means it’s immutable, which means that if I have an object…

const person = {
 name: 'Wes',
 age: 28
}

…and if I try to update something in the const object by typing person = { name: 'Wesley' } it won’t allow me to do that.

However, the properties of a const variable can change. That’s because the entire object is not immutable. It just can’t be reassigned entirely.

The way I like to think about it with an object is that the person is me. I’m not going to ever change, my entire life, but attributes about me are going to change.

Maybe my age, my hair color, where I live — things about me — are going to change. That’s fine, as long as the object that is assigned to Wes is always the exact same object, I can go ahead and set a new age:

const person = {
  name: 'Wes',
  age: 28
}

person.age = 29

That will work just fine, but I cannot ever wipe out the entire variable.

If you do need to freeze everything, we have something called Object.freeze. It’s actually not part of ES6, but you can take a look at it on MDN.

So we can use it on our object:

const wes = Object.freeze(person);

If I try to update Wes.age = 30, it will still say 28 👌

1

There are a couple new ways to declare variables in ES6 that help us out with scoping. We can declare variables with var, which we’ve always used, but now we can use let and const
to declare variables too.

These two have some attributes about them which are going to be helpful for us in creating variables but let’s do a quick review to show you how var, let, and const are different.

Firstly, var variables can be redefined or updated. Let’s use console.log to show the width which we can update the width to be 200, and then we’ll console log the width again.

var width = 100;
console.log(width); // 100
width = 200;
console.log(width); // 200

If you run this in your browser, you’ll see we get 100, 200, which isn’t a big deal. We’re able to update them. You can also put a var in front of line 3 if you were to accidentally redeclare the variable. If you do, it won’t do anything. It will work as you’d expect, but it won’t yell at you for creating the same variable name twice in the same scope because var variables can be updated or redefined.

We also need to remember how var variables are scoped. Scoping essentially means, “Where are these variables available to me?” In the case of var variables, they’re function scope, which means that they are only available inside the function that they are created in. However, if they are not declared in a function, then they are globally scoped, and they’re available in the whole window.

If I created a function and put my var width inside of it, and console logged the width, and then I were to run it? Is that going to work?

function setWidth() {
  var width = 100;
  console.log(width);
}
setWidth();

Of course, it’s going to work because this width is available inside of this function.

But if I also tried to console log the width after I’ve set the width like this?

function setWidth() {
  var width = 100;
  console.log(width);
}
setWidth();
console.log(width); // error, width is not defined

It won’t work. Why won’t it work? Because width is only scoped to that function. It is a local variable to our setWidth function. It is not available outside the confines. Think of the curly brackets as gates, or function jail, and our var variables are in there.

That’s important for us to know. If you do want to globally scope width, we need to declare it outside the function like so, and update it inside the function:

var width;
function setWidth() {
  width = 100;
  console.log(width);
}
setWidth();
console.log(width);

Generally, it’s probably not what you want to do. You want to keep your variables inside of your function. If you need something outside of a function, you want to return it and store that in a variable. That’s something that we need to know about function scoping. But I’m going to show you a use case where function scoping sort of comes back and bites us.

Let’s say we have an age variable and we have an if statement. We want to create a number of dog years. If they are greater than 12, let’s calculate their ages in dog years and show “You are (however many) dog years old” in the console if they’re older than 12.

var age = 100;
if(age > 12) {
  var dogYears = age * 7;
  console.log(`You are ${dogYears} dog years old!`);
}

Just as an aside, you can see I’m using back ticks in this example, but I’m going to tell you all about this in the “Template Strings” section.

The one thing that is a little bit strange here is that var dogYears is just a temporary variable, and I just needed this real quick in order to calculate something and then stick it into a console.log or stick it into a string or whatever. If you go to your browser console and call dogYears, you’ll see that it’s leaked outside of the if statement and it is now a global variable that lives on window, which isn’t really what we want.

Even though this was a temporary variable that I only needed inside of one if statement, because var variables are function scoped and remember, there’s no function here, it’s going to be globally scoped. It’s scoped to the entire window, which is a little bit of a pain here. That is one of the benefits to using let and const. Instead of being scoped to the function, it is block scoped, which is something new.

What is a block? Here is a great example:

// ...
if(age > 12) {
  var dogYears = age * 7;
  console.log(`You are ${dogYears} dog years old!`);
}

// ...

Any time that you see { curly brackets }, that’s a block. Functions are also blocks, let and const are still going to be scoped to a function, but if inside of that function or if inside of some other element that you have, it will be scoped to the closest set of curly brackets.

If I now take this dog years here and change it to let

var age = 100;
if(age > 12) {
  let dogYears = age * 7;
  console.log(`You are ${dogYears} dog years old!`);
}
console.log(dogYears); // error because it's scoped only to the above block

…and I refresh, everything works as we would want. However, if you call dogYears in the browser console, it says, “Dog years is not defined.” Why? Because I declared it as a let variable. It is only declared inside of a block scope, now, not a global scope like var, a block scope, and that temporary variable has not leaked out of the block.

You can also use const and get the same results, which is what we will talk about in the ES6.io video.

es6-facebook-share

es6-facebook-share

The last few months I’ve been hustling away at my next JavaScript course – ES6 for everyone. Today I’m super excited to launch it! ES6.io

ES6 for Everyone is a premium training course to strengthen your core JavaScript skills and master all that ES6 has to offer. ES6 is a major update to JavaScript that includes dozens of new features. With a focus on simplicity and readability, this course is an efficient way to find out what is new in JavaScript and most importantly when and how you should use it.

Join me for a fun and approachable look at all ES6 has to offer — boost your skills and further your career.

share

share

I’m super excited to announce my latest course Learn Redux.

Redux is a way to manage your state in your React (and other JavaScript) applications. I’ve had over 5,000 people take my React For Beginners and this is the answer to “What should I learn next?!”.

It’s 20 videos at just over 2.5 hours of content – easily doable in an afternoon. The videos are totally free and you can thank Sentry for sponsoring my time to create them.

Grab them at LearnRedux.com today!

flexbox-resources

flexbox-resources

Flexbox is unbelieveable – it’s not only making complex layouts easier to build, it’s starting to push the limits of what we can do in the browser and in turn makes us better designers.

Yeah it’s a bit hard to learn. Yeah there are bugs. Yeah the API is funky. Quit your belly achin’ — spend an afternoon learning flexbox and that will all melt away.

With the demise of IE9 for most developers, everyone is learning flexbox! With that, we have seen some fantastic Flexbox resources popup. Here are the best ones to update your skillset and get some practice.

Chris Wright has some great experiments and has done a ton of research into how to best use Flexbox.

What The Flexbox?! — Flexbox.io is a quick, free 20 video course aimed at getting you to drop your float knowledge and understand the fundamentals of Flexbox.

Flexbugs is a Github repo full of the weird cross browser bugs that you may hit accompanied with solutions on how to solve them.

Almost complete guide to flexbox (without flexbox) is a cheatsheet-esque guide that offers backwards compatible alternatives to flexbox properties.

CSS-Tricks Flexbox Reference is a must bookmark for anyone needing a quick visual reference on each of the flexbox properties.

Webflow Builder is a great tool that will help you build Flexbox layouts.

Flexbox Froggy is a really fun game aimed at teaching you flexbox. It helps with the question “How do I get this to go there?!”.

Flexbox in 5 is a quick tutorial that steps you through high level flexbox understanding.

Flexbox Game is another fun game that will help you sharpen your flexbox skills.

aeron

Everyday I get a few emails asking about the specifics of some piece of software or hardware I use.

I change up things fairly often, so this page will serve as a living document and a place to point curious developers to when I get asked.

If there is something missing leave a comment below or ask in my AMA — happy to chat and help you figure out your own situation.

Editor + Terminal

  • Sublime Text V3 beta is my editor — I write more about my setup in my book. I’m keen on Atom, and try it every few months but it isn’t at Sublime Text levels yet for my own personal daily use.
  • I created a theme called Cobalt2 for both Sublime Text and iTerm2 v3 which I use.
  • I’m currently using Operator Mono for a font. Yes I paid the $200 for it. Before that I used Inconsolata for many years.
  • I use Operator Mono in Sublime, iTerm2 (with these settings: http://wes.io/fYY8), and in Chrome Dev tools with Dev Tools Author

Desktop Apps

Recording

Desk Setup

share@1x

Mastering Markdown

Markdown is my favourite way to write everything from training material to github responses and it’s ubiquitous enough that we are able to write markdown on most major platforms.

Markdown is a very simple language and can be easily mastered in under an hour. I made this quick 34 minute mini course for anyone who is looking to learn markdown for the first time, or fill in any gaps along the way, or just see my personal process and workflow when I write markdown.

Enjoy! MasteringMarkdown.com

ss 2016-03-10 at 9.09.24 AM

Don’t you just love little tips that make you say “How did I not know that?!”?

Small incremental improvements are the way that you inch towards mastery of a topic. Every day I learn little things about web development that as a whole make me much better at my job.

This is a list of git tips — you may know a few of them but I bet there are a few nuggets that will help you improve your workflow 1, 5 or 10%.

A big thanks to everyone who shared their tips on twitter.

git add -p

Rather than git add everything or individual files, this -p will allow you to step through each change, or hunk, and decide if you’d like to commit it. This is really handy if you have made two different changes to the same file and want to commit them separately.

git log -5 --pretty --oneline

View your last 5 latest commits each on their own line.

🍟 @luclemo

git shortlog -sn

Quickly get a list of contributors and see how many commits each person has.

👏 @csswizardry

git log --all --graph --decorate --oneline --simplify-by-decoration

This one is the best – you need to see what it does visually:

You’ll never remember this one so put it in your ~/.gitconfig file under [alias]

wow = log --all --graph --decorate --oneline --simplify-by-decoration

😮 @innovati and 🙌 @winstonswchow

git checkout pr/123

Quickly check out a remote for pull request review. You’ll need to set it up like this.

🤘 @linclark

git diff --shortstat "@{0 day ago}"

See how many lines of code you have written today.

💃 @innovati

git checkout -

It’s like the jump button on your TV remote – jump back to to your last branch.

💆 @everyone

git reset --soft HEAD~3

A soft reset will keep your changes but allow you to “uncommit” something.

Instead of doing a squash, Dan prefers to dial back HEAD any number of commits and then add & commit everything into a single commit.

🇷🇺 @dan_abramov

git reflog

David says it best — “Don’t worry, it’s probably saved somewhere”. Git reflog allows you to see every step you have made with git allowing you to retract and reinstate your steps.

😱 @davidnormo

git stash, then git stash pop

Stash let’s you squirrel away unstaged changes, do some work, and then apply those changes back on.

git stash will stash those changes and put them into your list — I like to think of this as an array of changes. Now to get them back you can git stash apply but what Sam is suggesting here is that you use git stash pop instead which will also bring back your changes, but it removes them from your stash “array”.
ok
🏍 @sambreed

git log -S puppy

Search the commit history for the word puppy and display matching commits.

🚀 @chrisrockwell

git latest = for-each-ref --count=30 --sort=-committerdate refs/heads/ --format='%(refname:short)’

Allows you to view your latest branchces – this is helpful for when your branch names are based on bug IDs that you have a hard time remembering.

🔥 @wesbos

git config --global help.autocorrect -1

Mistype or misspell a git command? Immediately re-run the correct command. You can use -1 to 1000 to wait a full second before the command is re-run.

🔥 @wesbos

git commit --amend

Great for squashing staged files into your last commit.

🐙 @carlosperez

git cherry-pick [hash]

As long as the commit has been fetched somewhere, you can cherry pick that code in your own branch without having to merge the entire thing.

🐳 @jonalvarezz

git remote update --prune

Remove local branches that have been deleted from your remote (like GitHub). You can always run git remote prune origin --dry-run to see what will be deleted before going all in.

🍉 @mourawaldson

git rebase -i HEAD~4

Interactive rebase allows you to pick and choose which commits you can pick, squash, reword, edit, or fixup

😎 @Stephn_R

More?

Post yours in the comment below!

es6 + NPM

A big thanks to bitHound for sponsoring my time to research and write this article. Check out their service, which provides continuous analysis and quality checks for both your front and back end JavaScript and its dependencies.


The JavaScript landscape is changing quickly and along with it the way that we work with dependencies in our websites and applications.

This post is for developers who are currently loading in their JavaScript via multiple script tags and finding that dependency management is becoming a little cumbersome as their webpages or applications start to grow.

For a deep dive into everything the spec has to offer, as well as some great comparisons to CommonJS and AMD, check out Axel Rauschmayer’s Exploring ES6 book, particularly chapter 17.

What are JavaScript Modules?

JavaScript modules allow us to chunk our code into separate files inside our project or to use open source modules that we can install via npm. Writing your code in modules helps with organization, maintenance, testing, and most importantly, dependency management.

When we write JavaScript, it’s ideal if we can make modules that do one thing and one thing well. This separation allows us to pull in various modules only when we need them. Modules represent the core principle behind npm — when we need specific functionality, we can install the modules we need and load them into our application.

As time goes on, we’re seeing fewer large frameworks that do everything under the sun while seeing more small modules that do one thing and one thing well.

For example, many of us learned jQuery. It included methods for doing absolutely everything from CSS manipulation to ajax calls. Now, many of us are migrating to libraries like React where often we need to pull in additional packages to perform tasks like ajax or routing.

This article will take a look at using npm and ES6 Modules. There are other registries (e.g. Bower) and other module loaders (e.g. CommonJS and AMD), but there are plenty of articles already on those topics.

Whether you are doing Node or front end development, I believe that ES6 modules and npm are the way forward. If you look at any of the popular open source projects today, such as React or lodash, you’ll see they have also adopted ES6 modules + npm.

Current workflow

Many workflows for JavaScript look like this:

  1. Find a plugin or library that you want and download it from GitHub
  2. Load it into your website via a script tag
  3. Access it via a global variable or as a jQuery plugin

This type of workflow has worked fairly well for years, but not without its issues:

  1. Updates to the plugins have to be done manually — it’s hard to know when there are critical bug fixes or new functionality available.
  2. Messy source control history — all dependencies need to be checked into source control and unpleasantness can result when libraries are updated.
  3. Little to no dependency management — many scripts duplicate functionality but could easily share that functionality via a small module.
  4. Pollution and possible collisions within the global name space.

The idea of writing JavaScript modules isn’t new, but with the arrival of ES6 and the industry settling on npm as the preferred package manager for JavaScript, we’re starting to see many devs migrate away from the above workflow and standardizing on using ES6 and npm.

Hold on. npm? Isn’t that for Node?

Many moons ago, npm began as the package manager for Node.js, but it has since evolved to become the package manager for JavaScript and front end dev in general. Nowadays, we can cut the whole song and dance for installing libraries down to 2 steps:

  1. Install our dependency from npm, e.g.: npm install lodash --save
  2. Import it into the file where we need that dependency, e.g.:
import _ from 'lodash';

There’s a lot more that goes into setting this workflow up, as well as plenty to learn about importing and exporting from modules, so let’s dive into that.

The idea behind Modules

Instead of just loading everything into the global namespace, we use import and export statements to share things (variables, functions, data, anything…) between files. Each module will import the dependencies that it needs and export anything that should be made import-able by other files.

Getting everything working in current browsers requires a bundle step. We’ll talk about that later in this article, but for now let’s focus on the core ideas behind JavaScript Modules.

Creating your own Modules

Let’s say we are building an online store app and we need a file to hold all of our helper functions. We can create a module called helpers.js that contains a number of handy helper functions — formatPrice(price), addTax(price) and discountPrice(price, percentage), as well as some variables about the online store itself.

Our helpers.js file would look like this:

const taxRate = 0.13;

const couponCodes = ['BLACKFRIDAY', 'FREESHIP', 'HOHOHO'];

function formatPrice(price) {
    // .. do some formatting
    return formattedPrice;
}

function addTax(price) {
    return price * (1 + taxRate);
}

function discountPrice(price, percentage) {
    return price * (1 - percentage);
}

Now, each file can have its own local functions and variables, and unless they are explicitly exported, they won’t ever bleed into the scope of any other files. In the above example, we might not need taxRate to be available to other modules, but it’s a variable we need internally within this module.

How do we make the functions and variables above available to other modules? We need to export them. There are two kinds of exports in ES6 – named exports and a single default export. Since we need to make multiple functions and the couponCodes variable available, we will used named exports. More on this in a second.

The simplest and most straightforward way to export something from a module is to simply stick the export keyword in front, like so:

const taxRate = 0.13;

export const couponCodes = ['BLACKFRIDAY', 'FREESHIP', 'HOHOHO'];

export function formatPrice(price) {
    // .. do some formatting
    return formattedPrice;
}

//  ... 

We can also export them after the fact:

export couponCodes;
export formatPrice;
export addTax;
export discountPrice;

Or all at once:

export { couponCodes, formatPrice, addTax, discountPrice };

There are a handful of other ways use export, make sure to check the MDN Docs if you run into a situation where these aren’t working for you.

Default export

As mentioned before, there are two ways that you can export from a module — named or default. Above were examples of named exports. In order to import these exports into another module, we must know the names of the variables/functions we wish to import — examples of this coming in a second. The benefit of using named exports is that you can export multiple items from a single module.

The other type of export is the default export. Use named exports when your module needs to export multiple variables/functions, and use a default export when your module only needs to export one variable/function. While you can use both default exports and named exports within a single module, I’d advise you to pick only one style per module.

Examples of default exports may be a single StorePicker React Component or an array of data. For example, if we have the following array of data that we need to make available to other components, we can use export default to export it.

// people.js
const fullNames = ['Drew Minns', 'Heather Payne', 'Kristen Spencer', 'Wes Bos', 'Ryan Christiani'];

const firstNames = fullNames.map(name => name.split(' ').shift());

export default firstNames; // ["Drew", "Heather", "Kristen", "Wes", "Ryan"]

Just like above, you can append the export default in front of a function you wish to export as well:

export default function yell(name) { return `HEY ${name.toUpperCase()}!!` }

Importing your own modules

Now that we have separated our code into little modules and exported pieces that we need, we can go ahead an import parts or all of those modules into other parts of our application.

To import modules that are part of our codebase, we use an import statement and then point to a file’s location relative to the current module — just like you are used to in any HTML src path or CSS background image. You’ll notice that we leave off the .js extension as it’s not required.

It’s important to note that we don’t import modules once and have them available to the entire application as globals. Whenever one of your modules has a dependency on another module — say our above code needed a lodash method — we must import it into that module. If we require the same lodash function in 5 of our modules, then we import it 5 times. This helps keep a sane scope as well as makes our modules very portable and reusable.

Importing named exports

The first thing we exported was our helpers module. Remember we used named exports here, so we can import them in a number of ways:

// import everything as methods or properties of an object
import * as h from './helpers';
// and then use them
const displayTotal = h.formatPrice(5000);


// Or import everything into the module scope:
import * from './helpers';
const displayTotal = addTax(1000);
// I'd recommend against this style because it's less explicit
// and could lead to code that's harder to maintain


// or cherry pick only the things you need:
import { couponCodes, discountPrice } from './helpers';
const discount = discountPrice(500, 0.33);

Importing default exports

If you recall, we also exported an array of first names from people.js, since this was the only thing that needed to be exported from that module.

Default exports can be imported as any name — it’s not necessary to know the name of the variable, function, or class that was exported.

import firstNames from './people';
// or
import names from './people';
// or
import elephants from './people';
// these will all import the array of first names

// you can also get the default export like so:
import * as stuff from './people'
const theNames = stuff.default

Importing modules from npm

Many of the modules we will use come from npm. Whether we need a full library like jQuery, a few utility functions from lodash, or something to perform Ajax requests like the superagent library, we can use npm to install them.

npm install jquery --save
npm install lodash --save
npm install superagent --save
// or all in one go:
npm i jquery lodash superagent -S

Once these packages are in our node_modules/ directory, we can import them into our code. By default, Babel transpiles ES6 import statements to CommonJS. Therefore, by using a bundler that understands this module syntax (like webpack or browserify) you can leverage the node_modules/ directory. So our import statements only need to include the name of the Node module. Other bundlers may require a plugin or configuration to pull from your node_modules/ folder.

// import entire library or plugin
import $ from 'jquery'; 
// and then go ahead and use them as we wish:
$('.cta').on('click',function() {
    alert('Ya clicked it!');
});

The above code works because jQuery is exported as a CommonJS module, and Babel transpiles our ES6 import statement to work with jQuery’s CommonJS export.

Let’s try it again with superagent. As jQuery, superagent exports the entire library as a default export using CommonJS, so we can import it with whatever variable name we like — it’s common to call it request.

// import the module into ours
import request from 'superagent';
// then use it!
request
    .get('https://api.github.com/users/wesbos')
    .end(function(err, res){
        console.log(res.body);
    });

Importing Pieces or Cherry Picking

One of my favorite things about ES6 modules is that many libraries allow you to cherry-pick just the pieces you want. lodash is a fantastic utility library filled with dozens of helpful JavaScript methods.

We can load the entire library into the _ variable since lodash exports the entire library as a the main module export (again, Babel transpiles our import to treat it as if lodash is using export default):

// import the entire library in the _ variable
import _ from 'lodash';
const dogs = [
  { 'name': 'snickers', 'age': 2, breed : 'King Charles'},
  { 'name': 'prudence', 'age': 5, breed : 'Poodle'}
];

_.findWhere(dogs, { 'breed': 'King Charles' }); // snickers object

However, often you will want just one or two lodash methods instead of the entire library. Since lodash has exported every single one of its methods as a module itself, we can cherry-pick just the parts we want! This is made possible again because of how Babel transpiles your import statement.

import { throttle } from 'lodash';
$('.click-me').on('click', throttle(function() {
  console.count('ouch!');
}, 1000));

Making sure modules are up-to-date

Some resistance to the whole “small modules” way of coding is that it’s easy to end up with a dozen or more dependencies from npm that all interact with each other.

The JavaScript ecosystem is moving very quickly right now, and keeping your dependencies up to date can be a headache. Knowing when both your own code and your dependencies have bugs, security flaws, or just general code smells isn’t as easy as it used to be. We need to know if anything in our project is insecure, deprecated, outdated, or unused.

To solve this, bitHound offers a fantastic service that will constantly monitor your code and let you know when there is anything wrong with your dependencies, as well as provide an overall score of how well your repo is doing. Find out how yours stacks up, it’s free for all your open source projects.

bitHound integrates with GitHub and BitBucket and has also rolled out automatic commit analysis which will notify bitHound of changes to your repository’s branches. When your dependencies are out of date, you’ll be pinged in Slack or HipChat or get an email detailing everything.

bitHound also has branch status on Pull Requests – set up pass/fail criteria and bitHound will post the status right to GitHub or Bitbucket.

Another tool that works well with bitHound is called npm-check-updates. Install globally on your development machine with npm install npm-check-updates -g and then run ncu. To quickly check if your packages have any available updates. If they do, you can run ncu --upgradeAll to automatically update all packages in your package.json. Make sure to run a npm install after doing this to fetch the latest code from NPM.

The Bundle Process

Because the browser doesn’t understand ES6 modules just yet, we need tools to make them work today. A JavaScript bundler takes in our Modules and compiles them into a single JavaScript file or multiple bundles for different parts of your application.

Eventually we won’t need to run a bundler on our code and HTTP/2 will request all import statements in one payload.

There are a few popular bundlers, most of which use Babel as a dependency to transpile your ES6 modules to CommmonJS.

  • Browserify was initially created to allow node-style commmonjs requires in the browser. It also allows for ES6 modules.
  • webpack is popular in the React community. It also handles many module formats, not just ES6.
  • Rollup is built for ES6, but seems to have trouble with sourcemaps — I’d check on this one in a few months.
  • JSPM sits on top of npm and SystemJS.
  • Ember CLI is an easy-breezy command line tool similar to webpack for users of Ember. It uses Broccoli under the hood.

Which one should you use? Whichever works best for you. I’m a big fan of Browserify for the ease of getting started and webpack for many of its React integrations. The beauty of writing ES6 modules is that you aren’t writing Browserify or webpack modules — you can switch your bundler at any time. There are a lot of opinions out there on what to use, so do a quick search and you’ll find plenty of arguments for each tool.

If you are already running tasks via gulp, Grunt, or npm tasks for your existing JavaScript and CSS, integrating Modules into your workflow is fairly simple.

There are many different ways to implement a bundler — you can run it as part of your gulp task, via your webpack config, as an npm script, or straight from the command line.

I’ve created a repo detailing how to use webpack and Browserify along with some sample modules for you to play with.

Importing code that isn’t a module

If you are working on moving your codebase over to modules but aren’t able to do it all in one shot, you can simply just import "filename" and it will load and run the code from that file. This isn’t exactly ES6, but it’s a feature of your bundler.

This concept is no different than running concatenation on multiple .js files except that the code you import will be scoped to the importing module.

Code that requires a global variable

Some libraries, such as jQuery plugins, don’t fit well into the JavaScript Modules system. The entire jQuery plugin ecosystem assumes that there is a global variable called window.jQuery that each plugin can tack itself onto. However, we just learned that there are no globals with ES6 modules. Everything is scoped to the module itself unless you explicitly set something on the window.

To solve this, first ask yourself if you really need that plugin or if it’s something you could code on your own. Much of the JavaScript plugin ecosystem is being rewritten to exclude the jQuery dependency and to be made available as standalone JavaScript Modules.

If not, you will need to look to your build process to help solve this problem. Browserify has Browserify Shim and webpack has some documentation on it.

Gotchas

When exporting a function, do not include a semicolon at the end of the function. Most bundlers will still allow the extra semicolon, but it’s a good practice to keep it off your function declarations so you don’t have an unexpected behavior when switching bundlers.

// Wrong:
export function yell(name) { return `HEY ${name}`; };
// Right:
export function yell(name) { return `HEY ${name}`; }

Further Reading

Hopefully this was a nice introduction to using npm and ES6 Modules. There is a lot more to learn and in my opinion the best way to learn is to start using them in your next project. Here are some fantastic resources to help you along the way:

Thanks + Updates

A huge thanks to Stephen Margheim, Kent C. Dodds, Mike Chen, Ben Berman, and Juan Pablo Osorio Ospina for reviewing and providing excellent feedback on this article.

If you have any suggestions, code samples, technical updates or clarifications you would like to add to this, please send on over a pull request.

ss 2015-12-07 at 2.45.50 PM

A few weeks back, the WordPress community was abuzz when Automattic announced Calypso — the new WordPress admin interface build with Node and React.

This weekend Matt Mullenweg, the creator of WordPress, spoke about JavaScript in his yearly keynote “The State of Word”. In it, he gave the WordPress community homework — to Learn JavaScript, Deeply. To go out and make 2016 the year that you finally take those steps into getting comfortable with JavaScript.

To see Matt acknowledge this shift in the tech stack has me really excited and it confirms that JavaScript is exploding, and regardless of what you use to build your websites, JavaScript must be a major part of it.

Take Every Opportunity to really beef up your JavaScript Chops — Mall Mullenweg, Creator of WordPress

That said, I know there are many developers in the WordPress community who have been just getting by stringing together themes, jQuery plugins and Stack Overflow answers. There are many developers who feel burned, who feel it’s too hard to learn or just something they can get by without. There will always be varying degrees of JavaScript involvement in your sites, but the one constant is that the types of sites and the interactive interfaces that you make with WordPress are happening more in the browser and are requiring some level of JavaScript knowledge to get going.

So — how do you learn JavaScript? My answer is always this: Build things, build things, build things!

And while this is a simple answer to give, and is one you will get from many experienced developers. It’s frustrating to hear, because:

  1. You aren’t sure what you should build — either from lack of ideas, or that you aren’t 100% sure what you are capable of
  2. You need at least some fundamentals before you can get started!

My answer is still to find a project that you are excited about, and invested in and see it through to completion. Along the way you are going to need some resources that will help you out. I’m compiling a list of resources here. This will be a living list — if you have something that has helped you, or something you have created and would like it added, please leave a comment below and I’ll get it added to the site.

Go forth and learn JavaScript. Will it be hard? Yes! Is everyone else smarter than you and maybe JS just isn’t for you? No! JavaScript doesn’t have a learning curve, it’s more like learning mountains. It’s hard, but push through it with nothing but hustle and repetition and you’ll get it, trust me, I’ve seen this with hundreds of students at HackerYou.

Video

In Person

These are pretty localized – so search in your local area for a coding school – most should have full time, evening and weekend classes.

Books

There are tons and tons of book roundups – here are a few:

Editor Based Code Alongs

Podcasts

Read Other people’s code

RFB2

I’m super excited to announce React For Beginners – my new premium step-by-step training course to get you building real world React.js + Firebase apps and website components. You probably can’t stop hearing about React as of late and that is because it makes building interactive interfaces both really fun and easy.

This is my second premium product after my Sublime Text Book and many who have taken the free Flexbox.io and CommandLinePowerUser.com courses are now learning react.

This course has only been out for 3 weeks and over 2,300 other devs have already joined me in learning React.js! If you are interested in leveling up your JavaScript skills and learning React, head on over to ReactForBeginners.com and take at what it all covers.

Enjoy!

ss 2015-11-24 at 10.23.45 AM

What’s up with WordPress and JavaScript? Are they ditching PHP and moving to JavaScript?

Yesterday Automattic (the company behind WordPress) announced Calypso, a new admin interface for anyone using a WordPress website.

As a JavaScript developer, I was excited to hear that it was built entirely in JavaScript. I was even more excited to hear that it was built in React, because I’m a huge WordPress fan and I just launched React For Beginners — my two worlds are colliding!

It seems like there is a lot of misinformation in the community. Let’s clear this up and understand what it means for us as Web Developers.

WordPress is not being rewritten in Node.js

Relax. WordPress is written in PHP, but the Calypso admin interface for WordPress is written with popular front end tools like React and Lodash.

This is part of a popular trend – use your server to just give us raw JSON data, and then build your application entirely in JavaScript to consume that JSON data. WordPress essentially becomes an API which you can pull and push data from. This decoupling of the view and the backend logic has let the developers of WordPress move much faster because they don’t have 12 years of PHP view logic dragging them down.

What about WordPress is Node.js?

So, why are we seeing tweets about Node.js? Well, almost all front-end tooling is built in Node.js. Calypso is built with popular node tools like WebPack, Babel, Jade, Uglify, Hot Loader, Marked and over 100 other modules.

This is how the front end space is evolving and frankly I’m glad to see WordPress start using them because its one space we don’t see a lot of people using these tools.

Isn’t it just for WordPress.com accounts? What about self hosted? Plugins? Custom post types?

Calypso is an editor and an RSS reader for WordPress.com sites. You can, however, use it to manage your self-hosted WordPress account. Once you enable Automattic’s JetPack plugin, you can manage your content with Calypso.

I went ahead and built a copy locally to try it out.

WordPress Calypso React App

Right now, you can only manage, Pages, Posts, Themes, Menus, Plugins and a few settings. Everything you need to manage a blog.

What is missing is an interface for custom fields, custom post types and any custom interface that a plugin would expose. This is a deal killer for most devs as we aren’t using WordPress just as a blog, but I can only assume this will be coming.

What does this mean for me as a WordPress Dev?

Right now? Nothing. But this is thunder in the distance as to what is to come in the WordPress.

Much of a theme writing I do is already in JavaScript – I often use WordPress as just an API to get data out of, and then use frameworks like Angular, React, Google Maps or jQuery to display that data. I’m not building an entire website in a JavaScript framework, but much of the interactive view layer of these sites is moving into JavaScript frameworks.

Our trusty PHP template files aren’t going anywhere anytime soon, but I’ll bet you dollars to donuts you’ll be writing a lot more JavaScript in your WordPress sites in the years to come.

It’s all about the experience

Since Calypso is open source, I’m curious to see what will come next. I can imagine developers like Elliot Condon from Advanced Custom Fields and the folks at Web Dev Studios are excited about this. This means we can build much more flexible plugin and admin interfaces which will in turn make clients extremely happy.

There is a reason why things like Squarespace are becoming popular — the interface for creating a beautiful website is a breeze and WordPress is now _react_ing in a huge way.

Start learning JavaScript

So as a WordPress builder, don’t rush to this, but don’t write it off – keep an eye on it.

For many this is going to be the last straw with JavaScript. Plugins and STack Overflow questions can get you pretty far, but the front end dev landscape is changing, it’s hard to ignore all that has happened with JavaScript in the last few years.

If you aren’t super comfortable with JavaScript, it would be a great time to start learning. It’s a little hard at first, but you can do it, no problem. I’ve seen hundreds of my students at HackerYou do it, and I know you can too.

Wes Bos at Fronteers Conference 2015

Wes Bos at Fronteers Conference 2015

Last month I had the privilege of heading out to the Netherlands for Fronteers conference. In addition to some training the day before the conf, I did a talk on Modern Workflow + Tooling.

In this talk, I review a handful of tools that every front end developer should know about. From image compression with Gulp or Grunt to JavaScript Modules and using NPM as a package manager.

Follow along with the slides here.

A big thanks to the crew at Fronteers – this was a extremely well put together conference. Enjoy!

yoytube

Since I wrote Sublime Text Power User and recently released React for Beginners – one of the questions I get most often is how do I use Emmet shortcuts right inside of my JSX?

There are lots of tricks out there, but this is the proper way to get everything setup without any hacks.

Grab the snippet code from https://gist.github.com/wesbos/2bb4a6998635df97c748

ss 2015-10-19 at 2.31.20 PM

Arrow functions are a really handy new part of the ES6 JavaScript spec.

Along with shorter, more concise syntax one of the benefits is that is handles the keyword this a little differently. More specifically, it doesn’t change the binding of this when you enter into a new function that was declared with an arrow.

So, while you’ll use this in any of your JavaScript, here is a problem we have all run into with jQuery events, and how you can fix it with ES6 arrow functions.

    // Go from this code:
    $('.cta').on('click',function() {
      var that = this;
      setTimeout(function() {
        $(that).toggleClass('on');
      }, 1000)
    });

    // To this code:
    $('.cta').on('click',function() {
      setTimeout(()=> {
        $(this).toggleClass('on');
      }, 1000)
    });

22076759852_6f0d9117d7_k

21468088723_62f0ddfcaa_k

I’ve been to a ton of conferences, as a speaker, a trainer and an attendee. Most of the conferences in our industry are top notch – I’ve been inspired, I’ve learned and I’ve created many fantastic friendships.

Conferences can be expensive, so when you do go to one, make sure you make the most of it. Here are a few things I’ve learned that you can use to maximize your learning and meet some of the best people in our industry.

Get on Twitter a few days before

Buzz around the event starts to grow and you can often start to familiarize yourself with others going to the event. Read up on anyone who you would like to specifically meet so you have something to talk about. I often get “Hey — thanks for your flexbox/sublime text/whatever tutorial – it really helped me.” and its such an easy way for both of us to launch into a comfortable conversation.

Grab lunch with Speakers

If you live in the area of the conference – see if any of the speakers want to grab lunch or dinner the day before the conference. More often than not, the speakers are in a foreign city corralled in their hotel room. They are going to order room service anyways, so you might as well extend the gesture and see if they want to grab a bite to eat. I’ve made many friendships and have gotten some of the best consulting work of my career this way.

Meet everyone!

Many conference talks are streamed online, so why even attend? A huge part of a conference is in the people that you will meet – for many this is the primary reason of attending.

I often find that people come off a little sour, or aggressive, online and upon meeting them in person they are the kindest people I’ve ever met. If you are intimidated by some of these larger figures in our space, just remember they are regular people and are probably as shy as you are — here are a few tips on how to do that…

Stay off your phone during breaks and meals!

This is probably the hardest thing and I catch myself pretending to look at my phone all the time. It’s awkward, but bite your tongue and say Hi to someone else who is milling around. Most people at conferences don’t know anyone, we’re all in the same place.

Go to the conference parties 🎉

Good conferences make sure the music is low/off and there are non-alcoholic drinks available for anyone who doesn’t drink. This is a fantastic opportunity to meet tons of other developers in a short amount of time.

This goes for speakers as well 😐

Sometimes we see little posses of speakers do their own thing and it bums me out. As silly as it may seem, many of the attendees really look up to you are dying you meet you.

Wear your name badge with style

You might think it’s lame, but it’s the best way to have people remember your name or even make the connection to your twitter account. Some name badges have a habit of flipping over – make sure yours is pointing the right way because everyone sneaks a peak at your name when you join a group.

Ask good questions

What do you do doesn’t cut it – we’re all devs. What are you working on? What was your favourite talk? What did you think of Ember? Ask questions that will open up the conversation.

These are some of the smartest people in our industry – imagine what would happen if everyone met each other?!

Sit with random people for lunch 🍔

Is this spot taken — do you mind if I sit here? The answer is always “No – it’s all yours! I’m ____ – nice to meet you!”

Invite others to lunch

If you are going out for lunch, put out a call on twitter for anyone to join you. There is nothing more sad than seeing a McDonalds full of people wearing their conference lanyards sitting by themselves.

I’ll always be the poutine pied piper at conferences here in Toronto.

Lunch Topic Tables

Sometimes conferences will have lunch topic tables dedicated towards certain topics – jump into one of those or even organize your own the week before by tweeting. This always goes over well.

Practice your break away.

After a while conversations grow stale and it’s time to meet new people. Getting trapped is easy, mastering your out is key. As Jerry Seinfeld would say there is no better way to dismiss someone by saying “it was so nice to meet you”.

Jump into conversations

If there is someone you would like to meet or a group you would like to join, just jump in with a “Hey I heard you talking about React – I hope you don’t mind if I jump in.” When there is a small lull, do the rounds of “Hey – I don’t think we have met, have we?”. Often when I do this, I find out that at least half the circle doesn’t know each other and it’s a chance for everyone to meet each other.

On the flip side, if you sense someone lurking at the side of your conversation, pause your conversation, be a human and say Hi!

Ask who should I meet?

I think this one is from Tim Ferris, but I’ve found many successfully have used it. When you are breaking away from a conversation – just ask them who you should meet next. It’s an easy in when you can walk up to someone and say “Hey – Sarah said we should meet – just wanted to say hi!”.

Say Hi to the speakers

They aren’t rock stars and more often than not they don’t know anyone and are a ball or nerves on top of that because of their talk the next day. It’s so easy to ask about their talk. I know I love to get asked about my talk because it gives me a chance to dry run some of the ideas and I often pick up valuable insights from the questions/responses I get.

Take notes / visual sketches

I don’t do this, but I know many find it a fantastic way to pay attention. Report back to your team or write a post summing up the conference. The best way to solidify something to yourself is to explain it to others.

Here are some great examples from #fronteers15

Watch Twitter

All events will have a hashtag where you can follow along with the chatter. This is a great opportunity to get more context for the talk as well as find & follow some really great people in the industry.

Be as open minded as possible

Check any preconceptions at the door. I could link you to 2013 JSConf where everyone was bashing this stupid idea for a JS framework called React. Conferences are about new ideas and changing the way we work — give everything a chance before going all negative nancy on the talk.

Choose at least one thing to put into practice immediately afterwards.

I’m always jacked up on some sort of technology after a conference. Choose something that you can immediately put into practice and keep that momentum going!

Plan ahead!

A schedule will keep you focused on the important talks/events – especially if there are multiple tracks going on at once.

Read the code of conduct.

Most conferences will have a code of conduct. Read it and treat everyone with respect.

Say thank you to the organizers

Running a conference is often a thankless job that takes months and months of work. The organizers are often volunteers and are doing it for the industry. A written note or even an email goes a long way.

Watch Twitter for a few days after

There is a steady stream of links, tweets, conversations and slide decks the few days following the conference. It’s a great time to tweet at speakers telling them how much you enjoyed their talk as well as find your new friends that you met at the conference on twitter.

Make the most of it!

Hopefully you learned a few new tips that will make your next conference even more enjoyable. We have an amazing community filled with some of the best people I’ve never met – make sure to make the most of it!

Big thanks to Peter Peerdeman for the photos used in this post!

pagespeed-header

Google Page Speed Insights gives your site a score for speed an useablilty, and while I had a great score for useability, my score for speed was a pathetic 51/100. My site is WordPress, and because of the plugin ecosystem inserts many blocking assets into your head, WordPress often gets flack for being slow.

So – armed with an hours worth of time, I set out to fix my own website while recording my progress. I’m far from a performance specialist, but hopefully this shows you that making your sites fast is a relatively simple task that can pay off huge for your users.

I mention a few WordPress/Apache specific things in this video, but the tips should apply to any site/server config.

Links:

.htaccess config:

# 1 Week
Header set Cache-Control "max-age=604800, public, must-revalidate"

<IfModule deflate_module>
  <IfModule filter_module>
    AddOutputFilterByType DEFLATE text/plain text/html
    AddOutputFilterByType DEFLATE text/xml application/xml application/xhtml+xml application/xml-dtd
    AddOutputFilterByType DEFLATE application/rdf+xml application/rss+xml application/atom+xml image/svg+xml
    AddOutputFilterByType DEFLATE text/css text/javascript application/javascript application/x-javascript
    AddOutputFilterByType DEFLATE font/otf font/opentype application/font-otf application/x-font-otf
    AddOutputFilterByType DEFLATE font/ttf font/truetype application/font-ttf application/x-font-ttf
  </IfModule>
</IfModule>
ss 2015-08-25 at 1.10.54 PM

How do you comment in JSX? Regular JavaScript comments in JSX get parsed as Text and show up in your app.

Comments in JSX are weird and when searching for information, it’s hard to find a straightforward answer. So here it is:

You can’t just use HTML comments inside of JSX because it thinks they are real DOM Nodes:

render() {
  return (
    <div>
      <!-- This doesn't work! -->
    </div>
  )
}

You’ll need to use JavaScript comments inside of
You can use regular /* Block Comments */, but they need to be wrapped in curly braces:

{/* A JSX comment */}

Same goes for multiline comments:

{/* 
  Multi
  line
  comment
*/}  

Kind of a pain, but React devs has stated they do not plan to add regular JS commenting to JSX.

If you use Sublime Text, I’ve created a little snippet so you can just type jc + TAB to get a quick comment. Download it here. To install, PreferencesBrowse Packages → Put snippet in User folder.

I’m still on a hunt for a for a fix to get the comment shortcut working – or even a small package that would toggle them on and off. If anyone is a interesting in working on this (and knows Python) – let me know!

ss 2015-08-21 at 11.03.49 AM

In What The Flexbox, one of the biggest questions I’ve received is “how do you get your colours to show up in Sublime Text like that”?

I’ve answered it maybe 20 times now. The trick is getting them to show up all the time, instead of just when you click a color. This is one of my favourite packages because it works in CSS, Stylus, Sass and Less! Here is a quick 101. Watch the video or read the text below:

First, install the Color Highlighter package from Package Control

Next, restart Sublime Text.

Then, in Preferences → Package Settings → Color Highlighter → Settings – User

Use the “filled” setting to make them show all the time.

{
"ha_style": "filled"
}

Enjoy! You can also grab my Sublime Text Book and use WESBOS for $10 off.

ss 2015-07-28 at 2.45.04 PM

ss 2015-07-28 at 2.45.04 PM

Hey everyone – I’m super excited to announce that I’ve released my third big video series. It’s called What The FlexBox?! – a simple, free 20 video series aimed at getting you to master CSS Flexbox.

I created this because while Flexbox is one of the best things to come to CSS layouts in years, it’s a bit hard to initially learn. These 20 videos are short and focused on a single topic each – pick and choose which topics you need clarity on. The last 7 videos are all code-alongs where we will build some really great layouts with CSS Flexbox.

Grab them at Flexbox.io. Enjoy and let me know what you think!

ss 2015-07-19 at 10.44.25 PM

Update: The teespring is now over! Thanks to everyone who purchased a shirt, hoodie or tank. All 10 winners have been picked and emailed about shirt arrangements. Enjoy!

I love JavaScript and I love shirts! Do you? If you do, then you should get a JavaScript Shirt, Tank or Hoodie in blue or black on TeeSpring. I’ve set the campaign to $12 per shirt, which means that there is no profit being made here – it’s just an effort to get JS devs some really great shirts!

people-js-shirts

Available in high quality American Apparel, these shirts are screen printed and are the top quality — no iron ons here. I’ve ordered from Teespring many times and I’ve always been very happy with the product. The campaign needs to sell We have already sold the 15 needed, so grab yours today and you for sure get it!

Tshirt Giveaway!

In an effort to get the word out – I’ll be giving away 10 shirts! Simply Enter Here → and you’ll be notified if you have one a shirt. You may pick any shirt available and it will be mailed anywhere in the world. Good luck!

FAQ

Did you make the JS Logo?

No, but it’s a community project licensed under MIT so you are welcome to print it on your own stuff as well!

What if I buy a shirt, and then win?

If you win and have already bought one, I’ll make sure you get a refund so you don’t have to pay for one!

Can I get one in ${color} || ${garmentType} || ${design}

I’ve made a handful of different options available that should suit most tastes – if you aren’t fond of the design or shirt types, I’d love to hear what you would like best, but this time around it’s all I’m offering

Why are they so cheap?

I’m not looking to make any money off selling these shirts. I know developer love t-shirts and stickers, and after a successful sticker giveaway, I thought I’d try my hand at doing a few shirts as well!

I have a question about Sizing, Shipping, Prices

Please contact TeeSpring directly for those questions.

mailchimp-to-sendy

mailchimp-to-sendy

I absolutely love MailChimp but as my email list starts to grow, I’m finding the monthly payment too expensive. With a list of my size, I was paying about $2500 per year. Since I don’t send out a regular or weekly email, I was pretty much paying $200+ a month to hold onto email addresses.

After a listen to this codepen radio podcast on how they use a transactional email provider to send their emails, I went looking for other solutions.

This is when I stumbled upon Sendy – a self-hosted PHP-based solution that is just the right amount of work to replace my MailChimp needs all together. It works by hooking into Amazon’s SES (or another transactional email provider like SendGrid or Madrill via SMTP) to send your emails out. You pay $65 once for Sendy and then $1 per 10,000 emails sent via SES.

So – I decided to give it a shot. It’s far from a perfect replacement for a heavy MailChimp user, but for someone who is somewhat technical and knows a little bit about email, it’s totally worth putting a few hours into getting it setup.

Setup

Sendy isn’t a service – it’s just a codebase that you run yourself on your own server – kind of like running your own WordPress. You’ll need your own PHP server for this – I run mine on a cheap Bluehost account.

The setup was really easy, just like WordPress you put your username, password and database info into a config file.Then, they have little popups telling you what to do next and how to get Amazon SES setup. The only snag I hit was setting up a cron task to check for emails to send every 5 mins, It wasn’t in the instructions but this page details how to do it on most hosts with cpanel.

List Size

Your server doesn’t actually do the sending of the email – it pings the SES API and let’s amazon send the email. This is crucial for your emails actually showing up in users inbox rather than getting marked as spam.

By default amazon gives you 200 emails per day for free. You have to request more sending space – I asked for 20,000 / day and they gave me 50,000. If you have a need for more than that, Amazon will increase it once you have proven you have a low bounce + spam reporting rate. I’ve heard it needs to be less than 1% which should be easy to hit if you are following all email newsletter best practices.

Editing the code

Another good/bad things about this is that you can edit the code. There were a few spots where I wanted to customize the dashboard with a daily tally of signups – this was easy enough to do by cracking open the codebase and making a few changes myself. The code is pretty simple, but feels crufty.

API Endpoints

When replacing MailChimp, I had to swap out all my ajax endpoints from hitting MailChimp to my own. Sendy has an API to do this, but it doesn’t support JSON, JSONP or CORS in addition to just spitting out a plaintext response. This is a problem if you want to use JavaScript to hit the API endpoint. A quick fix of adding header("Access-Control-Allow-Origin: *"); at the top of the subscribe php file fixed this and allowed me to do cross-domain API calls.

Backups

The last, and probably most important thing is that there is no service making sure your data is safe from server crashes. If your database goes missing or gets corrupt, you are pooched. There are many ways to do automated backups of a database, I’ve opted for a pretty simple email script that dumps the database and emails it to me daily. In my email I’ve got a rule that automatically archives them.

Segmentation

One feature that Sendy is missing is the ability to segment your list. If you want to email just male users who live in Canada and have bought 2+ items, you have to export your list, do a little excel magic, and import those subscribers into a new list. Not the end of the world, but definitely a feature I’d like to see.

Final Thoughts

As you can see, it’s not a 1:1 replacement of MailChimp, but if you look at your needs, Sendy might be a really nice option. I’ve put probably about 2 hours of work into getting it running and it’s been running without a hitch for 3+ months. I’d definitely recommend it!

stickers

stickers
Hey there – in an effort to promote a few of my projects, I got a whole bunch of stickers made! I’ve been handing them out like candy locally, but many have asked if I could mail you a few.

For $2, you will get a 5 sticker pack – that will help cover the cost of shipping and the PayPal Fees. Will ship anywhere in the world.

The stickers are:

  • Command Line Power User — my free video series on ZSH, Z + related tooling.
  • Sublime Text Power User Badge – my book + video series on mastering Sublime Text
  • Good At Gulp – an upcoming book + video series I’m working on
  • Gulp Logo – only 100 of these left!
  • What The FlexBox – an upcoming video series on FlexBox

Interested? I have enough stickers for about 150 packs. Fill out the form below and I’ll throw them in the mail for you. By signing up, I’ll send you an email when I launch new video or book tutorials.

Sorry Folks – I’ve given them all away. Make sure to follow me on twitter or like my FB page – I’ll give away some more once I’ve got them printed!

Artboard 1

Web tooling is changing at an extremely rapid pace right now and there is a sense of exhaustion, being overwhelmed and anxiety of becoming out of date. “Why is this stuff moving so fast?” cry the developers.

Artboard 1

JavaScript var is dead? We should use ES2015 let and const now?

CSS is getting variables, nesting, scoping and custom selectors. Preprocessors like Sass and Stylus are dead, long live PostCSS.

Just learned Grunt? Oh you should use Gulp – wait no, Webpack.

Still laying out your sites using floats like a sucker? Flexbox is here!

Just built a project using protocol relative // – that’s an anti-pattern now. Oh and jQuery .hide() is bad for performance, so cut that out.

Finally dipping your toes in Angular? Oh, it’s totally changing in 2.0. Wait, shouldn’t you be using React? Haven’t you heard of Aurelia or JSBlocks?

Whenever a new framework, tool or technique comes out, I hear more groans than celebrations.

How are we supposed to get any work done when everything keeps changing?

It’s going to keep changing

It’s human nature to resist change, and it’s kind of a hard pill to swallow for some. Working on the web means that things change really quickly. We’re never to to settle on a technology stack and hang it out – we will always see innovation, people pushing the envelope on both what is possible and the best way to get things done.

It’s not really changing that fast

What you see on twitter, HackerNews and in your newsletters isn’t necessarily what everyone is using. Companies make multi-year investments in technology and will stick to their stack for quite some time. So as much as you think that everyone scraps their current setup for a shiny new framework every 6 months, it isn’t the case at all.

Would you guess that Spotify is built with LESS? Or TweetDeck is highly reliant on jQuery. Yuck, right? No – those were the technologies that were evaluated at the time. There are better options now, but it’s not causing their app to crash or business to fail.

Wait it out and Evaluate

Am I going to drop my JavaScript framework for JSBlocks today? No way! Am I going to keep my ear to the ground and see how people like it? Absolutely. We have all been burned by picking up technologies when they are too early, and it’s important to watch out for that.

At JSConf two years ago, I was there when Facebook introduced React.js and they got laughed off the stage because they thought the idea of markup in your JS was ridiculous. Now I’m starting to swap my beloved Angular.js out for React.js. I waited for the community as a whole to test and embrace it. It’s at a point now where enough people I trust are using it, not because it’s new and cool, but because it’s the right tool for the job.

I sure am glad that facebook decided to put out React.js and push how we think about these frameworks. We had Angular and Backbone at the time, and many would have said we had enough frameworks.

Same goes for PostCSS – it’s a pretty new idea to ditch your Sass for PostCSS and CSS Next. Should you do today? Probably not. Should you keep your ears open and see if momentum for transpiled CSS picks up? Yes yes yes.

Just Build Websites

Making stuff is how you get better, so just build websites.

In the wise words of Chris Coyier, just build websites. Don’t get me wrong, what you use to build them is really, really important, but it’s even more important to actually be continually building things and improving on your skill. That is how you get better, just do a lot of work.

As you get better, these new frameworks and tools become way less daunting and the anxiety caused by things moving too fast will subside because you know that you can easily pick it up in a day or two.

So how?

So – to sum this up. Things are always going to change and that is fantastic news for our industry. You won’t become obsolete overnight if you keep your ear to the ground, honestly evaluate new technology and never stop building stuff. Here are a few tips:

Newsletters

Subscribe to weekly newsletters that give you a high level overview of what is new. Peter Cooper runs some of the best ones around. Take 5 minutes a week to read over the list – no need to click through to every link but keep tabs on what you keep hearing over and over. Chances are that if you hear about something every week, it’s starting to gain traction.

Side Projects

ABC – always be coding. If your work doesn’t allow you to try new things as frequently as you like, have a side project that you are invested in. You can use this to try out new tech you otherwise might not be able to.

One New thing

If you do regularly start new projects, make it a point to try one new thing in every project. It might just be trying Flexbox on a smaller part of a site, but you are making progress.

Self Improvement

There is a wealth of information out there and you should take advantage of it. Whether it’s taking a class at something like HackerYou, watching some free tutorial videos (like http://CommandLinePowerUser.com), or reading a book from someone in the industry (hint: https://SublimeTextBook.com), you should make a point to dedicate a few hours every week to self-improvement. You picked this industry, so it’s your responsibility to keep up.

That’s it, That’s all

TLDR; Yes our industry moves quickly, but that is because it’s getting better and better. If you are always iterating on your skillset in small ways, you will be just fine – don’t worry 🙂

ss 2015-04-13 at 4.03.32 PM

Have you ever wished you could use background-size:cover; on regular elements? Well, it turns out you can with a CSS property called object-fit – and with the recent release of FireFox 36, we can start to use it in our designs as we have really good browser support for it.

See the Pen Object Fit for Videos by Wes Bos (@wesbos) on CodePen.

It’s a popular design trend to have videos and images span the entire width and height of an element. Problems arise when it comes to the media’s ratio – they never quite fit perfectly width and height wise – especially with dynamic content and responsive viewports.

Enter object-fit. It’s a new CSS3 property that we can use to stretch embedded media (videos and images) across the entire parent, while still maintaining the aspect ratio. No JavaScript required!

How does it work? It’s pretty easy – first you start with a container that has a defined width and a height on it – for our purposes I’m using viewport units so get a perfect 100% width and height of the screen. Then on the video or image itself, we use object-fit: cover;. You’ll now see the video span across the entire element – it’s cropped either at the left/right or the top/bottom to ensure full coverage.

We can also use object-fit:contain;, which is the same as background-size:cover;, it won’t crop the video but rather show ensure the entire video is always visible. There are a few more values available, but these are the most likely use cases when trying to replicate background-size:cover; with a video.

Check out the demo – http://codepen.io/wesbos/full/YPmyxy/ or view the code below. Enjoy!

ss 2015-04-02 at 2.20.32 PM

ss 2015-04-02 at 2.20.32 PM
Today I’m excited to announce my latest project – CommandLinePowerUser.com. It’s a free 11 video series for web developers on learning a modern command line workflow with ZSH, Z and related tools.

I created this video series after a successful launch of my Sublime Text Book + Video Series. The terminal is the perfect companion to Sublime Text, and as web developers I find we are spending more and more time in the command line with tools such as Git, Gulp, Grunt, Bower and so on. The command line is daunting at first, but hopefully with these videos you will find tips, tricks and a comfort in working in terminal.

Head on over to CommandLinePowerUser.com and grab the videos!

Speed Learning

I was joking with some friends the other day that I rarely read books. While this is technically true, I do consume a ton of audiobooks, conference talks, video tutorials, podcasts and blog posts. It’s what keeps me growing as a developer and entrepreneur. With informational resources, it’s easy to find them piling up. We all have a list of tutorials we would like to watch, blog posts we should read and audiobooks we would love to listen to, if we only had the time, right?

Over the past 6 months I’ve been teaching myself to speed learn. That is, consume this information as fast as possible while maintaining or increasing my comprehension of the material.

Learning from the Blind Community

Now before you write this off as “not for you” because you don’t like to listen to sped up voices that resemble a chipmunk, let’s take a quick look at the blind and #a11y community. A few years ago at the Snow Mobile conference, I saw Kevin Jones, who is blind, demonstrate how he uses his iPhone without seeing it.

In addition, experienced users often like to speed up the reading rate to 300 words per minute or more, which is more than the inexperienced listener can easily understand.

http://webaim.org/techniques/screenreader/

While the entire presentation was eye opening, the one thing that stood out to me was the speed at which the iPhone was speaking back to him. All the attendees were blown away at the speed, to which Kevin said “Oh, I’ve slowed it down for you“. It turns out that many blind users have trained themselves to comprehend insanely sped-up voices in order to make up for not being able to visually read the text and navigate around their devices.

Learning to Speed Learn

So – this is what brought me to speed learning. The process is fairly simple – you need to ease into it. I started listening to content at 1.25x. At first it may seem a little fast, but after a few hours it becomes the norm. Going back to 1x now seems like slow motion. After a few months of gradual bumps I’m now at anywhere from 1.75x to 2.3x depending on the type of media (more on this in a second).

On average, podcasts, conference talks and video tutorials are spoken at around 150 WPM. Professional audiobooks are usually a little less. I speak at 145wpm in this Animate.css tutorial. With a little training, you can easily listen to this video at 2x and above if Youtube allowed for it. I find this technique especially helpful for long YouTube tutorial where you find yourself jumping ahead to the parts actually want.

I asked Kevin about how fast his screen reader runs at. He told me “Usually around 400 450 wpm but it can go up to 700”. Note that the regular human reads at 250wpm and speaks around 125! He noted that he also uses this for learning material – for fiction he slows it down for enjoyment.

I don’t have to really explain why this is ideal, but I’ll state it for the sake of saying it straight up:

Consume 2x the amount of content, learn twice as much in the same amount of time!

So, check out that Animate.css tutorial and try to watch it in 1.25x – can you handle it?

Each persons voice is different. I find that I can listen to Seth Godin’s audiobooks easily at 2.5x but quick talking Renee Richee starts to get a little chip-munky around 1.75x.

Tools

So, what do you use to listen to sped up media? It’s important to have good tools for playing this back as poor ones will result in your audio or video skipping or jumping.

Podcasts

Most podcatchers will include a speed up function, but I’ve been in love with Marco Arment’s Overcast for the iPhone. Not only does it have the ability to speed up podcasts, but it has Smart Speed which analyzes the track and removes pauses and gaps in talk shows. I can easily listen to a podcast at 2x and with Smart Speed turned on, I sometimes see the track jump to 2.3x with the gaps taken out.

speed

Video Tutorials

The YouTube player has speeding up to 2x built in but I prefer to watch my tutorials with VLC. I use the youtube-dl command line tool to download my youtube videos for offline viewing and then use VLC to speed them up. VLC is the best piece of software I’ve found for listening to watching media so far.

Blog Posts & eBooks

While this is still new to me, I’m playing with the OSX screen reader in Safari & iBooks to read the text back to me as I read the text on the screen. I find this helps me keep a good pace and focused on the text.

ss 2015-03-09 at 7.31.05 PM

Audiobooks

Most of my audiobooks come from Audible, so I use their built in functionality which works great and goes all the way to 3x. I’m not at 3x yet, but we can dream!

Headphones

One thing I’ve found is that limiting distraction is important for speed learning. At the gym I’ll use regular Apple earbuds, but while taking a walk or sitting on the train I use a pair of Bose QC25 noise canceling headphones. They aren’t cheap but well worth the investment if you are really into speed learning.

Other

What do you use? I’m always open to suggestions on how to improve my speed learning. Comment below or tweet me @wesbos

I’m really not the first person to uncover the benefits of speed learning, but I’ve found this technique super helpful and many of my students at HackerYou have started to train themselves as well. Anyone can do this.

There is a great [post on Quora] (http://www.quora.com/How-much-longer-does-it-take-to-listen-to-an-audiobook-than-it-does-to-read-the-equivalent-paper-or-eBookabout the actual stats behind this and I couldn’t agree more.

If you like efficiency and use Sublime Text, check out my book + video series Sublime Text Power User. Use code WESBOS for $10 off!

clipboard

This is a little known secret of Sublime Text – the ability to have multiple items in your clipboard history and access them with the keyboard.

To access the clipboard history, simply hit + K, + V – so just add the + K infront of your regular paste shortcut. Windows users swap out with Ctrl.

Watch the video for a quick tutorial on how to use it with your workflow:

Like this tip? Check out my book + video series for tons more!

ss 2014-11-17 at 3.25.14 PM

Hey everyone – a little trick here today with the HTML5 audio element and the Google translate API.

Turns out you can use this query string to dynamically create an audio element. We can then encode our text, pop that url into an audio element and play it with a few lines of JavaScript.

It’s worth noting that this isn’t the real way to do text to speech, but its a very simple, cross browser solution that can help you out in a pinch.

Here is a quick video detailing how it works – I’d love to see what you all do with this.

ss 2014-10-31 at 9.58.57 AM

Update: November 2014 – these theme has received a major UI upgrade for new Sublime Features and editor tweaks.

I love text editor colour schemes. I’ve tried dozens of them over the years but always found myself coming back to trusty old cobalt. I liked this theme quite a but but I didn’t love it. So, over the years I’ve tweaked and tuned cobalt into a theme that I am very happy with. Its easy on the eyes, works well across many languages and takes note of those little UI elements like the caret, searches and bracket matching.

I have had quite a few friends use my theme and they seem to be sticking with it. So, I’ve decided to release it to the masses. To download it, head on over to the github repo. As always, would love to hear any feedback you may have 🙂

Quick aside: I wrote a book on sublime text which comes along with a video series. If you like my themes and blog posts on Sublime Text, you will love this!

#cobalt2
A Sublime Text theme based on our old blue friend cobalt.

A refined colour scheme that is easy on the eyes and takes small UI elements into account. Includes full sublime theme (sidebar, search, tabs, etc…) as well as support for SublimeLinter, git diffing and a growing number of plugins.

See below for examples. Read more at http://wesbos.com/cobalt2-theme-sublime-text-2/

Installation

With Package Control

  1. Open package control toolsCommand Palette and type Install Package
  2. Search for Cobalt2 and hit enter
  3. Lastly, open PreferencesSettings - User. Add the following two lines:
"color_scheme": "Packages/Theme - Cobalt2/cobalt2.tmTheme",
"theme": "Cobalt2.sublime-theme",

If these are the last two lines of your settings file, make sure to omit the trailing ,

Screenshots

Sidebar Icons

Dirty Tab and Selected Tab

Indentation Guides — Guide, Stacked Guide and Active Guide

Use "indent_guide_options": ["draw_normal", "draw_active"] for this

GitGutter Support

Autocomplete

Command Palette

GoTo Anything

Tabs, Spaces and Comments

Folding Lines

Searches

Highlighted Line

JavaScript

CSS

PHP

Ruby

Python

Markdown

Contributing

While cobalt2 covers all languages, I write mostly JavaScript and CSS so I welcome any additions for other languages.

Thanks

Some icons from Soda Theme by Ian Hill

Kyle Knight for pushing cobalt2 past the code screen and styling the entire editor.

Seti UI Atom theme for the sidebar icons

Official Colours

Yellow: #ffc600
Blue: #193549
Dusty Blue 35434d
Dark Blue: #15232D

You may also like:

Cobalt2 Theme for iTerm https://github.com/wesbos/Cobalt2-iterm

Sublime Text Power User Book

square-share

After over a year of writing, I’ve launched my book and video series on Sublime Text!

The idea for this book was spurred on after a few blog posts on Sublime Text — my readers loved the tips and were always asking for more!

Wait no longer – the 25 chapter book and 20 video package is now available! This book is going to really help you become a better and more productive developer. Head on over to SublimeTextBook.com to see what it’s all about!

ss 2014-09-30 at 12.39.44 PM

A few days ago there was a buzz about a new Sublime Text package called Takana which claimed to do live editing of Sass. As someone who works on fairly large Sass projects, I was skeptical but decided to give it a short.

Wow, it is fast.

Takana is built upon the blazing fast C/C++ libsass and works in parity with Sublime Text to listen to any changes in your code (not just a save).

This is huge for those who work with Sass and Sublime Text in their workflow. Here is a video exploring how to install and get up and running with some HTML, Sass and the Bourbon library.

ss 2014-09-17 at 12.35.04 PM

We need to have a talk about phone numbers on our mobile sites. This is such a small change, but when left out, it causes a major inconvenience for your users.

I’m talking about when phone numbers on a website aren’t tapable. Often the HTML is so that mobile operating systems cannot select the phone number alone and you are forced to remember/recite or write down the actual number.

So, when you put a phone number on a website, don’t just use any old element, use a link with the tel protocol.

So, you links look like this:

<a href="tel:+14168342343">416-834-2343</a>

You can put whatever you want inside the link – just like normal links!

<a href="tel:+14168342343">Call me Maybe? <img src="hehe.gif"></a>

This is better for your users, better for business owners and better for the site’s SEO. Win-win-win.

That’s all, please help me in spreading this best practice by sharing this article.

ss 2014-08-12 at 1.22.54 PM

I posted this simple tip to twitter and it was instantly popular with developers from all around the world. It’s a small improvement that makes a big visual difference in your applications.

Since a tweet is only 140 characters, I thought I would expand on best practices a little bit in a post.

Using UTF-8

A few mentioned that you can just go ahead and use the unicode × instead of the HTML entity &times;. As long as your document is setup for UTF-8, go ahead. I personally rather use the HTML entity &times; because I can remember and type that, whereas × needs to be copy and pasted from a blog post like this.

Accessibility

If a visually impaired user uses a screenreader like JAWS to access your website, this will read multiplication to them. So, it is very important that you use proper aria attributes. Something like this will work great:

<a href="#" aria-label="Close Account Info Modal Box">&times;</a>

or better yet:

<button aria-label="Close Account Info Modal Box">&times;</button>

Other Appropriate Characters

A few more mentioned that it would be better to use &#x274C; and &#x274E; as they are real × characters rather than just the multiplication sign. While these are great, they are 1) Not supported on many systems. I’m on osx 10.9.4 and Chrome Canary and they are just boxes. ❌ ❎ 2) twitter and the iPhone swap them out with goofy looking emojis.

So unfortunately, not a good solution just yet.

ss 2014-07-21 at 2.35.55 PM

Choosing a font to use in your editor is a very important step in your workflow that many developers don’t think twice about. Small things like the difference between 0 vs o or l vs 1 and large things like the readability of the font is key to your productivity and strain on your eyes.

If you are still using the default that came with your editor, it might be worth checking out a few below and see how you like coding with each of them.

Since talking about text editor configuration is a huge interest of mine, This list has been compiled over the last year talking to developers at meetups and on twitter. So while the list isn’t totally complete, It’s a great reflection of what developers are using these days.

Consolas

M+2m

inconsolata

Menlo (sublime default)

Monaco

Ubuntu Mono

Adobe Source Code Pro

ANONYMOUS PRO

Dejavu Sans Mono

Envy Code R

Hermit

Have a favourite that isn’t listed? Comment below or tweet at me and I’ll add it to the list.

capslock

I’m a big keyboard shortcut user. After a while you may find that you are running out of easy keyboard shortcuts.

One little trick that many developers do is to remap their capslock key to something a little more useful.

In my case, I remapped my capslock key to open up the Divvy window manager.

Whatever you use it for is up to you, but don’t just let a perfectly good key sit dormant! Watch the 5 min video below or follow the instructions. Happy keyboarding!

Disable the Capslock key

First thing you’ll need to do is open System PreferencesKeyboard → Then click the Modifier Keys button in the lower right.

Set your capslock key to No Action and repeat for every keyboard you have attached in the “Select Keyboard” dropdown. If you are on a laptop with an external keyboard you’ll need to do this twice.

ss 2014-07-18 at 11.08.45 AM

Remap the Key

Now that Caps Lock is disabled, we need to remap it to another key. When you press a key, the OS sends a KeyCode to the program letting them know what key was pressed. I made a little site to help you with this in JavaScript: http://keycode.info.

To do this, we need to use a program called Seil (previously PCKeyboardHack). Download, install and open it.

Check the first box that says “Change Caps Lock” and set the keycode to be one that you do not use and ideally a key that you do not have. A popular choice here is 80, which maps to F19. Unless you have a huge keyboard, you probably do not have an F19 key.

Now when you press your Caps Lock key, they system will interpret this as a press of the F19!

Now you get to choose which program you want to map Caps Lock to. I chose Divvy:

ss 2014-07-18 at 11.15.13 AM

It works with any program that accepts a hot key including Alfred and Slate.

ie-testing

Testing on other browsers can be a pain, especially if you are on a Mac and need to test on the many versions of Internet Explorer.

Microsoft gets this and has made the process extremely simple. I’ve seen a few guides on how to get up and running with virtual images of Windows, but none of them cover the entire process from start to finish.

So, if you are new to cross browser testing, or just have never had a chance to get your environment setup perfectly, here is a short 11 minute video on how to do just that.

Links mentioned in this video:

https://modern.ie/en-us/virtualization-tools

https://www.virtualbox.org/wiki/Downloads

emmet-value-bumping

One of my favourite things about Sublime Text is the Emmet package. Most people know it for the code completions, but it also has a handful of helpful utilities.

One of those is the ability to increment / decrement values in CSS by 0.1, 1, and 10 – just like you probably already do in dev tools.

incement:decrement

Take 1 minute to watch this video on how to use it, save yourself many minutes in the future!

That’s it! Next time Git requires you to edit a file or commit message, Sublime Text will pop open!

ss 2014-06-05 at 6.10.10 PM

Animate.css  is a fantastic little library of Animations that takes the messy keyframing out of web animations. While they can definitely be abused, short and subtle animations are a great way of adding feedback and interaction to your website or web app.

While you can get away with just using the CSS classes, you will most likely want to apply these animations on command with JavaScript. This short tutorial will show you how to get setup with animate.css, use it properly with jQuery and listen for the animationend event to take the classes off.

Hope you enjoy, please leave any questions or comments below!

ss 2014-06-01 at 3.25.53 PM

Toggling comments in Sublime Text is broken and it’s time you fix it. If you work with HTML/JavaScript you have probably run into this while using the ⌘ + / comment toggle.

broken-toggle

Sublime Text thinks it is JavaScript, so it uses a JavaScript comment! The problem is that the script tag is acutally HTML, so we need to use an HTML comment to comment it out. We want something like this:

<!-- <script src="jquery.js"></script> -->

The underlying problem is inside the HTML syntax file and it is actually an easy fix.

We need to edit the HTML.tmLanguage file that is located in preferencesbrowse packagesHTML.

Open it up and look for a line that looks like the following. It should be around line 286.

<string>(?:^\s+)?(&lt;)((?i:script))\b(?![^&gt;]*/&gt;)</string>

Replace it with this:

<string>(?:^\s+)?(&lt;)((?i:script))\b(?![^&gt;]*/&gt;)(?!.*&lt;/script&gt;)</string>

Save. You should now be able to properly toggle comment out script tags in Sublime Text!

ss 2014-06-01 at 2.36.03 PM

If you are a terminal or command line power user, you often want to open in from Sublime Text right from the cmd line. Often something like this:

subl style.css

On OSX and Linux, we have the subl command that comes with Sublime Text, to install it you can follow the instructions here.

However, on windows we need to do it a little different by creating something called a doskey.

So, if you wish to use the subl command to open files and folders from the command line in windows, you can use the following:

doskey subl="C:\Program Files\Sublime Text 2\sublime_text.exe" $*

Paste the above into your command line prompt and this will make the subl command available to you.

If you are using Sublime Text 3, use the following instead:

doskey subl="C:\Program Files\Sublime Text\sublime_text.exe" $*

wordpress-logo-notext-rgb

When it comes time to migrate wordpress, it isn’t all that easy. You have a number of things to move over including your database, your images, your themes and your plugins.

I’ve been teaching WordPress for years and by far the most common question I get is “How do I get my website online?”

Well, I’ve put everything I know into an in depth tutorial on how to migrate your site. This might take a little while the first time, but as you do it a few times, this becoming a pretty quick process.

I recommend using BlueHost for hosting WordPress as it is very affordable, the support is amazing, and they are professionals at hosting WordPress. Here is my link for a discounted rate: http://wesbos.com/bluehost – if you sign up from this link you’ll get a discounted rate and I’ll get a small affiliate fee.

Hope you enjoy!

ss 2014-05-29 at 10.04.18 AM

In JavaScript or jQuery you often need to find out which key was pressed. Unfortunately, we don’t have it as easy as comparing it against a string like “esc” or “space bar”.
Each key on the keyboard is associated with a number, or what we call a keyCode and it is accessed on the event object.

When I do keycode listening, I always scrounge the net for the appropriate keycode to check for. No more! I’ve made keycode.info which does one thing well: tells you the asociated keycode and key when you tap any key on your keyboard.

Simple and easy. Hope you find it useful. Head on over or make it better on github.

CRA_HQ-slider

I’m preparing to sell my e-book on Sublime Text very soon. Part of that is building the online checkout module.

I was hoping to just use a simple solution where I only needed to ask buyers for a credit card and their email address. Since it’s an online download / virutal product, I didn’t think I needed to collect addresses from users.

So, as I’m setting this up, I was wondering about HST. With regular goods and services, you charge Canadians the destination HST/GST rate. I bill Ontario customers 13% HST, Alberta Customers 5% GST and out-of-country customers 0%. But how does this work when you are selling something online and planning not to collect addresses? Whoever buys the e-book might be from Ontario, they might be from somewhere else in Canada or they might be from outside the country.

So, I called up the CRA and asked them what to do in this situation. Lucky for me I was able to get a tech-savvy person on the other end that was extremely competent in his job. Because the good will be usable in Canada (Canadian can read the book), I will need to follow regular HST charging practices. So, I would need to collect the home address of every single person who buys my book. Arg.

So my next question was:

Can I just ask them if they live in Canada or not?

No. Asking someone isn’t enough proof of where they live. It won’t hold up in an audit.

Well, then..

Can I use IP address detection to see if they live in Canada or not?

No, because users can spoof an IP. Still not good enough…

So what are my other options if I don’t want to collect addresses?

If I really don’t want to collect billing information from everyone who buys the book, I would have to charge Canada’s highest possible tax rate to every single customer, regardless of if they live in Canada or not. This is the 15% tax rate of Nova Scotia.

Better safe than sorry

So, it looks like I’ll have to collect the addresses and charge the customer’s provinces HST/GST rate. Out of country customers will pay nothing in taxes.

Not the solution I wanted to hear, but I’m glad to find this out now rather than down the road.

Hope this answers a few questions!

gitsublime

By default, git uses Vim as the editor for commit/rebase messages. This can be somewhat limiting if you aren’t comfortable with using Vim, especially if you need to move around lines of code.

Luckily it’s easy to switch over to using Sublime Text as the editor for your messages. When git needs you to input and save a message. It will simply open up Sublime Text and prompt you with the file that needs editing. Once you save and close the file, git will continue on with what it needs to do.

Install subl

First thing we need to do is to make Sublime accessible via the command line. Chances are you might already have this installed, but if you haven’t, you can follow the instructions here. If you are still on Sublime Text 2 – follow these instead.

Set git to use

Next, open up your Terminal or command line and paste the following:

git config --global core.editor "subl -n -w"

That’s it! Next time Git requires you to edit a file or commit message, Sublime Text will pop open!

gutter

At my jQueryTO talk I showed a new Sublime Text Package called GutterColor that allows you to view your CSS colours in your gutter.

Amazing! It works with plain CSS, SASS, Stylus or LESS. If you are any sort of front end developer, you probably want this right away! Unfortunately the install process is a little klunky as it relies on a lower-level program called ImageMagick to be installed on your computer. It’s easy to do, just requires a handful of steps to get up and running.

TL;DR: brew or port install ImageMagick and set the path of your convert script in your GutterColor prefs.

Installing ImageMagick on OSX

So, we need ImageMagic to be installed on our computer. The easiest way to do this is with a package manager for your mac. If you already have homebrew or macports installed, you can simply type one of the following into your terminal:

brew install imagemagick

or

sudo port install ImageMagick

No idea what brew or macports is? You’ll need to install that first before you can install ImageMagick. I recommend using HomeBrew. Simply open your terminal window (found in applications → Utilities → Terminal) and paste the following code in and hit enter:

ruby -e “$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)”

That will ask you for your computer’s password and then take a few minutes to install homebrew.

Once that is complete, copy and paste this into your terminal as well:

brew install imagemagick

This will also take a few minutes to install, grab a coffee!

Finally, type the following into your terminal

which convert

This will return the location of your imagemagick convert script. Remember this. Skip the windows part and jump down to Setting up Sublime Text

Installing on Windows

Head on over to the ImageMagick website and download/install the option that works with your computer. If you download the wrong version, no worries, just try another version.

When installing, take note on the install path. You will need it later.

Once you have that installed, check if it worked by opening up the command prompt (start->cmd) and type convert. You should see a few hundred lines scroll across your screen.

Now, you need to find the path that it was installed to. Open windows exporer and find where it was installed to. This is probably something like c:/Program Files/ImageMagick-6.x.x.x We want to find the convert.exe file as below:

Setting up Sublime Text

First we need to go ahead and install the GutterColor package. You can do this via Package Control (Tools → Command Palette → Type install → Search for GutterColor and hit enter).

As of right now, this package requires you to tell SublimeText where the convert script lives on your computer. Go to Sublime TextPreferencesPackage SettingsGutterColorPreferences - User and paste the following code in there. Make sure to swap out the path if your which convert command returned something different.

{
“convert_path” : “/usr/local/bin/convert”
}

In my experience, sublime required a few restarts before it started to work totally. If you see red squares in your gutter, it’s helpful to look in the Sublime Console (view → Show Console) to see if you can make sense of the errors.

ss 2013-11-15 at 1.59.48 PM

Three things I love are coding, teaching and running a business. I’m fortunate enough to do all three for a living. Doing so I get a ton of questions about my lifestyle. What is it like? How do you get work? How much do you charge? What are the challenges? Do you wear pants during the day?

Learning to code is one thing, but running a successful business as a freelancer is an entirely separate skill. So, rather than reply to email after email, I decided that we would hold an informal Q&A night at HackerYou to answer all your questions! If this if of interest, you may want to join us at HackerYou where I teach everything from HTML, CSS, Responsive Design, JavaScript and WordPress to the real skills you need to start getting paying clients and running the business.

Below is a 2 hour video recording of our Q&A night as well as a summary write. Big thanks to Heather Payne for taking the notes below and distilling my thoughts into short, concise paragraphs!

Continue reading

blogtitle-ep2

The second instalment of the CSS3 FlexBox video series. This video will show you how to use order, re-ordering and columns to achieve an extremely flexible layout without re-ordering any of your HTML.

Series Links:

Introduction & Basics — Part 1
CSS Flexbox Video Series: Flexbox order, re-ordering columns and rows — Part 2
CSS Flexbox Video Series: widths, heights and Layout — Learn CSS3 Flexbox — Part 3

blogtitle-ep1

Update: While these videos are still a fantastic intro to flexbox, I’m working on a much more in depth, free video series called What The Flexbox – will be out in a few weeks! In the mean time check out my free Command Line Power User video series as well!

Tell me when it launches!


Flexbox is a new part of CSS3 that allows us to create super flexible layouts without having to deal with floats, margin centering hacks, variable height bugs, vertical centering hacks and any number of layout challenges you face when creating a website or application.

With the rise of Responsive Design, web developers everywhere feel the pain of trying to create ultra-flexible layouts with traditional CSS tools. With flexbox, we can create a container with children that expand, contract and scale to fit in the best possible way. Columns, rows, scaling, equalized heights, re-ordering and directions have never been easier with flexbox.

Flexbox is a very new idea and it can be really hard to wrap your head around how it works, and when you should be using it. To add insult to injury, there are two implementations of flexbox in the wild and every browser vendor does it just a little differently.

This leaves us with a MESS of code that will leave even seasoned CSS developers running back to warm familiar arms of floats, clearfixes and JavaScript hacks.

.flexWrapper {
display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
-webkit-box-direction: normal;
-moz-box-direction: normal;
-webkit-box-orient: vertical;
-moz-box-orient: vertical;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
-webkit-flex-wrap: nowrap;
-ms-flex-wrap: nowrap;
flex-wrap: nowrap;
-webkit-box-pack: start;
-moz-box-pack: start;
-webkit-justify-content: flex-start;
-ms-flex-pack: start;
justify-content: flex-start;
-webkit-align-content: stretch;
-ms-flex-line-pack: stretch;
align-content: stretch;
-webkit-box-align: start;
-moz-box-align: start;
-webkit-align-items: flex-start;
-ms-flex-align: start;
align-items: flex-start;
height: 100%;
}

This video series will simplify things, discover the ins and outs of flexbox, how it works as well as how to back-port flexbox to work with older implementations, devices and browsers.

Here is video #1 introducing the video series as well as the very basics of what flexbox is and how we can use it. I will be updating my blog over the next few weeks with the rest of the videos, each diving into a different part of flexbox.

Series Links:

Introduction & Basics — Part 1
CSS Flexbox Video Series: Flexbox order, re-ordering columns and rows — Part 2
CSS Flexbox Video Series: widths, heights and Layout — Learn CSS3 Flexbox — Part 3

ss 2013-07-08 at 5.36.16 PM

So, can I move to Sublime Text 3 yet? 

I’ve had this question asked quite a few times over the past month so I thought I would write up a quick post on my answer: probably.

Since my last “First Look” post on Sublime Text 3, 5 months have past and a lot has changed. Updates have been flying out, producing a faster and more stable Sublime Text 3.  Since then the beta has been opened to the public, so if you are still checking Sublime out, you can give ST3 a shot.

Continue reading

linebubble.mov

As I’ve been writing the Sublime Text Power User book over the last few months, I’ve had some interesting conversations around favourite features of ST. The one feature that I constantly surprise people with is called line bubbling – moving lines of code up and down a document without cutting and pasting them.

linebubble.mov

It’s an extremely simple feature but will save you lots of time and potentially lost code.

Let’s take this list as a very basic example. This list could be any block of code that you want to move up or down – they are only numbered as a visual.
ss 2013-03-11 at 11.14.30 PM
How do we move them up and down to end up in the correct order? We could cut and paste, but line bubbling is much faster.

In Sublime Text, hold down + control (CTRL + SHIFT on Windows) and use your ↑ up* and ↓ down arrow keys to move the lines around. This works for single and multiple lines.

Check out the video for a visual:

ss 2013-01-29 at 1.48.10 PM

I woke up to a real treat this morning: Sublime Text 3! Sublime Text development has always moved at an incredible pace and now just a few months after 2.0 was released, 3.0 peaks around the corner. ST3 isn’t at the point where it can be your daily editor – you will still be using ST2 for some time – but its exciting to take a look at what ST3 has in store for us!

ST3 is only available to registered ST2 owners, you will be reqired to input your license key upon launch. If you forget where you put your license key, go to Preferences → Browse Packages and then open the settings folder and look for License.sublime_license

What’s new

You can read all the new features over at the Sublime Blog, here are the main features along with some explanation and commentary.

It’s even faster!

Sublime has always been a blazing fast editor and Jon Skinner has outdone himself with this. The editor starts and opens up my last project in less than a second. On OSX the icon doesn’t even reach the top of the bounce before it has loaded.

Python 3.3 & Packages API

Sublime has now switched to Python 3.3. If you aren’t familar, Python is the programming language that Sublime Text uses to expose it’s API. It is how we get all those great packages. Python 3.3 has been out for a while, but many developers have been dragging their heels in upgrading as many of the packages haven’t been ported over. I’m not a Python developer, but according to the Python Wall of Superpowers things are looking better lately.

The downside to this is that most Sublime Text packages will need to be ported to ST2/Python 3.3. The author of Sublime Text says porting to the new API involve minimal work.

Sublime Text package manager doesn’t work yet, but the author Will Bond says work is already underway. Will also has a number of popular packages so I would watch his github, twitter and site for his experiences with porting everything over.

UPDATE: Will Bond has updated package manage to work with Sublime Text 3. See his commend below.

Pane Management

Previously sublime text only allowed you to split your editor into 1-3 columns, 1-3 rows or a grid of 4. This has changed in Sublime Text 3 which exposes controls for splitting panes indefinitely.

I played around with the commands and keyboard shortcuts for a bit but I will be sticking with Origami to manage my panes as I find the commands for moving files splitting panes to be more natural.

Symbol Indexing


ST3 introduces project wide Goto Symbol and Goto Definition. Previously Goto symbol fuzzy search only worked when you specifically noted which file you wanted to look in. In the example above I’m able to see everywhere the post_render function is called in Octopress. This is a really big step up for Sublime that may have a few IDE-lovers jumping ship.

Themes and colour schemes

The UI of Sublime hasn’t changed at all other than a few animations when hiding/showing the sidebar. I’ve tested ST3 with my Cobalt2 theme and color scheme and I’m happy to report that everything worked flawlessly.

Prices

Sublime text 3 will go for $70 or a $30 upgrade from ST2 ($15 if you purchased it recently, so don’t hold off buying ST2).  Money extremely well spent.

Wishlist

This is just the beginning of ST3 and I’m excited to see what it has in store for the future. A few things that are on my wishlist:

  • Full blown terminal integration
  • Binary file display  – One thing Coda does really well. If I click an image, I’m able to preview it and get its dimensions.
  • Find/Replace Macros – being able to record a find/replace and play it back or run with arguments would be very handy.
  • Sidebar icons – Sublime excells in its simple interface but having icons for folders/filetypes is something that has always been on my list
  • What is yours? – Post in the comments what you hope Sublime Text 3 will bring

photo (1)

If you do any sort of web development locally you have probably run into at least one of the following problems:

  1. I can’t access my local sites/apps on my mobile devices
  2. I can’t access localhost inside of my virtual machines
  3. My teammates can’t access my local site to view it
  4. I need to test IE6 on my Toshiba crapbook

Pushing your site to a server isn’t ideal, especially when you are debugging a problem and have a longer deploy process.

I develop everything locally and have to test my sites/apps on a variety of mobile devices as well as a few different installs of windows which I run on Virtual Box. This is how I run a single development domain that is available to every device on my wireless network as well as on my laptop, regardless of the wifi network I’m on.

Continue reading

photo

photoIf you haven’t heard, there are beautiful 27″ IPS monitors coming out of Korea that use the same panels as the Apple Thunderbolt display. Turns out that Apple buys its panels from LG and any panels that aren’t absolutely perfect get rejected. Enterprising companies in Korea are then buying these panels and putting them into their own monitor housing. You don’t get the apple looks, nor the docking ports at the back, but at $300-400, these monitors are attractive to many who just want a high quality panel without the $1000+tax price tag an Apple display. This isn’t a $300 best buy special with a 1080 resolution, its a serious monitor pushing out 2560×1440.

Before we go any further, if you are on team $1000 apple thunderbolt display. We get it, apple displays are perfect  and worth every penny to you. Pretty much everyone would kill for a thunderbolt display. This is my story how I got the exact same quality display for half the price.

There are tons and tons of articles that will catch you up to speed on these monitors, I suggest you read them if you want to know more. Here is the short and skinny:

  1. There are many different brands that package the same panel and the prices vary. Some have poor build quality (including the circuitry) and other have really nice stands. The three big names are Yamakasi Catleap, Achieva Shimian and  Crossover. Do your research by reading the forums – there are literally thousands of pages of  information on this.
  2. Most of these monitors are sold on ebay. Monoprice recenrly started to sell their own brand. I bought mine off a seller called ‘Dream Seller’ who shipped it free from Korea in a shocking 3 days.
  3. You run the risk of getting a few dead pixels or back light bleeding. I paid an extra ~$25 for a pixel perfect version and I have zero dead pixels and no backlight bleed. Many buyers risk the dead pixels and end up with perfect displays, others have a few dead pixels.
  4. These are barebones as it gets, DVI only and no on screen display.

I bought a Crossover Q27 LED because it has the best build quality with a metal bezel and stand. I replaced the stand with a monoprice arm because I found it less bulky. If you are considering the Crossover Q27 LED and have neck problems, go for the Crossover Q27 LED-P which has a stand that allows for pivoting and moving up/down.

photo_3

Running it on a Macbook Pro

Most of the forum posters are serious gamers so I found I had to do quite a bit of research about running it on my Macbook Pro. The biggest takeaway is that these monitors require a dual link dvi cable to hook it up. Those $10 mini display port / thunderbolt → DVI connectors won’t work here. Because the resolution is so high, we can’t simply just convert the signal from our macbook to DVI like we do with other monitors – this is what we call passive conversion. As I understand it, we need an Active converter that will take the output from the macbook pro and kick it up to  2560×1440.

DV019_Jpg_Regular_501043

The above is Apple’s version, and it doesn’t come cheap at around $150. There are other companies including StarTech and Monoprice that put out cheaper, and supposedly better, adaptors for around $100-120. No cheap, so keep this in mind when factoring in the price of the monitor. These adaptors require a USB port, which is purely for power. The apple one gives you a passthrough so you don’t lose a precious port. I plugged mine into a powered hub and it works fine.

I’m running this on a mid 2010 macbook pro. It’s important to note here that even if you have a newer model with thunderbolt, you still need to buy this adaptor. I found a cheap one on Craigslist.

Power

This is another thing to pay serious attention to. Most of the monitors come with Korean power bricks which operate at 110-240V. North America runs on 120v, so I was safely inside that voltage. The only thing I needed to do was swap the korean plug for a north american on. Its the same plug as printers/scanners/monitors use, so I could just unplug the korean wall plug version and swap it out with mine.

If you live in a european country that runs on 250V – you need to make sure you buy a proper power pick. Do not fry your monitor!

Calibration

Out of the box, the colour was almost bang on and I only had to do a little bit of calibration. These monitors only come with two buttons: brightness UP and brightness DOWN. No problem here though, OSX comes with a very nice colour calibration wizzard which allowed me to make everything look 1:1 to my macbook pro.

Warranty

There isn’t much of a warranty with these things past the initial delivery, this is one of the major downsides. There is no Apple store appointments for these monitors. Luckily, I was able to pop my ebay listing # into SquareTrade and they sold me a 3 year warranty for $50. Totally worth the peace of mind.

Overall Prices

Monitor $380

Display port to Dual link DVI Converter $60 (craigslist)

Monoprice Monitor Arm – $20 off craigslist

Duty – $60 (I was one of the only instances I could find online where poeple got nailed by customs. Oh well, oh Canada).

Total: $520 taxes in

Hope this was helpful and saves you hours of searching. In the picture above, I’m also using a USB to DVI converter from displaylink to run the third display.

 

photo_2photo_1

Please leave any tips or questions in the commends below.

Let me know when this book launches

Enter your email address below and I’ll give you a hoot when its ready plus a discount code for being so great!

Sublime_Text_Logo

I’m working hard on my Sublime Text Book and have received fantastic response for everything so far – very motivating. The last post was so well received that I’ve decided to post a few more of my favourite tips.

1. Save on focus lost

Chronic ⌘+S’er? This tip is particularly helpful when working with CSS/LESS/SASS and switching between your editor and browser. Instead of saving on every tiny little change, tell Sublime to automatically save your files when you tab away from the editor.

I find this is super handy when working with extensions like Live Reload or compiled languages like coffeescript that watch for file saves. Put this in your settings file at PreferencesSettings - User

"save_on_focus_lost": true

If you work with other watch scripts that break and restart a process upon save (like supervisor or forever), this might not be ideal for you. No problem, only enable it for the languages you want – simply place the above setting in /Packages/User/[syntax].sublime-settings. For example, I put the above in CSS.sublime-settings and LESS.sublime-settings

2. Paste and Indent

One of the best tricks I’ve ever learned in Sublime Text is paste and indent. If you have ever pulled a piece of code off the Internet and pasted it into your application, you’ll no doubt feel the pain of having it paste in all weird and have to go in and fix it.

Easy fix to this, instead of pressing the normal cmd + v to paste, simply switch to using cmd + shift + v to paste. This will automatically indent your code block.

Like that one? I loved it so I remapped my key combos to paste and indent by default on cmd + v

Paste this little snippet into your key bindings file located at PreferencesKey Bindings - User

{ "keys": ["super+v"], "command": "paste_and_indent" },
{ "keys": ["super+shift+v"], "command": "paste" }

3. Reindent Keyboard shortcut

Now, if for some reason you end up with either a block of code or an entire file filled with hard to ready, messy, poorly indented code, reindent is your best friend.

To automatically re-indent your code, simply select the code you want to indent and then from the menu EditLineReindent

Sublime doesn’t ship a keyboard shortcut for this. No problem, let’s make our own. Pop this little snippet into the PreferencesKey Bindings - User file.

{ "keys": ["super+shift+r"],  "command": "reindent" }

4. Highlight Modified Tab

When making a change in sublime text, by default it changes the × to a circle of the same colour.

Make it a little more obvious when you haven’t saved changes to a document by turning on the following:

"highlight_modified_tabs": true

The exact styling of your modified tabs will vary depending on your theme. It looks fantastic with my cobalt2 theme for Sublime Text

I’m an instructor at HackerYou where we use Sublime Text extensively. This is a small, yet common, problem that we run into. Making it visually obvious cuts down on mistakes like this.

5. Proper Fullscreen for Mac Users

This one is only for those running Sublime Text on Mac OSX 10.7 or 10.8 with multiple monitors. You have probably realized that apple has really dropped the ball when using fullscreen, rendering the rest of multiple monitors into nothing but a linen backdrop.

If you like to code fullscreen yet still use your other monitors, go ahead and add the following to your preferences file:

"use_simple_full_screen": true

You’ll have to restart Sublime Text for this one.

More?

I’ve got plenty more tips as well as in-depth guides on the rest of Sublime Text in my book. If you have a must-use tip or commends on any of the above, please feel free to leave a comment!

ss 2013-01-08 at 11.38.07 AM

I love tweaking Sublime Text. There are hundreds of settings you can change and I’ve blogged about a few of them before.

Here are five visual changes you can use to make your text editor just right. You should place these items inside your User settings file which can be located at preferencesSettings - User

1. Change the caret style

Who thought a caret could be sexy? Change your caret style to phase and it will fade in and out rather than blink.

"caret_style": "phase"

Other available options include “smooth”, “phase”, “blink”, “wide” and “solid”. I’ve been fond of “wide” which doesn’t blink and is clearly visible for screenshots in my new book.

2. Highlight current Line

This is one thing I wish Sublime Text enabled by default. Highlighting the current line is a subtle visual cue when jumping back and forth between a browser and code.

This is also super handy when you are dealing with long lines of code/text and you want to quickly know if the current line is wrapped or not.

"highlight_line": true

ss 2013-01-08 at 11.21.30 AM

3. Increase the line height

This trick adds just two pixels to each line, but increases the readability of code so much better. Might not be for everyone but I really enjoy this one.

 "line_padding_bottom": 1,
  "line_padding_top": 1

4. Show Code folding arrows

Code Folding in Sublime Text is really great but I’ve noticed most people don’t use it as much as they do in editors because the arrows aren’t visible until you hover over the gutter.

Make them always visible and get folding!

"fade_fold_buttons": false

ss 2013-01-08 at 11.27.27 AM

5. Bold Folder Labels

One of the downsides to Sublime Text is that the sidebar isn’t as strong as other editors. One visual cue that helps me out is bolding folders. This helps me quickly identify what is a folder and what is a file.

"bold_folder_labels": true

ss 2013-01-08 at 11.28.45 AM

More…

business

Hey you!

Yeah you!

I’m talking to you!

Don’t email me with your questions.

Please!

Read below

Update: This post is extremely popular and the comments are a wealth of information – make sure to read them. Please remember that these are just my experiences – I’m not a tax lawyer and and I cannot consult on your situation – so please do not call or email me with your questions. You should talk to an accountant, a book keeper or a tax lawyer. Or just call the CRA, they are pretty nice and have the answers your questions. Again, please don’t email me!

The new year marks the beginning of a new fiscal year for many businesses so I thought I would share a few things I have picked up over the past few years. I’ve run my web consulting business as a proprietorship the past three years and have picked up quite a few nuggets of useful information along the way. These things seem simple and almost laughable now, but as a greenhorn I wish I had known these before I started.

These tips are best if you are thinking about running a sole proprietorship (a business that is owned and run by a single person) in Canada but are helpful for other outside of the country.

Hire a good Accountant

I’m putting this one first because its by far the most important thing you should do when starting a business. My first year I paid someone $50 to do my taxes and I really got what I paid for. I had my taxes reassessed three times and had to pay the government more each time. The second year around I paid around $700 for the fantastic services of Waterford Tax & Advisory who did an amazing job straightening everything out and giving me some fantastic advice which saved me tons in the long run. A good accountant will always be around to answer questions and give you advice. You can’t afford to use a cheap accountant, trust me.

Ditch excel, use Freshbooks

This is a no-brainer for taking care of estimates, expenses and invoicing clients. At $33 a month, this is one of the more expensive services I subscribe to, but it is worth every penny. At the end of the year I’m able to export a few reports and send them off to my accountant – no dealing with spreadsheets. My clients love Freshbooks too – I often get compliments on both how easy it is to manage invoices and how professional my invoices look like.

Understand taxes – Personal and HST

Starting a business, you are probably coming from  a job where all your taxes are taken care of and at the end of the year, you get a nice little return from the government. Not so when you are on your own, take the time to educate yourself on what sort of taxes you need to pay in your area.

Personal Income Taxes: Running a sole proprietorship in Canada means you get taxed at the same rates as everyone else who isn’t self-employed. There are both provincial and federal tax rates that vary depending on how much income you bring in. You can run your numbers for both at the CRA website.

HST: I run my business in Ontario, and I need to charge all my clients who live in Ontario 13% HST – your province or state will have something similar setup. If you are making more than $30,000 a year  you will need to register for a HST number and start collecting.

So, the biggest lesson learned here is you need to pay a ton of taxes. As soon as you get a cheque, you should cut out anywhere from 35-50% (13% HST, 22-37% income tax)  – depending on how high your taxable income is – and placing it in another account to pay the tax man at the end of the year.

Keep every receipt and expense everything

The best thing you can do to reduce how hard you get hit by taxes is to expense every single dollar you pay to run your business. Again, this may seem like easy stuff to some, but its worth noting how this stuff works.

You only get taxed on net income, not gross income. So, if you get paid $1,000 for a project, but spent $200 on hosting for it, you will only be taxed on $800.

So, think of every little thing you use to run your business. Buying a new laptop, conference tickets + flights, printer ink, online subscriptions, software licenses… It all adds up quickly and can really help you reduce your taxable income.

As a business, you also don’t have to pay HST. So any receipt you have that includes 13% HST, you will get that back from the government when you pay your taxes.

Max out your RRSP

This is a good tip for anyone around tax time. Up until the end of February, you can contribute to the previous years RRSP. Anything you contribute to your RRSP is not taxed, so you can treat it as a huge expense. The amount you con contribute depends on your previous years income, but it could be as much as around $20,000. In Canada, this money is meant to only be taken out at retirement, but there is a special clause that lets you cash it out, without penalty, when you buy your first house.

Health Insurance is cheap

My wife recently quit her job to work independently beside me. While we are super happy with that decision, we lost the perk of health benefits. In Canada residents are covered for the big stuff like surgeries and doctors appointments, but not things like medicine, dental work and eyeglasses. Insurance plans are surprisingly affordable, starting at $60 for basic coverage. Kait and I went for pretty good dental, eye and prescription coverage and it was around $160/month.

One other thing, we shopped around on the net for insurance and we didn’t find any good rates, only after getting in touch with a broker did we find out its much cheaper to have a human do it for you.

Incorporate to save $$

Coming full circle to having a good accountant, mine suggested that once you start earning decent income or are working in an arrangement like Kait and I are, it would make sense to ditch the sole proprietorship and incorporate as a business. Its more expensive to incorporate a business (~$500 vs $60) and its a more work to get up and running, but its well worth the tax savings in long run. I’m only beginning to explore this world but I’ll be sure to follow up with a post after a few months.

That’s it

TL;DR : Hire a good accountant and explore every possible way that you can reduce your taxable income. Starting to run your own business can be confusing so hopefully these tips can help you.

Update: Check this comment for a lot more useful tips, thanks Martin

androidthumb

Be sure to Follow @wesbos on twitter for more like this 🙂

Earlier this week Chrome for Android was finally announced and web developers everywhere celebrated. Not only did we have one of the best browsers now on our phones, but we had access to remote debugging, which we have been waiting for and talking about forever.

Remote debugging allows a developer to use the browsers developer tools from a desktop computer while inspecting and manipulating the website on the mobile device – all in real time! This means you no longer have to use alert boxes to debug a problem that only reproduces on the phone.

So, while there have been a few earlier implementations of something similar, Chrome for android brings us the rock solid experience that we have been waiting for. Without further ado, here is a quick tutorial on how to get remote debugging up and running.

Update: I’d like to specifically point out that Opera Mobile has has this functionality for quite some time now and you’re able to do it without USB or a SDK (miketaylr had an awesome presentation on it at jQuer conf). So, develop in whatever browser you prefer and use both these tools when you’re debugging that specific mobile browser.
Continue reading

goog

Over the last few weeks I’ve been interviewing with Google for a job doing primarily JavaScript development. I didn’t end up getting the job but I thought I would share the process of interviewing for Google as it was both very exciting and a humbling experience. I can’t reveal everything as I’m under a few NDAs. I’m not going to mention the products or teams that I was interviewing for but you may be able to guess.

For those that don’t know me, I’m an independent developer/designer. A majority of my work falls into the four categories of JavaScript development, WordPress development, HTML5/CSS3 or UI/UX design. I absolutely love running my own show and it would take quite a bit to get me to switch out.

In the beginning

So, a few months ago I had a Google employee ask me if I was interested in joining their team. As I said, I’m super happy with what I’m doing at the moment but I didn’t want to turn down the chance to interview or even work for Google. I happily passed along my resume and that was the end of that for about 5-6 months.
Continue reading

html5icon

Happy New Year! I hope everyone had an awesome holidays. To celebrate, I’m going to be giving away 5 of these kickass HTML5 shirts that the folks at Microsoft have kindly provided.

These aren’t your regular HTML5 shirts, they come from Canada so naturally they involve a polar bear, a beaver and a moose.

How To Enter

To enter, simply sent out a tweet with the hashtag #HTML5shirt and a link to this post.

“Win a #HTML5shirt from @wesbos http://wesbos.com/html5-shirt-giveaway”

I will be giving them away to 5 random tweeters and using twittertwitterchickendinner.com to pick the winners. I’ll ship you the shirt anywhere in the world. I have them in most sizes but is first come first serve.

Thats it, good luck and if you so please, follow me on twitter for more on HTML5.

Update: Winners!
First off, thanks to everyone who entered the draw, having almost 2,000 enter is pretty nuts! I’ll have to find a way I can do this again because you guys love your free shirts 🙂

Drumroll please… The Winners are:

@steno, @sheppy, @csixty4, @oscargodson and @PatridgeDev

Congrats! Contact me wes@wesbos.com within 24 hours with a mailing address and shirt size to claim you prize.

Thanks again everyone, I have some really cool HTML5 stuff coming down the pipe so stay tuned!

llc

This November I have two development related talks coming up and I thought I would take a second to formally invite you!

The first is an all day workshop on WordPress development which is being done with the great folks at Ladies Learning Code. If you haven’t heard yet, LLC is an awesome initiative started by a few Toronto ladies with the purpose of creating a comfortable environment where women can learn basic web development skills. I will be leading the upcoming WordPress workshop where I will take you from installing WordPress to making your very own theme. The workshop is on Saturday, November 26 and costs $40. The first round of tickets sold out in a heart beat, so be sure to sign up for the second round if you’re interested!

The second is quick talk on HTML5 Canvas at the #devTo meetup. This event is held once a month and is open to anyone who is interested in chatting about development. I’ve been to the last few meetups and I’ve found them pretty awesome. There a good mix of designers, developers (of all languages) and industry folk which always allows for good conversation (the free pizza and beer aren’t bad either!). I’ll be doing a quick introduction to the HTML5 Canvas element, what it is, what we can do with it, how to work with it as well as showing a few examples of stuff I’ve done with it. Canvas really is one of the most exciting parts of HTML5 so I’m looking forward to sharing what I’ve done so far. This event is always super popular and has already sold out, so get on the wait list and cross your fingers!

Thats all for now, hope to see you at one of the upcoming events!

newsstand

Many people, myself included, were annoyed that you aren’t able to put the new Newsstand Icon in a folder. Well a quick little hack I found today lets you do just that! Turns out you can trick iOS5 by creating a folder with other icons and then quickly drag it into that folder.

This doesn’t require you to jail break, but it does take a quick finger! Watch this video to see how to do it:

Note

This should only be done if you are no using newsstand. Trying to launch newsstand from within a folder crashes springboard!

Cool eh? Follow me on Twitter for more like this 🙂

Screen Shot 2011-10-03 at 5.57.36 PM

To continue on with my string of blog posts on Sublime Text, I’m going to show you a short but handy feature that was just pushed to the stable build. Code Folding!

Unfortunately, collapsing of code in sublime text isn’t exactly the same as textmate, so you dont get the little arrows in the sidebar. The code is also folded into a single character which makes it easy to delete an entire block of folded code without noticing you have done so. This is the first iteration of code folding in sublime text 2, so I’m sure it will only get better. With those cautions in mind lets take a look at how to work code folding in Sublime.
Continue reading

build

A really great feature of Sublime Text 2 is the ability to create your own build scripts. A build script is helpful when you are writing in a language that needs to be compiled or executed from terminal / command line. I personally use build scripts to compile the current file into CoffeeScript as well as run the current file in Node JS.

Watch the tutorial or continue reading to learn how to make Sublime Text 2 build scripts.
Continue reading

facedetection

This morning I saw this link on youtube which was a little mashup of some HTML5 technologies. I thought it would be funny if I could do the same, but with goofy pair of glasses. I’ve also been itching to put the CCV JavaScript Face Detection library to use. This library shows a few examples on static images, but after a quick look at the code, it shows that the underlying element to the script is a canvas element. So instead of running it on a single image, I am running it on a feed of frames coming from an HTML5 video element.

I’ll go into the technical details further on in the post, but here is a demo as well as a youtube video showing the effect as it can be a little sluggish on older machines. Currently tested and working in Google Chrome 14 and Firefox 6.0.  Continue reading

sublIcon

I’m a long time Coda user. A few months ago I, like everyone else, decided to switch over to vim. I really liked Vim but just couldn’t get the hang of it for whatever reason. After shamefully crawling back to Coda, I found myself realizing that Coda fell short in a few areas. It was then I decided to give Sublime Text 2 a shot as it had been touted as the sucessor to Text Mate. Its taken me a few weeks to get used to, but I can happily say I’m a Sublime Text 2 user now. Here are a few tips that make switching over easier.

Continue reading

wordpress

We have all been there. You finish up the most beautiful design with perfectly picked colours, font sizes and page style and pass it off to the client. A few days later you check back at the site and they have happily splattered underlined neon green h1 tags with inline styles. Why why why? Because the WordPress WYSIWYG editor is hard to use and by default it temps you with a basic colour pallet and basic h1-h6 tags.
Continue reading

sockets

Web sockets and Canvas are two really cool features that are currently being implemented into browsers. This tutorial will give you a short rundown of how they both work as well as create a realtime drawing canvas that is powered by Node.js and web sockets. For simplicity’s sake, I’ll be writing all the code in coffeescript. If you prefer regular ‘ol JavaScript, take a look at the corresponding .js files. I’ve also left out the CSS for the same reason.

Quick Screencast detailing tutorial

Cross Device / Browser compatibility

Server Side

The first thing we need to do is create a web socket server. For this we will be using Node.js and the module Socket.io. Socket.io makes its super easy to get a web socket server up and running. It even provides a flash fallback for browsers that don’t support native web sockets. In this tutorial we will only be working with browsers that support the canvas element.

If you don’t have Socket.io installed yet, make sure you do so by typing npm install socket.io into your terminal.

For now, lets just set up the web socket server. Create your server.coffee file with the following configuration.

io = require('socket.io').listen(4000)
io.sockets.on 'connection', (socket) ->

Compile your coffeescript and hop back into your terminal and type node server.js. You now have a web socket server running on port 4000.

If you go to localhost:4000 you’ll see the following:

Client Side

First, lets quickly get our index.html file up and running. In addition to some bare bones markup, I’m also including jQuery, our Socket.io JS file which is now being served up from our server, a jQuery plugin for drag events, and our own scripts.js file which will hold all the magic.

<!DOCTYPE HTML>
<html>
<head>
	<meta charset="UTF-8">
	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
	<script type="text/javascript" src="js/jquery.event.drag-2.0.js"></script>
	<script src="http://localhost:4000/socket.io/socket.io.js"></script>
	<script type="text/javascript" src="scripts.js"></script>
	<link rel="stylesheet" href="style.css" />

	<title>HTML5 Canvas + Node.JS Socket.io</title>
</head>
<body>
	<article><!-- our canvas will be inserted here--></article>


	<!-- Scripts required -->
	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
	<script type="text/javascript" src="js/jquery.event.drag-2.0.js"></script>
	<script src="http://localhost:4000/socket.io/socket.io.js"></script>
	<script type="text/javascript" src="scripts.js"></script>
</body>

Now that we have our server up and running, we can write some code which will draw to the canvas. Create a new file called scripts.coffee. All of the following code happens within the App.init() method which we will trigger on the jQuery document ready.

Create our Canvas Element

# setup our application with its own namespace 
App = {}

###
	Init 
###
App.init = -> 
	App.canvas = document.createElement 'canvas' #create the canvas element 
	App.canvas.height = 400
	App.canvas.width = 800  #size it up
	document.getElementsByTagName('article')[0].appendChild(App.canvas) #append it into the DOM 

	App.ctx = App.canvas.getContext("2d") # Store the context 

	# set some preferences for our line drawing.
	App.ctx.fillStyle = "solid" 		
	App.ctx.strokeStyle = "#bada55"		
	App.ctx.lineWidth = 5				
	App.ctx.lineCap = "round"

	# Draw Function
	App.draw = (x,y,type) ->
		if type is "dragstart"
			App.ctx.beginPath()
			App.ctx.moveTo(x,y)
		else if type is "drag"
			App.ctx.lineTo(x,y)
			App.ctx.stroke()
		else
			App.ctx.closePath()
	return

Draw to canvas function

Since drawing to canvas involves beginning, moving and closing paths, i’ve create a short little function that hooks into the jQuery dragstart and drag events.

# Draw Function
App.draw = (x,y,type) ->
	if type is "dragstart"
		App.ctx.beginPath()
		App.ctx.moveTo(x,y)
	else if type is "drag"
		App.ctx.lineTo(x,y)
		App.ctx.stroke()
	else
		App.ctx.closePath()
return

Setup our client side web socket

Since we included our file at http://localhost:4000/socket.io/socket.io.js we are able to create an object which we can send our data over. With just a few lines, we create our App.socket object and bind to any incoming web socket events called ‘draw’. We will go over this more soon.

# Sockets!
App.socket = io.connect('http://localhost:4000')

App.socket.on 'draw', (data) ->
	App.draw(data.x,data.y,data.type)

Canvas Drawing Event

This is where things gets exciting. Now we want to bind a few events to our canvas element. The way this works is when someone draws on the canvas, we immediately use our draw() function to draw to the current canvas as well as send the x and y ordinates over the web socket with socket.io’s emit. In just a bit we will take a look at the server side part of this event and see how the server sends out this data to all open windows.

###
	Draw Events
###
$('canvas').live 'drag dragstart dragend', (e) ->
	type = e.handleObj.type
	offset = $(this).offset()
	
	e.offsetX = e.layerX - offset.left
	e.offsetY = e.layerY - offset.top
	x = e.offsetX 
	y = e.offsetY
	App.draw(x,y,type)
	App.socket.emit('drawClick', { x : x, y : y, type : type})
	return

Jump back to server side

Now that we know we are sending the x, y and type of event over the web socket, we need to do something with that on our server. What we want to do, is take that data and send it back out to everyone else that has a browser open.

Our updated server.coffee file now looks like this. We first wait for a connection event, then wait for a ‘drawClick’ event to be sent by a browser. When that happens we take the data and send it out to everyone else with a browser open. THe server side script we wrote earlier will then paint the canvas.

io = require('socket.io').listen(4000)

io.sockets.on 'connection', (socket) ->
	socket.on 'drawClick', (data) ->
		socket.broadcast.emit 'draw',{ x : data.x, y : data.y, type: data.type}
		return
	return

You’ll now need to restart your web socket server as we have made changes to it. Hit control-c to kill it, and node type node server.js to restart it.

Get Drawing!

One you fully understand how this all works, open your index.html file in any web browser that supports web sockets and canvas (at the time of writing Chrome, Firefox, Safari, Opera and IE9). Check http://caniuse.com/#search=canvas for more support info.

Limitations

As this is a very basic demo, there are a few limitations which can easily be solved with a little more code. Currently the canvas only supports one person drawing at a time, if two or more are drawing, the canvas will be painted sporadically. Also, there is definitely a lot of room to add tools such as brushes, colours, erasers and PNG export. If there is interest, I’ll expand this tutorial series to cover them.

If you’re interested in getting this up and running in the real world and off of your localhost, I was able to get mine running on Amazons free micro instance of EC2 although this involves installing Node and NPM all over again. Also note you should run your server on port 80 rather than 4000.

Please feel free to download, hack, complain, fork or contribute to the project on my github account.

cofeegrowl

Two things I’ve been working with lately have been Node.js and CoffeeScript. If you haven’t heard of either, Node.js is server side javascript and CoffeeScript is a ruby/python like langage that compiles down to regular javascript.

The way I develop my CoffeeScript is by using the Node.js compiler to watch my `scripts.coffee` for any changes and compile it into normal JavaScript every time I save my file. The process is instant, but I need to watch my terminal window to see if there were any compiling errors. As you can imagine, this can get fairly annoying especially if you aren’t on dual monitors.

So, my solution was to write a Node.js module that would send a growl notification to the user when the compile was finished. I made use of the growlnotify command line plugin for OSX.

To use, you need to first install growlnotify.

Then use NPM to install the package `npm install coffeescript-growl`

Finally, require (with -r or –require) the module when you compile your script. I like to use something like this:

`coffee -r coffeescript-growl –watch –compile ~/sites/my_project/scripts.coffee`

Thats it! If you have any suggestions or fixes, please fork me on github and follow me on twitter.

Screen shot 2011-05-17 at 12.56.54 PM

Two of my favorite jQuery plugins are Mike Alsup’s Cycle and Ben Alman’s Hashchange. Cycle allows you to create really flexible sliders /slideshows and Hashchange allows you to create an event that triggers on hash change. When you’re using jQuery cycle for a large slideshow, its a good idea to let users link within that slideshow to a specific slide so that they can share and bookmark them.

A great example of this is for a photographer that may have 50 pictures in their portfolio, they often do not let you share the link to that specific picture but rather just the page with the slideshow embedded in it. Additionally, the user can now use the browsers back/forward buttons to navigate through your slideshow Continue reading

Screen shot 2011-05-11 at 3.08.07 PM

Just about an hour ago Rovio and Chrome released Angry Birds for Chrome. As a JavaScript / HTML5 guy, I quickly jumped into the code to see how things worked.

I was quickly able to find a hack that gave me access to all the levels, even the special Chrome levels!  So to  get access to all levels in Chrome Angry Birds, just copy and paste the following line into your browser’s address bar.

Continue reading

mamp-logo

I’m a backup fanatic and not having a few backups of files makes me uneasy. Today I had a little scare where I couldn’t find a few of my databases when viewing PHPmyAdmin through MAMP. Turns out sometimes MAMP likes to sometimes grab the databases from the MAMP Pro location and sometimes the MAMP location.

So, I decided it was time to figure out how to automatically backup my databases. The problem is that my MySQL databases are not in the same folder as my Dropbox folder.

The answer to this is very simple! First, if you haven’t already, sign up for dropbox. Then we just need to create a simple symlink that will allow the databases to be stored in their location and still be backed up to the DropBox folder.

Continue reading

paywall

If you haven’t heard, the New York Times has implemented a paywall where you can only view 20 articles a month. After that they throw an overlay on top of the content so you can’t view it.

Since they still want to be indexed by search engines, they don’t bother to hide the content once you have reached your 20 max. Two simple lines of CSS will hide this. I’ve also made it into a Chrome Extension
Continue reading

Screen shot 2011-03-23 at 2.56.08 AM

Yesterday Firefox 4.0 was released and web developers everywhere celebrated a really great browser.  The browser comes packed with a super fast JavaScript engine called JägerMonkey. Now don’t get too excited just yet! We still need to keep that old version of Firefox around for testing; we can’t assume everyone has upgraded to Firefox 4. So, to run both Firefox 3.6 and Firefox 4.0 on the same machine, just follow these simple steps: Continue reading

Screen shot 2011-03-21 at 2.43.09 PM

Every now and then I like to play with the API of a social networking site. Burstn is an photo sharing website that allows users to quick snap photos and upload them to their website. Lucky for me, their API is fairly wide open, allows to easy calling, and returns a super nice JSON response. My idea is to ping the Burstn API for a timeline of public photos, parse the JSON response, and plot them on a Google Map based on their Lat and Long positions.  Sound fun? Lets go! Continue reading

Screen shot 2011-03-16 at 11.44.30 PM

Was helping someone out in the jQuery IRC channel today and they were having some trouble with a JSON api that they were using. To simply put it they wanted to:

  1. Load a JSON file via Ajax
  2. Parse the results
  3. Pass it to Google’s Visualization into a data table
  4. Create a map based on that data.

Now the example given is great, however it doesn’t jive well when you want to add in a friendly library like jQuery. So here is how we fixed it: Continue reading

wb

This is a phrase I will no longer have to joke about when telling someone about my website. I’ve finally taken the time to create myself a brand spakin’ new website. Its been almost 2.5 years since I launched the last one and a lot has changed. I’m very proud to launch this site as I think it reflects who I am a lot better than the old one. Continue reading

pagecache

This is a little code snippet that I use in almost every project that isn’t based on a popular CMS. Since its fairly expensive to hit the database on every page load, its a smart idea to cache the plain HTML markup of your page and serve that up. You can set how often the page cache is flushed out depending on how often you update your site’s content. Continue reading