Daniel Matthew HTML, CSS, and JavaScript developer

Substring, Substr, and Slice.

When dealing with strings in JavaScript, there are several options available when needing to return a particular section:

Substring

This function can accept two parameters: the first an integer between 0 and the length of the string; the second an integer between 0 and the length of the string. substring returns a subset of a string between one index and another, or if the second parameter is omitted, through to the end of the string. A useful feature of this implementation is that if the first parameter is larger than the second, the effect of substring will be as if the arguments were swapped.

Substr

substr is a variant of substring. The difference here is that while the first parameter defines the first character, the second specifies the number of characters to return.

Slice

Both arrays and strings boast a slice method. The arguments it will accept are integers to define the the start and end points of the extraction. Again, if the end point is omitted, the function will keep going until the end of the string. A benefit is that the second argument can be a negative value, which will allow the operation to begin counting from the end. On top of this, slice will return a new string.

References

Closures 101

I updated this post on the 16th February in order to clarify my writing and thoughts.

What is a closure?

In computer science:

a closure is a first-class function with free variables that are bound in the lexical environment. Such a function is said to be “closed over” its free variables. A closure is defined within the scope of its free variables, and the extent of those variables is at least as long as the lifetime of the closure itself.

A higher-level definition is that

A closure is a function defined within another scope that has access to all the variables within the outer scope.

And just in case, think of it as:

…like keeping a copy of the all the local variables, just as they were when a function exited.

Closures are a strange concept to get to grips with, but once this core concept is understood they’re relatively easy to understand: a closure is created when a developer accesses variables outside of the immediate lexical scope.

An example of a closure in action

function makeAdder(a) {
  return function(b) {
    return a + b;
  };
}

x = makeAdder(5);
y = makeAdder(20);

x(6); // 11
y(7); // 27

JSFiddle demo

What happens in a closure?

When makeAdder is called, a new scope is created with one property: a - the argument passed to the function. It also returns the anonymous function declared within it. This returned function maintains a reference back to that original scope. This scope will persist and escape being garbage collected until there are no more references to that function.

Take a look at what happens when we log x:

function(b){
  return a + b;
}

So when we call x and pass an argument, that’s going straight into the anonymous function makeAdder returned the first time. Because we know a closure is a combination of a function and its scope

Since we are then able to all y, we discover that we have ended up with two different copies of makeAdder’s local variables: one in which a is 5, and another where a is 20.

When would I use a closure?

The technique is often used to prevent against contaminating higher levels of scope - data is kept tucked away. Along these lines, a closure can be used to help practise encapsulation: an object can return its public methods and variable, while keeping those intended to be private hidden and inaccessible to the rest of the codebase.

You may have taken advantage of one without realising it, as they’re a key concept when implementing an ‘Immediately-Invoked Function Expression’ (IIFE). Using an IIFE within a module, as per the Module Pattern, ensures that the module is self-contained.

An intelligent developer will

use closures to create additional scopes that can be used to group interrelated and dependent code in a way that minimises the risk of accidental interaction.

Useful reading

Event Delegation In JavaScript

First, some markup:

<ul id="list">
  <li id="item-1"></li>
  <li id="item-2"></li>
  <!-- A little while later - hope this is automated! -->
  <li id="item-99"></li>
  <li id="item-100"></li>
</ul>

What is event delegation?

In the example above, it’s inefficient for both the browser and the developer to write event listeners for a large number of elements - particularly if these elements are being generated dynamically. Event delegation entails attaching a single listener to the parent element, then checking the target element as it bubbles up through the document structure.

What are the advantages?

Writing less code, for one, and less code means fewer opportunities for bugs to arise. It also means that when elements are removed, we don’t run into the risk of forgetting rid ourselves of their event listeners. Too many of those floating around in memory - particularly in complex web applications - can cause problems for the browser.

How do I implement event delegation?

Here’s a no-frills example:

document.getElementById('list').addEventListener('click', function(e) {
  if (e.target) {
    console.log(e.target.id); // Prints item id
  }
});

(See the demo)

JavaScript Feature Detection

Some JavaScript features just don’t work in certain browsers. While it used to be a common practice to ‘sniff’ the user-agent string of the browser, this is now frowned-upon. The preferred approach is for developers to implement feature detection. That is, testing the ability of the browser to carry out the desired task. If the feature is not supported, we write our code intelligently in order to cater for this eventuality.

In Mark Pilgrim’s Dive Into HTML5, he documents a selection of techniques:

  • Checking for the existence of a property on a global object
  • Creating an element and checking for the property on that
  • Calling a method on a generated element and examining the value it returns
  • Setting a property on an element to a particular value and checking to see whether it has retained this value

A common example of the first technique is when writing an AJAX function:

var xmlHttp;
if (window.XMLHttpRequest) {
  xmlHttp = new XMLHttpRequest();
} else {
  // Figure out which ActiveX control to set up for Internet Explorer
  var XmlHttpVersions = new Array(
  'MSXML2.XMLHTTP.6.0',
  'MSXML2.XMLHTTP.5.0',
  'MSXML2.XMLHTTP.4.0',
  'MSXML2.XMLHTTP.3.0',
  'MSXML2.XMLHTTP',
  'Microsoft.XMLHTTP');
  
  for (var i = 0; i < XmlHttpVersions.length && !xmlHttp; i++){
    try {
      xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
    } catch(e) {
      // Here be dragons
    }
   }
  }

