5 JavaScript Techniques Your Should Be Using

Through fire and flames, I’ve learned quite a few JavaScript techniques that have assisted in improving productivity, code quality, and code maintainability. Although simple in nature, I’d like to share the five techniques that I’ve found most beneficial when writing JavaScript:

1. Closures

A closure, in its most basic form, looks like a function within a function. This is a powerful concept because all local variables inside of an inner function can be relatively accessed after that function has returned. I like to think of closures as a particular scope’s “save state”. Free variables contained within closures are remembered, even after that function is returned. Closures are great because they provide scope to your functions and help protect sensitive areas of code.

function outer ( x ) {
    // x is a free variable within inner,
    // but when inner returns, the reference
    // to x’s value is saved and its scope
    // is “closed over”
    function inner () {
        return x;
    return inner;
var hello_world = outer( “hello world” );
// when inner closes over, x’s value of
// hello world is closed within that instance
// and returned to the hello_world namespace
console.log( hello_world() ); // hello world

Closures are used all over the place in JavaScript frameworks — probably in many places you’re not even aware of. It’s important to know what a closure is, but even more important to know how to use it. One of the most frequently used closure patterns is the Immediately-Invoked Function Expression. You will often see this expression where protecting scope is imperative.

(function( window, undefined ){
  // variables defined within the instance of
  // this closure are protected from the global
  // scope; however, we can attach them to the
  // sanitized window object for external reference
  var local_var = ‘foobar’;
  window.global_var = local_var;
})( this );
// this example of an IIFE creates a closure
// within it’s own scope, and both invokes and
// returns itself to it’s parent scope
console.log( typeof local_var ) // ‘undefined’
console.log( global_var ); // ‘foobar’
// in this example, the “inner” function is immediately
// closed over on itself when invoked; however, if it
// were named and set to a namespace, ‘local_var’ would
// be relatively accessible via the inner function’s scope

2. Object Literals

An object literal is a custom object defined in your code. Object literals are used in several ways, such as: containing multiple variables without polluting the global namespace, creating API objects, and passing neatly mapped data into a function. Here are examples of object literals in action:

// containing multiple variables
var data = {
  number: 55,
  string: “Hello World!”,
  array: [ “foo”, “bar” ]

Wrapping related data in an object literal grants scope to the data, as well as cleaning up the local namespace.

// creating API objects
var API = {
  foo: function ( data ) {
    // methods scoped to the “API” namespace

Creating API methods as part of an object literal grants specific scope to each method. This is highly advantageous due to each API’s ability to be quarantined, version-ed, and debugged with ease.

// passing mapped data to functions
function foo ( params ) {
  for ( key in params ) {
    console.log( key, params[key] );
  number: 55,
  string: “Hello World!”,
  array: [ “foo”, “bar” ]
}); // number 55 \n string Hello World \n array foo bar

Using object literals to pass data to a method is helpful when there are multiple arguments. Since object literals act as key-value stores, they can be passed in any order, allowing the API’s method to scale without updating each callee instance ( just be sure to validate object existence on required keys ).

3. Namespaced Application Objects

One of the great things about JavaScript is its ability to be written in many ways. However; this can also be a great pitfall if the author does not keep their code structured well. Globally namespacing an application object helps keep all system utilities and methods organized and easy to work with.

( function ( window, undefined ) {
  var APP = {
    init: function () {
      console.log( APP.pets, APP.favorite.color, APP.favorite.number );
    pets: [ “cat”, “dog”, “fish” ],
    favorite: {
      color: “blue”,
      number: 55
  // attaching this object to the global namespace allows attributes to be accessed
  // outside the scope of this closure – some like to emulate the concept of “private” methods
  // by not attaching those parts of the application object to the global scope
  window.APP = APP;
  $( document ).ready( APP.init ); // cat dog fish \n blue \n 55
})( this );

4. Console and Developer Tools

Problems are easily solved when enough data is provided regarding the issue. Browser development tools provide a console object and interface that can process data and browser information which is priceless when fixing JavaScript bugs. Logging data is a crucial tactic used in every programming language, so knowing how to use the console is necessary. I use the developer tools bundled in Google Chrome ( mostly because the V8 JavaScript engine is ridiculously fast ). Reading up on your dev tools’ abilities can drastically increase your productivity.

Chrome Dev Tools

Firefox Dev Tools

5. TDD

Test Driven Development is an essential part of our process at QuickLeft. Most developers have some experience in testing code, but are they actually test driving it? Test driving your JavaScript results in cleaner, more stable code. JavaScript can be hard to write in an organized manner. Frameworks like jQuery and Prototype make it very easy to develop code soup. Every large JavaScript project I’ve seen that isn’t test driven ends up in a big mess of bind events, meaningless closures, and random half-baked functions that don’t work in certain contexts. These inefficiencies often bloat the project budget and bug list significantly. Although the benefits of testing are sometimes argued against, there is no supportive defense that outweighs the amount of structure and stability test driving your JavaScript will enforce.

Not all tests are created equal. It is very important to make sure your tests cover the right functionality. Different project types call for different testing methodologies. In an event-driven application, any function that could be used from more than one context should be abstracted from it’s origin into a helper or API method. Test driving these methods help insure stability from an external context, but more importantly, it helps force the developer to write scalable and well structured code.

If you want to try TDD but don’t know where to get started, I would reccomend playing with Jasmine, QUnit, or PhantomJS:




`instanceof` considered harmful (or how to write a robust `isArray`)

By kangax

Checking types in Javascript is well known as a pretty unreliable process.
Good old typeof operator is often useless when it comes to certain types of values:

typeof null; // "object"
typeof []; // "object"

People often expect to see something like “null” in the former check and something like “array” in the latter one.
Fortunately, checking for null is not that hard, despite useless typeof, and is usually accomplished by strict-comparing value to null:

value === null;

Checking for arrays, on the other hand, is a somewhat tricky business. There are usually two schools of thought – using instanceof operator (or checking object’s constructor property) and the-duck-typing way – checking for presence (or types) of certain set of properties (which are known to be present in array objects).

Obviously, both ways have their pros and cons.

1) `instanceof` operator / `constructor` property

instanceof operator essentially checks whether anything from left-hand object’s prototype chain is the same object as what’s referenced by prototype property of right-hand object. It sounds somewhat complicated but is easily understood from a simple example:

var arr = [];
arr instanceof Array; // true

This statement returns `true` because Array.prototype (being a prototype property of a right-hand object) references the same object as an internal [[Prototype]] of left-hand object ([[Prototype]] is “visible” via arr.__proto__ in clients that have __proto__ extension). An alternative constructor check, which I mentioned earlier, would usually look like:

var arr = [];
arr.constructor == Array; // true

Both instanceof and constructor look very innocent and seem like great ways to check if an object is an array. If I remember correctly, latest jQuery is using constructor:

An excerpt from jQuery (rev. 5917):

isArray: function( arr ) {
  return !!arr && arr.constructor == Array;

The problems arise when it comes to scripting in multi-frame DOM environments. In a nutshell, Array objects created within one iframe do not share [[Prototype]]’s with arrays created within another iframe. Their constructors are different objects and so both instanceof and constructor checks fail:

var iframe = document.createElement('iframe');
xArray = window.frames[window.frames.length-1].Array;
var arr = new xArray(1,2,3); // [1,2,3]  

// Boom!
arr instanceof Array; // false  

// Boom!
arr.constructor === Array; // false

This “problem” was mentioned by Crockford as far as back in 2003. Doug suggested to try duck-typing and check for a type of one of the Array.prototype methods – e.g.:

typeof myArray.sort == 'function'

Exactly for these reasons Javascript authors often resort to a second approach:

2) Duck-typing

We’ve been using it in Prototype.JS for quite some time now. Dean Edwards was using it in its base2, last time I looked at it.

An excerpt from Prototype.js (v.

function isArray(object) {
  return object != null && typeof object === "object" &&
    'splice' in object && 'join' in object;

By “fixing” multi-frame “problem”, this naive approach fails short in some of the trivial cases. If you were ever to have an object with splice and join properties, Object.isArray would obviously detect that object as being an Array:

var testee = { splice: 1, join: 2 };
Object.isArray(testee); // true

Back in June, I was reading ECMA-262 specs and noticed that there was an easy way to get value of an internal [[Class]] property that every native object has. Object.prototype.toString was defined like so:

Object.prototype.toString( )
When the toString method is called, the following steps are taken:
1. Get the [[Class]] property of this object.
2. Compute a string value by concatenating the three strings “[object “, Result (1), and “]“.
3. Return Result (2)

Contrary to Function.prototype.toString which is implementation dependent and is NOT recommended to be relied upon, Object.prototype.toString has a clearly defined behavior for all native objects. Function.prototype.toString()
An implementation-dependent representation of the function is returned. This representation has the syntax of a FunctionDeclaration. Note in particular that the use and placement of white space, line terminators, and semicolons within the representation string is implementation-dependent.

Just as a fun exercise, I wrote a simple __getClass method, put it into an “experimental” folder and forgot about it : )

function __getClass(object) {
  return Object.prototype.toString.call(object)

A couple of weeks ago, though, someone created a ticket for Prototype.js – proposing an Object.isDate method. An implementation used constructor check and so was vulnerable to cross-frame issues. This is when I remembered about getClass and its possible usage in isArray, isDate and other similar methods.

Specs mention that: new Array([ item0[, item1 [,…]]])

The [[Class]] property of the newly constructed object is set to “Array”.

This means that creating isArray function could not be simpler than:

function isArray(o) {
  return Object.prototype.toString.call(o) === '[object Array]';

The solution is not dependent on frames (since it checks internal [[Class]]) and is more robust than duck-typing approach. I have tested it on a handful of browsers (including some archaic and mobile ones) and was happy to find that all of them are indeed compliant in this regard.

Let’s hope this little “trick” serves as a remedy to cross-frame issues that authors struggle to find workarounds for : )

Fixing the JavaScript typeof operator

Posted: August 8, 2011 | Author: | Filed under: JavaScript

Working with JavaScript’s typeof operator is a bit like operating a clapped-out old car (or an early model Dell Inspiron). It gets the job done (mostly) and you learn to work around the quirks – but you probably aspire to something better.

In this article I’ll give a brief overview of typeof before introducing a tiny new function which is a fully-loaded, more reliable alternative that works directly with the language internals.

The typeOf Operator

How is it used?

Since typeof is a unary operator, the operand follows the operator. No additional punctuation is required.

typeof 2 //"number"
typeof "belladonna" //"string"

But it works when I call it as a function?

The typeof operator is not a function. You can surround the operand with parentheses so that the expression looks like a function call, but the parentheses will simply act as a grouping operator (second only to the comma operator in the obscurity pecking order!). In fact you can decorate the operand with all manner of punctuation without derailing the operator.

typeof (2) //"number"
typeof(2) //"number"
typeof ("a", 3) //"number"
typeof (1 + 1) //"number"

What does it return?

The returned value is a somewhat arbitrary representation of the operand’s type. The table below (based on the one in the ES5 spec) provides a summary:

Type of val Result
Undefined undefined
Null object
Boolean boolean
Number number
String string
Object (native and not callable) object
Object (native or host and
Object (host and not

What’s wrong with typeof?

The most glaring issue is that typeof null returns “object”. It’s simply a mistake. There’s talk of fixing it in the next version of the ECMAScript specification, although this would undoubtedly introduce backwards compatibility issues.

1 var a;
2 typeof a; //"undefined"
3 typeof b; //"undefined"
4 alert(a); //undefined
5 alert(b); //ReferenceError

Other than that, typeof is just not very discriminating. When typeof is applied to any object type other than Function, it returns “object”. It does not distinguish between generic objects and the other built-in types (Array, Arguments, Date, JSON, RegExp, Math, Error, and the primitive wrapper objects Number, Boolean and String).

Oh and you’ll hear folks complaining about this…

typeof NaN //"number"

…but that’s not the fault of the typeof operator since the standard clearly states that NaN is indeed a number.

A Better Way?


Every JavaScript object has an internal property known as [[Class]] (The ES5 spec uses the double square bracket notation to represent internal properties, i.e. abstract properties used to specify the behavior of JavaScript engines). According to ES5, [[Class]] is “a String value indicating a specification defined classification of objects”. To you and me, that means each built-in object type has a unique non-editable, standards-enforced value for its [[Class]] property. This could be really useful if only we could get at the [[Class]] property…


…and it turns out we can. Take a look at the ES 5 specification for Object.prototype.toString…

  1. Let O be the result of calling ToObject passing the this value as the argument.
  2. Let class be the value of the [[Class]] internal property of O.
  3. Return the String value that is the result of concatenating the three Strings "[object ", class, and "]".

In short, the default toString function of Object returns a string with the following format…

[object [[Class]]]

…where [[Class]] is the class property of the object.

Unfortunately, the specialized built-in objects mostly overwrite Object.prototype.toString with toString methods of their own…

1 [1,2,3].toString(); //"1, 2, 3"
3 (new Date).toString(); //"Sat Aug 06 2011 16:29:13 GMT-0700 (PDT)"
5 /a-z/.toString(); //"/a-z/"

…fortunately we can use the call function to force the generic toString function upon them…

1 Object.prototype.toString.call([1,2,3]); //"[object Array]"
3 Object.prototype.toString.call(new Date); //"[object Date]"
5 Object.prototype.toString.call(/a-z/); //"[object RegExp]"

Introducing the toType function

We can take this technique, add a drop of regEx, and create a tiny function – a new and improved version of the typeOf operator…

1 var toType = function(obj) {
2   return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
3 }

(since an new, generic object will always use the toString function defined by Object.prototype we can safely use ({}).toString as an abbreviation for Object.prototype.toString)

Let’s try it out…

01 toType({a: 4}); //"object"
02 toType([1, 2, 3]); //"array"
03 (function() {console.log(toType(arguments))})(); //arguments
04 toType(new ReferenceError); //"error"
05 toType(new Date); //"date"
06 toType(/a-z/); //"regexp"
07 toType(Math); //"math"
08 toType(JSON); //"json"
09 toType(new Number(4)); //"number"
10 toType(new String("abc")); //"string"
11 toType(new Boolean(true)); //"boolean"

..and now we’ll run the same tests with the typeof operator (and try not to gloat) …

01 typeof {a: 4}; //"object"
02 typeof [1, 2, 3]; //"object"
03 (function() {console.log(typeof arguments)})(); //object
04 typeof new ReferenceError; //"object"
05 typeof new Date; //"object"
06 typeof /a-z/; //"object"
07 typeof Math; //"object"
08 typeof JSON; //"object"
09 typeof new Number(4); //"object"
10 typeof new String("abc"); //"object"
11 typeof new Boolean(true); //"object"

Compare to duck-typing

Duck-typing checks the characteristics of an object against a list of known attributes for a given type (walks like a duck, talks like a duck…). Because of the limited usefulness of the typeof operator, duck-typing is popular in JavaScript. Its also error-prone. For example the arguments object of a Function has a length property and numerically indexed elements, but it is still not an Array.

Using toType is a reliable and easy alternative to duck-typing. Reliable because it talks directly to the internal property of the object, which is set by the browser engine and is not editable; easy because its a three-word check.

Here’s an illustrative example – a snippet which defines a non-compliant JSON object. The jsonParseIt function accepts a function as its argument, which it can use to test the veracity of the JSON object before using it to parse a JSON string….

1 window.JSON = {parse: function() {alert("I'm not really JSON - fail!")}};
3 function jsonParseIt(jsonTest) {
4   if (jsonTest()) {
5     return JSON.parse('{"a":2}');
6   } else {
7     alert("non-compliant JSON object detected!");
8   }
9 }

Let’s run it, first with duck-typing…

jsonParseIt(function() {return JSON && (typeof JSON.parse == "function")})
//"I'm not really JSON - fail!"

…whoops!…and now with the toType test…

jsonParseIt(function() {return toType(JSON) == "json"});
//"non-compliant JSON object detected!"

Could toType reliably protect against the malevolent swapping of built-in JavaScript objects with impostors? Probably not, since the perpetrator could presumably also swap the toType function. A more secure test might call ({}).toString directly…

function() { return ({}).toString.call(JSON).indexOf("json") > -1 }

..though even this would fail if Object.prototype.toString was itself maliciously re-written. Still each additional defense helps.

Compare to instanceof

The instanceof operator tests the prototype chain of the first operand for the presence of the prototype property of the second operand (the second operand is expected to be a constructor, and a TypeError will be thrown if it is not a Function):

1 new Date instanceof Date; //true
3 [1,2,3] instanceof Array; //true
5 function CustomType() {};
6 new CustomType instanceof CustomType; //true

On the face of it this seems to hold promise of a nice type-checker for built-ins, however there are at least two snags with this approach:

1. Several built in objects (Math, JSON and arguments) do not have associated constructor objects – so they cannot be type-checked with the instanceof operator.

Math instanceof Math //TypeError

2. As @kangax and others have pointed out, a window can comprise multiple frames, which means multiple global contexts and therefore multiple constructors for each type. In such an environment, a given object type is not guaranteed to be an instanceof of a given constructor….

1 var iFrame = document.createElement('IFRAME');
2 document.body.appendChild(iFrame);
4 var IFrameArray = window.frames[1].Array;
5 var array = new IFrameArray();
7 array instanceof Array; //false
8 array instanceof IFrameArray; //true;

Type-checking host objects

Host objects are browser-created objects that are not specified by the ES5 standard. All DOM elements and global functions are host objects. ES5 declines to specify a return value for typeof when applied to host objects, neither does it suggest a value for the [[Class]] property of host objects. The upshot is that cross-browser type-checking of host objects is generally not reliable:

01 toType(window);
02 //"global" (Chrome) "domwindow" (Safari) "window" (FF/IE9) "object" (IE7/IE8)
04 toType(document);
05 //"htmldocument" (Chrome/FF/Safari) "document" (IE9) "object" (IE7/IE8)
07 toType(document.createElement('a'));
08 //"htmlanchorelement" (Chrome/FF/Safari/IE) "object" (IE7/IE8)
10 toType(alert);
11 //"function" (Chrome/FF/Safari/IE9) "object" (IE7/IE8)

The most dependable cross-browser test for an element might be to check for the existence of a nodeType property…

function isElement(obj) {
  return obj.nodeType;

…but that’s duck-typing so there are no guarantees

Where should a toType function live?

For brevity, my examples define toType as a global function. Extending Object.prototype will get you thrown to the dragons – my preference would be to extend Object directly, which mirrors the convention established by ES5 (and prototype.js before that).

1 Object.toType = function(obj) {
2   return ({}).toString.call(obj).match(/\s([a-z|A-Z]+)/)[1].toLowerCase();
3 }

Alternatively you might choose to add the toType function to a namespace of your own, such as util.

We could get a little cleverer (inspired by Chrome’s use of “global” for window.[[Class]]). By wrapping the function in a global module we can identify the global object too:

1 Object.toType = (function toType(global) {
2   return function(obj) {
3     if (obj === global) {
4       return "global";
5     }
6     return ({}).toString.call(obj).match(/\s([a-z|A-Z]+)/)[1].toLowerCase();
7   }
8 })(this)

Let’s try it out…

1 Object.toType(window); //"global" (all browsers)
2 Object.toType([1,2,3]); //"array" (all browsers)
3 Object.toType(/a-z/); //"regexp" (all browsers)
4 Object.toType(JSON); //"json" (all browsers)
5 //etc..

What toType does not do

The toType function cannot protect unknown types from throwing ReferenceErrors…

Object.toType(fff); //ReferenceError

More precisely it is the call to toType that throws the error, not the function itself. The only guard against that (as with calls to any function) is to practice good code hygiene…

window.fff && Object.toType(fff);

Wrap Up

OK I’ve babbled on for far longer than I intended to – so congratulations if you made it to here, I hope you found it useful. I covered a lot of ground and probably made some mistakes – please feel free to let me know about them. Also I’d love to hear about other people’s adventures in type-checking.

Further Reading

Juriy Zaytsev (“kangax”):
‘instanceof’ considered harmful (or how to write a robust ‘isArray’)

ECMA-262 5th Edition:
The typeof operator
Object Internal Properties and Methods (for more about [[Class]])
The instanceof operator

Terse JavaScript 101 – Part 2

Posted in ‘JavaScript‘ by James Padolsey on October 29th, 2011

Part one, posted last week, explored a few different ways of de-cluttering your JavaScript, and, in the process, making it more readable.

Some developers don’t like the idea of using a language’s more idiosyncratic features because it does, potentially, make your code less readable in the eyes of those who haven’t learned the language properly. I think it’s still up for debate. While you’re pondering that, part II awaits…

If you haven’t checked out the “Truthy & Falsey” introduction then please do so before continuing.


It’s something we barely think about but JavaScript’s expressive diversity allows us to invent new patterns for looping. First, there’s the standard:

for (var i = 0; i < array.length; i++) {}

This is conventional and will be known to developers coming from any language. There’s nothing inherently wrong with it. That said, for me, it’s not ideal.

The first improvement I usually make is to cache the length property of the array:

for (var i = 0, l = array.length; i < l; i++) {}

This doesn’t make it shorter, but it does make it more efficient, although marginally so…

Another change we can make is to combine the iteration expression (i++) and the conditional expression (i < l), like so:

for (var i = -1, l = array.length; ++i < l;) {}

Notice that we’re starting with an index of -1, but won’t worry because before the loop’s body runs, the conditional expression is run, and in the above code, the conditional expression is iterating the index and testing it against the length all in one.

It’s important to note that the prefix increment/decrement operators (++i/--i) return the changed value, while the postfix increment/decrement operators (i++/i--) return the old value. To make this clearer:

var x = 5;
alert(x++); // alerts 5 (old value)
alert(x); // alerts 6

var y = 5;
alert(++y); // alerts 6 (new value)
alert(y); // alerts 6

Another looping “pattern” in JavaScript is to assign and rely on what’s returned from that assignment for the conditional expression:

var elements = document.getElementsByTagName('a');

for (var i = -1, el; el = elements[++i];) {
  el; // => a single element

Yesterday’s post on truthy & falsey bears some relevance here. The expression el=elements[++i] will return the value of elements[++i]. If this value is falsey the loop will not continue. An element list is full of truthy values (objects). We don’t need to be worried about falsey values. Note that in this approach, you may be sacrificing performance for terseness.

In many situations, we do want to iterate over falsey values too, e.g.

var myArray = [1, 2, 3, null, 8, 54, null, 0, 32];

With something like this it would be best to use the traditional i<length conditional expression, but if you’re so inclined feel free to mix the conditional and iteration expressions together like shown further up (++i<l).

If we were feeling a bit crazy, we could combine everything — iteration, conditional test, and assignment of indexed value — in a single expression:

var array = ['a','b','c'];

for (var i = -1, l = array.length, item; item = array[++i], i < l;) {

// alerts, a, b, c

Here we used the useful comma operator which always returns its right-hand operand. In this example we used it to make sure that i < l is what the condition expression returns. Before the comma we’re assigning the value at the iterated index within the array.

I don’t really suggest doing all of this in one line, and to be honest, there’s nothing wrong with conventional looping structures. What I am trying to put across is how much expressive diversity JavaScript provides.


Assignments are expressions too, so you can slot them in wherever you want:

var a = 1;
alert(a = 2); // alerts 2
alert(a); // alerts 2

An assignment operator will always return whatever is on its right-hand side. Be careful with slotting in assignment expressions wherever you want though, because they can be misconstrued for equality operators. For example:

var match;

if (match = '1/2/3'.match(/\d/)) {

To some, upon initial inspection, it may appear that we’re testing match for equality against '1/2/3'.match(/\d/) when in fact the latter is being assigned to the former, and the if statement will run if the assignment expression returns a truthy value (i.e. if its right-hand side operand is truthy).

Casting to a number

Quick and easy:

var str = '222';
var num = Number(str); // => 222

typeof num; // => 'number'

A shortcut is the unary plus (+) operator, used like so:

var str = '222';
var num = +str; // => 222

typeof num; // => 'number'

It works in exactly the same way.

Casting to a string

Once again, quick and easy:

var arr = [1,2,3];
var str = String(arr); // => '1,2,3'

typeof str; // => 'string'

The shortcut, this time, is to simply concatenate an empty string to the value that you’re casting:

var arr = [1,2,3];
var str = '' + arr; // => '1,2,3'

typeof str; // => 'string'

Saving references

Property lookup can be verbose and inefficient. To save space and to benefit performance it’s common to save references and access those properties via the new reference instead of having to evaluate the entire expression every time you want the nested value:

// Original:

// "Caching"
var style = document.body.style;

// Whenever I need to access the `color` value:

It’s often referred to as caching. Essentially, all that’s happening is that a new reference is being created for an object and being assigned to an identifier that you specify. Let’s start with this:

var data = {
    config: {
        doSomething: function(item){

for (var i = -1, l = someArray.length; ++i < l;) {

It would make sense to minimise the amount of property access that needs to occur within the loop, and thus, potentially, anywhere else in our application that references data.config too:

var config = data.config;

Now the loop can simply reference config instead of data.config:

for (var i = -1, l = someArray.length; ++i < l;) {

We could even “cache” the function itself:

var doSomething = data.config.doSomething;

And then call it directly within the loop:

for (var i = -1, l = someArray.length; ++i < l;) {

IMPORTANT: It’s important to note that, when you assign a member function (that is, a function that is a property of an object) you are de-binding its this value, i.e. the context in which it runs. Here’s an example:

var obj = {
    value: 234,
    fn: function(){ return this.value; }

obj.fn(); // => 234

var fn = obj.fn;
fn(); // => undefined

De-binding the fn method will make its context the global (window) object instead of the obj which we defined, so when our fn function looks for its `this.value` it won’t find it (because this is the window, which doesn’t have `value` defined).

End of part 2

Truthy & Falsey

Posted in ‘JavaScript‘ by James Padolsey on October 19th, 2011

Before we continue with the “Terse JavaScript 101″ series, we’re going to take a break and explore, in detail, truthy and falsey.

These are fundamental topics which I should have covered in more detail yesterday. There is copious information on this elsewhere online, so don’t feel limited to this post in your study.

Truthy: Something which evaluates to TRUE.
Falsey: Something which evaluates to FALSE.

It’s mostly logical. One (1) is truthy, Zero (0) is falsey. An object of any kind (including functions, arrays, RegExp objects, etc.) is always truthy. The easiest way to determine if something is truthy is to determine that it’s not falsey. There are only five falsey values in JavaScript:

undefined, null, NaN, 0, "" (empty string), and false, of course.

Note: It is possible to explicitly wrap a primitive (string, number, null, undefined, boolean) in an object, which will make it truthy. For example, 0 (zero) is falsey, but new Number(0) is truthy. A scarier example is new Boolean(false) which is also truthy! Be careful. Only very rarely should you need to explicitly wrap primitives.

Why should you care what’s truthy and what’s falsey?

A value’s truthi’ness determines what it will evaluate to in logical expressions. For example:

if (0) {

We know that the alert() call will never run, because 0, being a falsey value, doesn’t satisfy the if statement’s condition — i.e. to run only if the passed expression is NOT falsey.

From the spec:

The production IfStatement : if ( Expression ) Statement is evaluated as follows:

1. Evaluate Expression.
2. Call GetValue(Result(1)).

↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓

3. Call ToBoolean(Result(2)).

↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑

4. If Result(3) is false, return (normal, empty, empty).
5. Evaluate Statement.
6. Return Result(5).

If you’re wondering, the phrase return (normal, empty, empty) essentially, means: continue with the program in a normal fashion. See 8.9 for more.

As the subtle arrows point out, the bit we’re interested in is step 3, which calls ToBoolean with the result of step 2, which is essentially (*) the value you passed in. But what is ToBoolean??

ToBoolean is simple:

Input Type Result
Undefined false
Null false
Boolean The result equals the input argument (no conversion).
Number The result is false if the argument is +0, -0, or NaN; otherwise the result is true.
String The result is false if the argument is the empty string (its length is zero); otherwise the result is true.
Object true

I hope this has made it clear enough.

Enough of the spec!

We now know what happens when we pass something as an if statement’s expression (if(..this bit..){}), but how much relevance does truthy and falsey have in other logical contexts? Well, a lot.

Let’s explore the basic if statement one last time though:

if (X) {
    // If this code runs, what have we proven about X?

If 123 is alerted what can we say (for sure) about X? We can definitely say that it is NOT one of: undefined, null, NaN, 0, "" (empty string), or false. We can therefore say that X is truthy. It might be the literal value true, a number that’s not zero, an array, a function, etc.

Remember, everything in JavaScript that isn’t a primative value can be considered an object. Functions are objects. Arrays are objects. And all objects are truthy.

Since all objects are truthy, code like this is quite common:

var el = document.getElementById('foo');

if (el) {
    el.style.color = 'red';

el is not a boolean, it’s just an object (in this case, a DOM Element object). The if block only executes if its expression is truthy. We could be more explicit though. The getElementById function returns null if it doesn’t find the element, so we could do:

var el = document.getElementById('foo');

if (el !== null) {
    el.style.color = 'red';

There’s usually little advantage in explicitly stating the falsey value that you’re looking for. Sometimes, you might want to guard against a null or an undefined but allow false, for example. In such circumstances, obviously, use the explicit syntax (strict equality and strict inequality operators – ===/!==).

The ToBoolean thing that we referenced above happens in all logical contexts in JavaScript. For example, the && (logical AND) operator:

0 && alert(0);
1 && alert(1);

In this case, only 1 will be alerted, since zero is falsey and therefore does not satisfy the &&‘s desire for a left-hand truthy operand. The logical AND operator will only evaluate its right-hand operand if its left-hand operand is truthy.

Further up we checked that the return value of getElementById wasn’t null by simply checking if it was truthy. If el was truthy then we knew the element existed in the DOM and we could begin to interact with it programatically.

We use a similar concept with object access.

alert(foo.bar); // Alerting the value of the 'bar' property of 'foo'

The only values that will throw an error when you try to access a property are null and undefined. So, if foo is truthy then we can safely attempt to access it’s bar property without worrying about exceptions being thrown.

if (foo) {

Assume carefully

With our if statement we have only proven that foo is truthy. It still might not be the object we expect. This is something to consider. Normally though, it’s safe enough to suppose that if some obscurely named value is not falsey, it’ll be the truthy value you desire and not something you don’t want.

element.addEventListener ?
    element.addEventListener('click', func, false) :
    element.attachEvent('onclick', func);

Here we make some assumptions:

  1. If element has a property addEventListener and its value is something truthy, it must be a function, so we’ll call it.
  2. If it doesn’t exist then attachEvent must exist and must be a function.

The code above happens to be working around old IE versions that don’t have the W3C DOM Event method, addEventListener. The assumptions I’m making are considered safe in the environments that I intend my web app to operate in, but they may not be safe assumptions in other environments, so it’s important to be wary of the fact that: just because something is truthy doesn’t mean it’s the truthy value you happen to be looking for (the same goes for falsi’ness).

It’s common to attempt deep object access using the following structure:

a && a.b && a.b.c && a.b.c();
  1. Make sure a is truthy.
  2. Make sure a.b is truthy (and thus exists).
  3. Make sure a.b.c is truthy (and thus exists).
  4. Call a.b.c.

Again, we’re making assumptions, but we already knew that. This structure is very useful, although too much of it can make your code bloated, so maybe consider other options. For one: consider what you CAN safely assume. In some instances, you may be able to do this:

a && a.b.c();
  1. Make sure a is truthy.
  2. Call a.b.c.

In this example, we’ve determined that it is safe to assume that if a is truthy, it is the very object that we’re looking for, and therefore must have a minimum structure of: a={b:{c:function(){...}}}. We’re aware of our own data structure so can make this assumption.

Explicit booleans

You might be left wondering why we even bother having proper boolean values in JavaScript if we can get around quite easily with our other truthy and falsey values. And it’s true, we could manage without these booleans, and we rarely check for them explicitly. We usually just do something like:

if (foo.isAFoo()) {
    // ...

foo.isAFoo() could return any truthy value (not necessarily the boolean of true) and it would make no difference to the code execution.

But, it is important, in many situations, to be explicit in our intentions. So we should insist on using real booleans when there is a binary decision to make (two possible values).

To cast a value to its boolean representation, we can just use ToBoolean. We can indirectly use this internal method by calling the Boolean constructor as a function:

Boolean(0); // => false

It will return a boolean value — either true or false, and is a really quick way of finding out whether a value is truthy of falsey:

Boolean(undefined); // => false
Boolean(null); // => false
Boolean(false); // => false
Boolean(0); // => false
Boolean(""); // => false
Boolean(NaN); // => false

Boolean(1); // => true
Boolean([1,2,3]); // => true
Boolean(function(){}); // => true

A well-known and widely used shortcut is to use the logical-NOT operator twice, like so:

!!null; // => false
!!0; // => false
!!123; // => true
!!'foo'; // => true

I’ll leave that up to you to figure out :)


Terse JavaScript 101 – Part 1

Posted in ‘JavaScript‘ by James Padolsey on October 18th, 2011

While some folk will argue that verbose code aids readability, I think almost the opposite, and in this post I’m going to list some basic tips for minimising redundant clutter in your code. JavaScript is a fun language at its core — it’s worth learning the tiny details.

I hope this post is useful to someone. I wrote it not for beginners (although it will be helpful to them), but for all those people writing JavaScript on a daily basis yet haven’t been afforded the time/motivation to get to know the language properly.

new Object()

Nope, don’t do this:

var o = new Object();

Or any of this:

var a = new Array();
var b = new Object();
var c = new RegExp("1(.)3");

Do this instead:

var a = [];
var b = {};
var c = /1(.)3/;

Array literal, object literal, regular expression literal. They rock. There’s usually no need to use the constructor functions when literals are available (please see the note below though).

Note: There are situations when calling Array or RegExp directly can be useful. In such situations, you needn’t bother with the new operator. Array(1,2,3) will produce the same as new Array(1,2,3). Calling RegExp directly can be useful for dynamically building a regular expression from various strings.

Calling a constructor

If you’re not passing any arguments then the parenthesis are not required. E.g.

var a = new Animal();

… and this becomes:

var a = new Animal;

Petty, perhaps. Still worth knowing though.


Quick and easy. Less of this:

var fun = 123;
var tun = 456;
var run = 789;

And more of this:

var fun = 123,
    tun = 456,
    run = 789;

This is why you should use a tab width of FOUR (or 4 spaces).

Undefined & Null

The following is universally true in JavaScript (assuming undefined hasn’t been mutilated):

undefined == null

“So what?”, you say? Well, it means you can replace this:

if (foo === undefined || foo === null) {

… With this:

if (foo == null) {

If something is == to null then it is either null or undefined. Those are the only possible values.

Returning undefined

Not returning something from a function is the same as returning undefined, so you may as well not bother explicitly returning undefined:

function a() {}
function b() { return; }
function c() { return undefined; }

a() === b(); // true
b() === c(); // true

Note: you should be careful with the undefined value as it can be changed. E.g. You can do undefined = true beforehand. The universe would shatter if you did that though, so please don’t. Many libraries declare an empty (undefined) variable in an enclosed scope, which provides a real undefined:


    // My private scope. They can't see me in here.

    var undef;

    undef; // => definitely undefined


Or, more succinctly:


    undef; // => definitely undefined

}()); // <- not passing anything in!

Empty array values

This is entirely legal in JavaScript:

var a = [,,,'foo'];
a[3]; // => "foo"

One potential use-case of this was discussed in my recent post, `match.()` trick.

Less blocks, more expressions

I’m sure we’ve all seen something like this before:

function validateFoo(foo) {
    var regexResult = /^foo+$/.test(foo);
    if (regexResult) {
        return true;
    return false;

A cleaner and more sensible solution is this:

function validateFoo(foo) {
    return /^foo+$/.test(foo);

No fussing with if statements and multiple returns. You can do everything within a single return statement.

Another example. We want to create a function that logs a name, specified by the arguments forename and surname, but if these arguments aren’t passed then the function should use the default values, “Bob” and “Smith”, respectively:

function printName(forename, surname) {

    if (forename == null || forename == "") {
        forename = 'Bob';

    if (surname == null || surname == "") {
        surname = 'Smith';

    console.log(forename + ' ' + surname);


This can be condensed to:

function printName(forename, surname) {

    forename = forename || 'Bob';
    surname = surname || 'Smith';

    console.log(forename + ' ' + surname);


Here, we’re using the logical OR operator (||) to provide a default value (right hand side) if the left hand side evaluates to false. Values that evaluate to false (i.e. “falsey”) are: An empty string (""), null, undefined, 0 and false.

So, this:

forename = forename || 'Bob'

… is essentially saying: if forename is a truthy value, then assign forename to forename (in other words: don’t do anything), but if it is a falsey value (e.g. an empty string), then assign the string "Bob" to forename.

So, our new printName function will behave like so:

//                            -- Logged --
printName();                  // Bob Smith
printName(0, 0);              // Bob Smith
printName(false, null);       // Bob Smith
printName('James');           // James Smith
printName('', 'Jones');       // Bob Jones
printName('Bill', 'Jones');   // Bill Jones

Part 1 [OVER]

That’s it for today. There may be a part two soon enough, depending on how useful this is to readers. I know many of you have surpassed this stage of learning, so sorry for boring you.

Recommended viewing/reading

Seriously, if you’re writing JavaScript as part of your job then you definitely owe it to future maintainers of your code to learning JS properly.

EDIT: Crockford links don’t work. The entire video can be seen on youtube instead.