JavaScript: Expressions v Statements

JavaScript, like many other languages, distinguishes between expressions and statements, which means you should too. However, the terms do not refer to a particularly clear cut syntactic difference in many cases and often the difference is largely context specific.

The simplest definition of these terms: Expressions produce a value, or stand in wherever a value is expected, these act without producing any side effects. For instance, examples are taken from Rauschmayer’s review of the subject,

myvar
3 + x
myfunc("a", "b")

On the other hand, a statement provides an action or behaviour, such as a loop, if statement, or function declaration. (Most authors lump together declarations with statements. this is not exactly true as, for instance, declarations are treated differently in the hoisting process.) An important unidirectional relationship exists between expressions and statements: A statement may always be replaced by an expression, called an expression statement. The reverse is not true. The distinction becomes more muddy from here!

A particular problem relates to the difference between function expressions and function declarations, which look essentially the same,

// Function expression
var greeting = function () { console.log("Hello!"); };

// Function declaration
function greeting() { console.log("Hello!"); };

I wasn’t lying! The devil is in the details: the function expression returns a function object which we’ve assigned to the variable greeting. The function expression here is actually anonymous - there is no name given on the right hand side of the equals sign. A named function expression such as,

// Named function expression
var greeting = function howdy() { console.log("Hello!"); };

has the name howdy that is scoped to the function expression. The function declaration on the other hand, declares a new variable, with a new function object assigned to it. This produces something equivalent to the function expression above,

var greeting = function () {
  console.log("Hello!"); 
};

Unlike function expressions, function declarations cannot be anonymous, which is why the the first example function expression was an expression not a declaration. This is an important point as this implies IIFE pattern has to be a function expression.

Without going into any great detail, the distinction between function expressions and function declarations also shows up again in the topic of hoisting: only function declarations are completely hoisted.

The discussion only continues from here: Whether statements or expressions are more performant - I accept it’s a nonce word, or which better lends itself to best-practices.

All the best,

Tom

Blogging Best Practices: Categories v Tags

Categories and tags can be a very useful tool to help make a blog/website more navigable for users and boost SEO to boot. However the specific execution of these features are very much a matter of personal taste and discussion of the subject quickly leads to confusion. This is even more the case for a blogging platform such as Jekyll, which has both few plugins to automate the process and best practices. I myself am guilty of blindly using the very straightforward YAML declarations that Jekyll supports without any real forethought. Wordpress however provides very explicit documentation on the subject, which we can use as a good starting place.

Very simply, categories describe the gross structure of your blog, tags label specific entries. By analogy consider a publication, categories would be the table of contents, tags would be index headings. With this in mind we can anticipate that there will always be at least as many tags than categories, most likely more. The exact number depending on the breadth and depth of topics you choose to blog about, and the level of specificity each category contains. Generally speaking, tags describe something about a particular post, categories group several posts together. Once you have come to a decision how you will use categories and tags in your blog, consistency is key to make the most of your conventions. Another point to bear in mind, more specific to tags, is to make sure to use them effectively. Tags can be both underused and overused, ideally - I use the term very loosely here - you want each tag to be used more than just a few times, without being used for any and every post. Another way to think about this is whether or not the tags actually inform or help users. Analytics services could be helpful here to indicate user flow through your blog.

In practice, the first step is to think ahead: anticipate the breadth and depth you could possibly write about. Although this might not be entirely realistic, it will help prevent the problem of tagitis in the future. Beyond this, you may wish to think about how a user may navigate using categories or tags. As mentioned above, Jekyll tends to have a fairly sparse set of plugins, though there are some authors who have looked at this specific issue.

All the best,

Tom

jQuery Tips

This is a very short post on some useful tidbits I’ve learnt using the ubiquitous jQuery library. I have occasionally found myself in a sticky situation because either (a) the library had not loaded, (b) I’ve been using the wrong version.

We can check if the library is available to us by using either a bang (or two), or using the instanceofoperator. We can use jQuery and $ interchangeably, as they are aliases.

// Load library if it hasn't already
if (!window.jQuery) { 
  // code goes here ...
}

if (typeof window.jQuery == 'undefined') {
  // 'ere be code ... 
}

In the previous example we used window.jQuery as this will simply result in a truthy output. Using just jQuery or $ alone with the leading bang will lead to a reference error.

We can get the version number by logging one of the following,

// Either ...
jQuery.fn.jquery // or jQuery().jquery

// or equivalently
$.fn.jquery // or $().jquery

Of course, we would need to know the library had already loaded before checking the version!

Short and sweet!

All the best,

Tom

High Performance CSS