Thankfully, libraries such as Modernizr can be implemented in order to reduce the amount of boilerplate that needs to be written. It has an API that can be queried to easily check for feature support. If they’re not present, we can write a fallback so that the user’s experience isn’t compromised:

// Determine if font-face is supported
if (Modernizr.fontface) {
  // Do something
} else {
  // No fancy fonts
}

References

Ensure A Table Fills Its Containing Element

table {
  table-layout: fixed; // Default is auto
}

I was wondering what the correct CSS property was to control this requirement. Setting a width on the table element was doing precisely zip. That is until we set the above.

Loops in Sass

Sass makes it dead simple to automate repetitive tasks we might encounter when writing CSS.

Sass ‘For’ loop

@for $i from 1 through 100 {
  .box:nth-child(#{i}) {
    // Properties
  }
}

Sass ‘Each’ loop

@each $member in john, paul, george, ringo {
  .bandmember.#{$member} {
    background url("images/#{$member}.png");
  }
}

Linked Lists

This is one of a series based around understanding a number of core Computer Science concepts - please read the original post for the intentions behind it.

A linked list is often used to implement data structures including lists, stacks, queues, and associated arrays. It’s constructed from a list of nodes which when linked together represent a sequence. Each node is built of its data and a pointer to the next node in the sequence. Elements can be inserted or removed at any position.

In JavaScript, a linked list could look like this:

// A single node
var node1 = {
	data: null,
	next: null
};
    
// Add data to node
node1.data = 12;

// Create another node
var node2 = {
	data: null,
	next: null
};

// Link (aha!) first node to second
node1.next = node2;

This will soon become rather unwieldy to manually manage, so at this point we’ll need to write a function that can do the grunt work for us.

The Path to Mastery

After reading Zach Wentz’s Medium post on CodeSchool, I resolved to reminding myself of the concepts I’d encountered while studying for my Computer Science degree.

Wentz’s key point is that:

To truly master the art of programming, we must learn the techniques available to us, not just the tools. Data structures, algorithms, design patterns, and computer science concepts are what I’m talking about here.

Of them, some came back incredibly quickly, while others were new - and I’m glad to have refreshed my memory, because they are genuinely interesting topics.

I’ve been drafting a series of posts that cover each of the topics Wentz suggested - I hope they’re of use.

Data Structures

  • Linked Lists (22/01)
  • Binary Trees
  • Tries
  • Stacks
  • Queues
  • Vectors/ArrayLists
  • Hash Tables

Algorithms

  • Breadth First Search
  • Depth First Search
  • Binary Search
  • Merge Sort
  • Quick Sort
  • Tree Insert/Find

Concepts

  • Bit Manipulation
  • Singleton Design Pattern
  • Object-Orientated Programming
  • Factory Design Pattern
  • Memory (Stack vs Heap)
  • Recursion
  • Big-O Time

Flavours of Linux

For whatever reason, I have found myself looking after two VPS set-ups: the first running CentOS with South West Broadband, the second an Ubuntu droplet over at Digital Ocean. Thing is, after learning the basics of server configuration, and getting comfortable with the way CentOS does things, I’ve only gone and confused myself by flitting between the variants. Common tasks are carried out in quite different ways.

For instance, CentOS uses yum as its package manager; Ubuntu has apt-get. When configuring Apache on CentOS, it is restarted using /etc/init.d/httpd restart (which I’ve aliased to the slightly snappier reboot). Back in Ubuntu-land, this operation is done with service apache2 restart, but don’t forget to activate any new hosts with a2ensite.

Below is a short table describing the commands I’ve found useful as a website owner:

TaskCentOSUbuntu
Change passwordpasswd
Add a useradduser USERNAME
Delete a useruserdel USERNAME
Remove user directoryrm -rf /home/USERNAME
Delete user and their home directoryuserdel -r USERNAME
Webroot/var/www
Edit virtual hosts/etc/httpd/conf/httpd.conf/etc/apache2/sites-available/site-name
Enable virtual hostN/Aa2ensite site-name
Reboot Apache/etc/init.d/httpd restartservice apache2 restart
Install packageyum install packageapt-get package
Find IP addressifconfig eth0

PS - Sorry for not using your favourite distro, or for doing things in an incredibly convoluted manner. Feel free to correct me on Twitter with any tips and tricks you’ve picked up!

Using Grunt to Compile Sass

A quick snippet from my gruntfile.js that illustrates how I’m using Grunt to watch my Sass directory for changes, before compiling and outputting minified CSS.

grunt.initConfig({
  watch: {
    css: {
      files: ['public/sass/**/*.scss'],
      tasks: ['buildcss']
    }	
  },
  sass: {
    build: {
      options: {
        style: 'compressed'
      },
      files: {
        'public/css/styles.css':'public/sass/styles.scss'
      }
    }
  }
});

grunt.registerTask('buildcss', ['sass']);

When coding, use grunt watch to keep track of changes, or run grunt buildcss to manually compile the files.