CSS performance covers a wide range of topics. We can mean anything from selector performance, property performance, architecture practices, and file size to mention a few. At times all these considerations pull in different directions, as what is most efficient for browser processing is least efficient for the developer’s time. This is especially true in relation to selector performance as the most efficiently rendered selectors, ids, are least practical for the purpose of CSS architecture. For the purpose of this post, I’m going to ignore the issue of selector performance as it quite difficult to predict performance costs ahead of time, can lead to bad practices (as already mentioned), and is highly browser dependent. (That said, there is a point to writing well structured selectors, but generally speaking this will be the place where good architectural practices step in.)

We instead want to explicitly look at the overall stylesheet size and property performance to achieve consistent, reliable, and meaningful performance gains for our stylesheets. In relation to the former, it is probably no surprise that a smaller overall file size performs better simply as there are fewer bytes to send over the intertubes. However the gains in rendering time can be significant to say the least. Sticking to a consistent CSS architecture style is the first step to creating smaller stylesheets. Further down the line, we may need to prune unused styles to reduce file size.

Property performance is not often discussed but if neglected can cause real performance problems. Costly properties are those that slow down the render tree construction most. These are properties that require the browser to perform more manipulations, repaint or reflow, in order to paint to/reorganise elements on the screen e.g. a background colour with a gradient as opposed to a plain background. For a WebKit based browser, “border-radius” and “transform” have been shown to be some of the most expensive properties. Our overall design should be sparing with browser reflows and repaints.

The main take away: solid CSS architecture is the gift that keeps on giving, it will empower developers to maintain a DRY, semantic stylesheet, which ultimately leads to performance gains come rendering time. This topic also touches on the issue of Critical Rendering Path optimisation, which I will cover in the future.

All the best,

Tom

CSS Attribute Selectors

We very often style our markup using attribute selectors such as class name or ID. However, CSS gives us a great deal more sophistication when it comes to using CSS attribute selectors.

To start with, we have a vanilla attribute selector,

[attr]

which will match any element with matching attribute selector. If instead we wanted to select a tag with a particular attribute,

elem[attr]

Easy enough. A more subtle point: It will probably be best to assume any attribute selector value i.e. attr=”value”, is case sensitive to avoid any nastiness.

Now the fun part! We can prepend the equals sign between the attribute name and attribute value to define the relationship between them.

[attr='value']

Matches all elements with “attr” with value exactly equal to “value”

[attr~='value']

Matches all elements with “attr” with value containing “value” within a space separated list e.g. rel="this is my value"

[attr|='value']

Matches all elements with “attr” with value containing “value” within a dash separated list e.g. rel="this-is-my-value"

[attr^='value']

Matches all elements with “attr”, with value starting with “value”

[attr$='value']

Matches all elements with “attr”, with value ending with “value”

[attr*='value']

Matches all elements with “attr”, with value contains at least one instance of “value”

You can go even further and combine the rules given above to create multiple attribute selectors.

Altogether, CSS attribute selectors provide more fine-grained control to style markup. For example, you can choose to style anchor tags that link to external pages differently - no need to needlessly suffer classitis.

All the best,

Tom

JavaScript Design Patterns: Revealing Module Pattern

This post carries on from yesterday’s so if you haven’t read, get to it! As you may have guessed from the name, the revealing module pattern is a variant of the module pattern already covered. However, it has proven so popular as to warrant specific mention in most to every discussion of design patterns.

The two takeaways from the module pattern were,

  1. We can choose the visibility of our variables and methods, either public or private,
  2. We use object literal notation to set out public variables and methods.

This is reasonably effective though a bit crude: We have the rather unfortunate practice of writing private entities differently to public ones, the latter use object literal notation. Furthermore it can lead to needless repetition in our code if we wish to reference public entities from another. The revealing module pattern leads to much cleaner code as all our methods and variables, regardless of visibility, are written together. We then return - reveal - the entities we wish to make public. For instance,

var House = (function () {
 
  // Both public and private entities go here using the same syntax
  var privateVar = 0;
  var publicVar = true;
  
  function privateMethod() {
    console.log(privateVar);
  }

  function publicMethod() {
    privateVar++;
  }
 
  return {
 
    // Public properties and methods go here.
    // The methods above are scoped to the closure, this gives us the
    // added benefit of sticking to a more specific naming convention.
    garage: publicVar,
    goShopping: publicMethod
 
  }
})();

Altogether, a bit nicer to look at. There may be some concerns, as with the vanilla module pattern, regarding the difficulty of testing or patching methods which refer to private entities.

All the best,

Tom

JavaScript Design Patterns: Module Pattern

Similar to my previous posts in this series, the module pattern is perhaps better described as a general best-practice than as by a distinct structure. Unsurprisingly then, there are a number of common variations in the wild such as using import mixins and exports. At its core it rests on a very simple principle we will see a lot more of in the future: Using object literal notation to assign property values and method to our class-like objects. This can be particularly useful as a (rather crude) way of setting properties as either public or private. An example using the IIFE pattern,

var House = (function () {
 
  // Private properties and methods go here,
  // everything here is scoped to the function closure
  var numToiletries, printToiletries;
 
  numToiletries = 0;
 
  printToiletries = function( numToiletries ) {
      console.log( numToiletries );
  };
 
  return {
 
    // Public properties and methods go here
    garage: true,
 
    // We can still interact with private variables here
    goShopping: function() {
 
      numToiletries++;
 
    }
  };
})();

This allows us to namespace private variables to the closure. However, this particular pattern can lead to some challenges if we wish to change the visibility or a particular variable at a later date: We will have to make a change at each place the variable was used. This frustration inspired the more sophisticated revealing module pattern, which I’ll cover tomorrow.

All the best,

Tom

JavaScript Design Patterns: Singleton Pattern

The singleton pattern is perhaps one of the more controversial patterns in common use. Ironically, both its proponents and detractors will point to the same feature of the pattern as its main plus/minus. This pattern provides a single instance of a class (or JavaScript object), with a global point of access: it advocates global namespace pollution. This can be particularly useful when using third-party libraries. Although there may be coping strategies available, jQuery for instance provides us with $.noConflict(), it is generally a sign of bad design. Code structured as a singleton pattern indicates that our logical is tightly coupled, which can make debugging nightmarishly difficult.

Unlike the other patterns we will come across, the singleton pattern is not defined so much by a specific written structure, we could just as well talk about either object literals and function closures. All we want is something that provides a globally available object instance. Carrying on from my previous post on the constructor pattern, we can create a singleton example, shamelessly hoisted from Rob Dobson’s post on the subject,

function House() {  
    // check global scope for existing object
    if (typeof House.instance === 'object') {
        return House.instance;
    }

    // bog-standard constructor
    this.bedrooms = 3;
    this.bathrooms = 1;
    this.garage = true;

    // cache this particular object instance
    House.instance = this;

    // implicit return
    return this;
}

This is admittedly quite crude, and highlights the key issue with globally available variables: we have no particular control where and how a given House instance is set. Although not specific to the singleton pattern, we can make it far more sophisticated by making use the IIFE pattern to make the contents private.

All the best,

Tom

JavaScript Design Patterns: Constructor Pattern

The constructor pattern is arguably the bread and butter design pattern. Some context: JavaScript is a so-called classless, inheritance is instead prototypal: objects inherit from objects. This particular feature of the language was originally inspired by Self. With this in mind, we try to mimic class-like inheritance using objects - in particular we want to create object constructors.

To start, all we need to bear in mind is some basic JavaScript syntax,

  1. We can append key to objects using the “dot” syntax,
  2. We create a new object instance using the new keyword.
1. Object.key = value;
2. var object = new Constructor( /* arguments */ );

The pattern usually follows,

  1. Use a function closure to create an object-like structure, this is our “constructor function,”
  2. Append variable values to an object instance using the this keyword,
  3. Append shared object methods to the Prototype object.

Altogether we would get something,

function House( bedrooms, bathrooms, garage ) {
  // this should prevent some annoying problems 
  // such as calling the constructor without `new`.
 "use strict";

  this.bedrooms = bedrooms;
  this.bathrooms = bathrooms;
  this.garage = garage;
 
}

// In other words we want House.prototype.hasOwnProperty('hasParking') === true
House.prototype.hasParking = function () {
  return "Has parking space:" + this.garage;
};
 
var bungalow = new House( 2, 1, true );
var terrace = new House( 3, 2, false );

Though simple in its execution, depending on the nature of the problem at hand the constructor pattern could lead to a lot of unnecessary bloat. In the coming weeks, we will see constructors again and again in some form or another, as they often form a smaller part of more elaborate patterns.

All the best,

Tom

JavaScript Design Patterns: Introduction

In this post I want to cover the general what and why of design patterns. Design patterns are popular, well-supported recipes for writing code. Sticking to a design pattern, as opposed to going completely freestyle can have a number of benefits. Arguably the most important advantage to using a design pattern is the larger community support that they engender: These patterns stick to a known structure, which is more readily communicated, and tend to follow best-practices. Furthermore, the structure they provide often helps prevent making costly mistakes with consequences further down the line. This can be contrasted with so-called “anti-patterns”, which true to their name go against the main advantages of following a design pattern. This includes such sins as namespace pollution, using less efficient non-native methods, and inline script.

Although there is always a kind of specificity in any code, after all we want solutions not just good practices, there are a few commonalities when it comes to writing a true design pattern. These include:

  • The practicality of the solution,
  • How well it follows best practices,
  • How easily a newcomer can come to grips with the pattern.

The latter point naturally leads to a strong emphasis on good documentation and community support, which is something of a virtuous circle. In other words, a design pattern is only a pattern in so far as it follows a solid set of principles.

I hope to work my way through a high-level overview of some of the more popular design patterns in the coming months.

All the best,

Tom