FeedBurner makes it easy to receive content updates in My Yahoo!, Newsgator, Bloglines, and other news readers.
Learn more about syndication and FeedBurner...
The last three years have been a whirlwind of amazing experiences. I taught English and IT in Thailand, developing a web application for a charity while I was there. I worked for Buildabrand, a logo-generation startup in Notting Hill, London. I helped the awesome folks at Uxebu build Pixelplant, their Flash-to-HTML5 conversion platform, and even got to work on the open-sourced Bonsai graphics library. I also worked for Lab49 building large and complex HTML5 web applications for desktop and mobile devices.
It is with great excitement that as of May 2013, I will be moving on to the next endeavor. I am part of a very exciting project that I can’t spill the beans on quite yet but while it’s growing I still need to make a living, and so I’m happy to be able to accept freelance work.
I am primarily looking for work of the following kinds:
I can do remote work or part-time on-site work in London. If you’re interested please check out my CV and my Github profile.
Please contact me here.
Over a year ago I released Sonic, a JavaScript Canvas utility for making loading spinners. I’ve used it in a couple of my own projects and was pleased with the result but I quickly became aware that others may not be happy to:
Not long after releasing Sonic, Github user cadc made SonicGIF, introducing me to a novel concept — converting images in an HTML5 Canvas to an animated GIF on the fly using jsgif.
Fast forward to this week and I’ve been working on a live Sonic editor so you can create spinners using JavaScript, immediately have them converted to GIF, and even a PNG Sprite (example), for you to use via a CSS3 steps Animation.
The spinner you use should be tailored to your needs though. This particular niche of graphic animation is split between various different techniques, each with merits of their own, so choose wisely…
<animate>, <animateTransform> etc.
[1]: By “continually recalculated”, I mean that the animated property values need to be recalculated on each frame and then the corresponding graphic needs to be drawn (even if you cache property values, individual elements need to be drawn for each frame). As far as I know this is unavoidable with traditional JavaScript DOM Animations (including SVG Animations). This is in contrast to Canvas, for example, where you have the opportunity to cache rendered frames and simply re-run them indefinitely.
The graphical capabilities of each technique should also be taken in account. If it’s a straightforward circling snake or dots then you’re probably best going with either SVG or DOM+CSS. If, on the other hand, it’s a more complex animation (e.g. gradients, blur, unique pathing) you may want to venture into Canvas territory or even developing your own PNG Sprite in Photoshop (or Sonic Creator!!). That said, a straightforward GIF may be the best solution if you’re not too fussed about 256 colours, lack of alpha transparency or a lower FPS.
From limited testing the most performant spinners are those using CSS3, either to animate DOM elements, or to animate through a PNG Sprite. Of course, a single spinner on a page will cost very little, so it’s not necessarily something you need to worry about.
For CSS+DOM Animation where all you want is a basic spinner (i.e. lines arranged in a circular fashion pulsating with frequency) I suggest using spin.js which utilises CSS3 Animations and falls-back to VML in older versions of IE.
If you do need more control and are happy using either HTML5 Canvas, GIFs or PNG Sprites (with CSS3) then I reckon you should try out Sonic Creator.
This is some humble advice on how I believe people should deal with bad code. It’s not technical advice. Actually it’s not really advice. It’s just stuff I’ve been thinking of lately.
Typically, the first thing a person does when encountering bad code is determining who they should blame.
Immediately it becomes a personal or tribal vendetta.
“Who could be so foolish?”
“Who is responsible for exposing my brain to such incoherence and blasphemy?”
“Who insults the house of <Insert Team Name>!?”
This is wrong. This should not be the first step. A deeper understanding of the code is necessary before we identify the poor soul who should suffer your wrath.
Too often a programmer is sure. People generally are quite stubborn, but I find programmers to be more-so. Programmers mostly deal in absolutes so I guess such confidence is understandable.
Approach the code with curiosity and a yearning to understand. Empathy for the person who wrote the code would help too. Imagine yourself in their shoes. They may not be anything like you. They probably care about different things too. They probably don’t have the same streak of what you call perfectionism. Their capacity for caring may be directed somewhere other than the whitespace that nestles their parentheses or the seemingly incoherent naming of their variables. Maybe they have a life.
Without empathy you are not going to understand the code, nor how it came about. You will simply sit there vocally festering in your self-appointed superiority.
Do you want to understand why there are such rampant GOTOs, such deeply nested switch statements, such obtuse naming, such ugly spacing?
It’s dead easy to understand. Just imagine that the code is yours and that you’re trying to rationalise your own stupidity. Eventually your mind will fathom sensible defenses: “I was being rushed”, “I didn’t understand the API”, “I didn’t have sufficient overview of the domain” …
Before you know it you’ll have a battery of excuses, and quite a few of them will probably touch on the truth. You could have written code this bad. It’s not beneath you.
As if you were a biologist discovering a new species that had evolved through millenia, without a watchful eye nor guiding hand. Such a creature begs questions. Such a creature begs inquiry. Of course, with code, you can just ask the author what their intentions were, and this is probably what you should do.
Yes, it’s crazy, but true. You can approach the author and ask them. I must warn you though: this may force you to take a slice of humble pie.
But what if there is no good reason. What if it is, in fact, laziness, or ignorance, or worse, malice?
Yep, I’m afraid so. Now that you’ve discovered the error it falls on you to spread your wise words so that nobody may befall such crappy code again.
Don’t let your ego play you though. Don’t email the entire team. Don’t shout from the rooftop. Don’t write another blog post. Your biggest mistake is believing that:
And if you have to email everyone. If you have to shout from the rooftops. If you must write a blog post about a topic that annoys you so, please remember to inject parody and hints of self-deprecation so as to to disguise your ego’s intent. If you were to write an article you should title it genuinely though, so as to entice the stubborn programmer to read your post… something like “how to deal with bad code” would work well.
Yep, sorry. You’re crap at many things. Yeh, yeh, you’re good at some stuff, but you’re pretty crap at everything else. Don’t blame others for not being as great as you think you are. The truth will hurt in the end. That you are in-fact the same blubbery mamallian mass as every other programmer,.. as every other person.
Now for some more delicious humble pie…
A few weeks ago I set about creating a new markup language. I wanted to learn more about language parsing, grammars, and the various difficulties involved.
I also had a very specific idea of what I wanted to create: a dead simple alternative to HTML. I’d recently picked up SASS and tried to draw on its succinctness to inspire me. CSS itself is quite succinct in how it declares elements, IDs, classes and attributes. And SASS, drawing on its own inspiration, HAML, adds the elegance of tabbed nesting.
I’d done something similar a while ago, allowing you to get DOM structures from basic CSS selectors:
ul li:5 span[innerHTML="item"]
Using satisfy() this becomes:
<ul>
<li><span>item</span></li>
<li><span>item</span></li>
<li><span>item</span></li>
<li><span>item</span></li>
<li><span>item</span></li>
</ul>But I didn’t want to stop there; I wanted to create a way to define entire HTML documents with minimal syntax. i.e. allowing you write stuff like:
html
head
title 'something'
body
h1 a[href=/] 'something'I began by looking into PEGjs, a really impressive parser generator for JavaScript. It allows you to specify the rules of your grammar like so:
Single
= Attribute
/ Element
/ Text
/ Directive
//...
Attribute
= name:AttributeName _ ":" _ value:Value (_ ";")? {
// This bit is just regular JavaScript...
return ['Attribute', [name, value]];
}Above specifies the grammar rule, Single, which defines various valid “Single” definitions, such as Attribute, which is also specified above. The Attribute rule references AttributeName:
AttributeName
= name:[A-Za-z0-9-_]+ { return name.join(''); }
/ StringAn AttributeName can be a string of characters matching the pattern [A-Za-z0-9-_]+ or a String (wrapped in quotes), which is also specified in the grammar.
It’s seemingly dead-simple, although there are gotchas like left-hand-side recursion and poisonously inefficient backtracking. At one point it was taking my parser 700ms to parse this:
a {
b {
c {}
}
}I found that I was writing rules in such a way that meant there was a lot of backtracking happening. I.e. when the parser tried a rule and failed on it, it would go back to the initial character trying the next alternate rule. In a nutshell, don’t do this:
SomeRule = [a-zA-Z]+ '::' [0-9]+ ';' / [a-zA-Z]+ '::' [0-9]+
Instead, just make the semi-colon optional:
SomeRule = [a-zA-Z]+ '::' [0-9]+ ';'?
This may seem trivial but it’s not always easier to spot for higher level rules. Small optimisations like this matter.
I was able to get that ridiculous 700ms down to 5ms! And there are still improvements to be made.
The generator would have to be able to take output from the parser and generate HTML from it. From a string like a b c the parser outputs a structure like this:
[ "Element", [ [ [ "Tag", "a" ] ], [ [ "Element", [ [ [ "Tag", "b" ] ], [ [ "Element", [ [ [ "Tag", "c" ] ] ] ] ] ] ] ] ] ]
The HTML generation was quite simple to do. Essentially, I treated every Element as an entity that can have children. An Element’s children could be other Elements, Attributes, Text or even custom directives. So, this:
label { label: foo; input#foo }
Would parse to:
[ "Element", [ [ [ "Tag", "label" ] ], [ [ "IncGroup", [ [ "Attribute", [ "label", "foo" ] ], [ "Element", [ [ [ "Tag", "input" ], [ "Id", "foo" ] ] ] ] ] ] ] ] ]
Essentially, the hiararchy that you originally write is reflected in the tree outputted by the parser. The generator can then just recurse through this structure creating HTML strings as it goes along.
For example, this is the default generator for HTML attributes:
//... _default: { type: 'ATTR', make: function(attrName, value) { if (value == null) { return attrName; } return attrName + '="' + escapeHTML(value) + '"'; } }, //...
This would make `for:foo;` output the HTML, `for=”foo”`.
The fake power you feel when creating a language frequently manifests in strange features and syntax. That’s what happened here. Although I do genuinely feel that this particular one is useful.
I’m talking about “Exclusive Groups”. When writing your CSS-style selectors, it allows you to specify alternates within braces and then these will then be expanded so that the resulting HTML conforms to all the potential combinations. An example:
x (a/b) // expands to: "x a, x b"
That would give you:
<x> <a></a> </x> <x> <b></b> </x>
A more complex example:
(a/b) (x/y)
That would give you:
<a><x></x></a> <a><y></y></a> <b><x></x></b> <b><y></y></b>
The original selector (a/b)(x/y) expanded to a x, a y, b x, b y.
A little nifty, a little pointless.. perhaps. Although it can be useful:
ul li ('A'/'List'/'Of'/'Stuff')(becomes)
<ul> <li>A</li> <li>List</li> <li>Of</li> <li>Stuff</li> </ul>
I wanted there to be the option to use traditional CSS curlies to demarcate nestings. I.e.
div {
ul {
li {
//...
}
}
}But I also wanted auto-nesting via indentation, like in SASS:
div
ul
li
//...Stuff became tricky, quickly. The problem with auto-nesting is that the expected behaviour can become ambiguous:
section
h1
em
span
div
pFurthermore, you have to contend with spaces and tabs. Which one counts as a single level of indentation?
The solution I eventually rested on was simply letting the user mess stuff up themselves, if they wanted. The parser will count levels of indentation by how many whitespace characters you have. I’d like to add an error that’s thrown if the user’s silly enough to mix tabs and spaces. For now, though, they’ll have to suffer. There is an inherent ambiguity in this kind of magic. What should the parser do with this? –
body
div
p {
span
em
}Right now, we assume, because the user has opted to use curlies on the p element, that the auto-nesting should be turned off until the curly closes. Another option would be to reset the indentation counter to zero and try to resolve children regularily. But the above code is still ambiguous. Should an error be thrown? Maybe “SyntaxError: What on earth are you doing?“
Yeh, it’s done, more or less.
Technically, it’s an HTML preprocessor. It’s not a templating engine. It doesn’t do that. Reasons are as follows:
Also: client-side templating is a minefield of different approaches. I’ll stay out if I can.
SIML can cater to the DOM template style quite gracefully. This is using SIML’s Angular generator:
ul#todo-list > li
@repeat( todo in todos | filter:statusFilter )
@class({
completed: todo.completed,
editing: todo == editedTodo
})That produces:
<ul id="todo-list">
<li
ng-repeat="todo in todos | filter:statusFilter"
ng-class="{ completed: todo.completed, editing: todo == editedTodo }"
></li>
</ul>The @foo things you see above are directives. You can create your own in a new generator, if you so wish. The Angular generator, by default, will create ng- HTML attributes from undefined psueod-classes and directives. So I could do:
div:cloak @show(items.length)
And that would generate:
<div ng-cloak ng-show="items.length"></div>
It’s early days and I’m not even sure if SIML provides enough value as-is, but I do think it could serve devs quite well for the following use-cases:
The last point is quite powerful, I think. Imagine having a bunch of pre-defined directives that would allow you to do stuff like:
#sidebar
input
@datepicker({
start: [2013,01,01]
})As a learning exercise it was very valuable. I hope, as a happy accident, I’ve created something potentially useful to others.
A ux.stackexchange question prompted me to consider how one might implement a more permissive type of input validation. It’s not rare for a form to punish the user if they add an extra space before typing in a date, or accidentally use a comma instead of a period when typing in an IP address. After-all, we employ strict validation to keep the data correct.
Garbage In — Garbage Out. It rings true but maybe, taken too literally, it makes us form strict validation and a no-exceptions policy to rebels. We punish a user typing ’12′ instead of the fully-qualified ’2012′,… why? Either it’s our thoughtlessness or it’s the very unlikely (depending on context) possibility that the user did in-fact mean the year ’1912′ or ’1812′ or ’1012′…
If we start down the road of permissive input validation then we need to also explore input correction. We can’t allow a rogue comma to slip in and not correct it. It’s probably best to correct it straight away (not too soon — possibly on blur) so that the actual data stored conforms to the correct format.
William Hudson executed a date survey in 2009 to discover all the various ways American users like to enter dates. The results show that users use a variety of formats. It makes perfect sense to accept all these variants and let the computer figure out what is what.
For the specific problem of entering dates, I would like to recommend Date.js, because it can successfully parse most of those variants. However, there is a big caveat when it comes to dates, especially on international forms. The American style of entering a date, MM/DD/YY, is technically impossible to differentiate from the other standard of DD/MM/YY, unless the DD portion happens to be above 12. For this reason I guess it would be best to cater to your localized users as best as possible.
An alternative is to retain rigidity in your validation but allow for some minor mistakes. For example, insist upon the ISO format of YYYY-MM-DD but don’t make a fuss if the user separates with a slash or a space (or heck, anything) instead of a dash.
My point is: Maybe formal validation with permissive aspects mixed in gives us the best of both worlds. We don’t punish the user for minor mistakes, and we don’t end up with ambiguous data.
In an attempt to practice this technique of mixing rigidity with leniency, I created vic.js.
Currently validation in JavaScript can be quite an ugly affair, plagued with remnants of DHTML and overly invasive input masks. It’s not uncommon to see stuff like this:
someInput.onkeyup = function() { if (!this.value.match(/some rigid regex/)) { alert('Enter the right value, you fool'); } };
Typically the rules are strict, the characters non-negotiable, the regular expression unyielding, and the presented invalidation UI annoying.
vic.js (a.k.a Vic, VIC) allows you to define a lenient regular expression, and it expects you to extract your important data from the captured groups.
Vic’s signature goes something like this:
vic( LENIENT_PATTERN_WITH_CAPTURED_GROUPS, PER_GROUP_PROCESSOR, POST_PROCESSOR );
The simple example would be a ‘year’ field:
var yearVic = vic( /^\s*(\d{1,4})\s*$/, function(year) { // Let's assume anything between 14 and 99 is from the 1900s: return vic.pad(year > 13 && year <= 99 ? '1900' : '2000' )(year); }, Number // cast full output to a Number ); yearVic('2012'); // => 2012 yearVic('01'); // => 2001 yearVic('hd2kd9'); // => false yearVic('20021'); // => false yearVic('96'); // => 1996 yearVic(' 4'); // => 2004 yearVic('113'); // => 2113
The regex used for the year example, /^\s*(\d{1,4})\s*$, is lenient in that it allows whitespace at the beginning and end, and doesn’t mind if the user enters one, two, three or four digits for the year. For years greater than 13 or less than 100 we assume the user is referring to the previous century, so we apply ’1900′ as padding, otherwise we assume we should pad with ’2000′.
Vic offers a couple of helpers for basic tasks like padding, applying lower/upper case, etc. I’ll probably be adding to these as I think of more common use-cases for vic.
Vic allows more atomized per-group processing too. In this example we’ll validate a date in the form YYYY-MM-DD, but we’ll allow any one of ./,:- (plus spaces) as separators, and we’ll validate the component numbers and pad them too:
var vicDate = vic(/^\s*(\d{1,4})[.\/,: -](\d{1,2})[.\/,: -](\d{1,2})\s*$/, { 1: function(year) { // Year between 50 and 99 assumed to be '19YY', otherwise presumed after 2000 return vic.pad(year >= 50 && year <= 99 ? '1900' : '2000' )(year); }, 2: function(month) { return month >= 1 && month <= 12 && vic.pad('00')(month); }, 3: function(day, i, all) { // Check that there are {day} amount of days in the entered month: return day > 0 && day <= new Date(all[1], all[2], 0).getDate() && vic.pad('00')(day); } }, function(v) { return v.join('-'); }); vicDate('111'); // => false vicDate('2/3/4/5'); // => false vicDate('16.332.2'); // => false vicDate('20 1 20'); // => false vicDate(' 1999.7.0'); // => false vicDate('1999.0.1'); // => false vicDate('1999.9.32'); // => false (no 32 in Sept) vicDate('1999.2.28'); // => '1999-02-28' vicDate('1999.2.31'); // => false (no 31 in Feb) vicDate('1.1.1'); // => '2001-01-01' vicDate('1956.3.2'); // => '1956-03-02' vicDate('16.03-2'); // => '2016-03-02' vicDate(' 20 1 20 '); // => '2020-01-20' vicDate('1999.7.31'); // => '1999-07-31'
What we’ve done above is execute a rigid validation of the data that’s important to us (YYYY, MM and DD) while letting the user mess with the non-important stuff to their heart’s content (whitespace & separators).
Vic is simple. It’s not a high level abstraction but it’s not complex. It’s a few lines of code.
The fact is: you could easily integrate this methodology into your own validation utilities. The basic principle is to extract the important data, validate it, but allow the user some flexibility in how they give you the important data.
Check out vic.js on Github.
My last post discussed techniques I once saw as the height of cleverness but now deem foolish. The truth is: I’m still battling with these coding dilemmas everyday… It seems to be a constant game of cleverness/terseness/speed vs. verbosity/readability.
We’re told to write code for the poor soul who has to maintain it in the future. What nobody tells you is how much knowledge this poor soul has, both about the language and the problem domain. People also say to expect this future maintainer to be an idiot — this will mean you write the most understandable code possible. But again: how much of an idiot is this person?
The fact is: we have a set of unspoken assumptions we tend to make about this mystery future maintainer.
The following are mostly assumptions related to JavaScript syntax. Unexplored assumptions are ‘Design patterns’, ‘OOP’, ‘The problem domain’ etc.
new Number(1) != new Number(1)*** The above is not exhaustive and is very subjective. I don’t wish to compartmentalize understanding into levels — it’s misleading. I just wanted to somehow portray these assumptions in a clearly understandable way.
I think most devs simply do not consider a future maintainer that is any less capable than themselves, and perhaps this is a problem. If you mark yourself as a maintainer 4.5 then is it fair for you to write in a way that presumes that all future readers of your code are <= 4.5? Is this reasonable?
I suppose it depends on what the code does (e.g. high level MVC sugar vs. low-level 3D rendering) and the people that you’re currently working with, for it is from them that you are likely to draw your estimation of an appropriate maintainer level.
I’m interested to hear other peoples’ opinions on this.
What level do you assume in your future maintainers? How clever does your code get before you deem it reasonable to add a comment or opt for a more explicit and clearer technique?
For me there was a time that can only be described as adolescence in the field of programming and more specifically JavaScript. This period was characterised by a certain laziness and hubris. I thought I was right. I thought others were wrong. I could see no path but the very strict one that I had boxed myself into through a process in which I longed for certainty and the expulsion of realistic doubt.
Today I present a short list of JavaScript practices that once seemed right but I now deem foolish (in most situations):
a() || b.foo.bar(); m && c() ? d() : l || m.foo[bee](3);
There is no real advantage in forgoing convention for the sake of cleverness.
function calculate() { var a, m, t, y, This, is, really, understandable = false; // Actual logic goes here }
Instead I declare a variable where it makes sense. Much of the time this is at the top of the scope, but there are enough exceptions to make me shake my head in dissapproval at the thought of a style guide imposing religious top-of-scope declarations.
function prepareRequest(mode, updateId, value) { var req = { mode: mode, updateId: updateId, value: value, uid: genUID() }; // etc. }
It’s better for clarity and performance (potentially) to define separate classes for cases where you repeatedly make object literals of the same structure. For example the above could be refactored into a Request class.
if (/r[ -~]?(?:m\d+|\d+[0-3]{2,})_m?$/.test(thing)) { // ... wat }
It makes sense to cache these things. Plus naming it means someone might have a chance of understanding WTF the code does.
They make no sense unless used in the various idiomatic loops.
if (typeof x === 'string' && x === 'mode:45') { // ... }
Sometimes it’s overkill. Regular equality can be used in both of the above cases.
if (!cachedReturnValues[key]) { cachedReturnValues[key] = value; }
It’s potentially dangerous. E.g. It’s better to use the ‘in’ operator to discover presence, or even ‘hasOwnProperty’.
// This is a loop for (var i = 0; i < arr.length; i++) { // This is me adding one to the item in the array at the index // specified by the variable `i` declared slightly above this comment: arr[i] += 1; } // this is the end of the loop
Commenting everything demonstrates either a lacking clarity in your code or a lacking clarity in your mind as to the intention of comments. Commenting nothing shows hubris and laziness.
Unit tests give me the confidence to be sure that my code does what I intend it to do.
A long name suggests bad API design. Re-think where you’re defining the variable/method. Think of a circumstance in which the variable name could be shorter — a context that makes sense for that variable. Then create that context. You’ll probably end up with a cleaner internal API. E.g.
// Version 1: var responseCache = {}; function generateNextIDForANewResponseCacheItem() {...} function deleteResponseCacheItemsThatDoNotEqual(value) {...} // Version 2: function ResponseCache() { this.data = {}; } ResponseCache.prototype = { genNextID: function() {...}, remove: function(optionalFnCheck) {...} };
This never works and never solves what you think it will. It’s better to dynamically sway and constantly rethink your idea of what is right and wrong given each situation as it arises. This is why I try to steer clear of over-zealous coding style dogma, or all dogma for that matter.
I want to share a tiny character-saving trick I use when flooring a number towards zero in JS. Hopefully you’re aware of the following idiom:
~~numberToBeFloored
Don’t worry… this post isn’t all about ~~…
In most cases this is used instead of Math.floor because it’s faster, terser and most important, much more confusing! Be careful though, it has different behaviour to Math.floor. For most cases, it has the effect of flooring the number towards zero. I wrote a post covering it in some detail a while ago.
It’s important to note, as pointed out by Mathias Bynens, that this and other similar bitwise operations only work reliably on numbers that can be expressed as 32-bit sequences. Any numbers above 2147483647 or below -2147483648 will not work as you expect. This is usually acceptable though.
The actual trick which I wanted to post about relates to operator precedence. I often find myself in a situation like this:
// Generate random RGB red value: var r = ~~(Math.random() * 255);
The bitwise-not operator (`~`) has a higher precedence than the multiplication operator (`*`) so the parentheses around `Math.random() * 255` are necessary to avoid the `~~` only applying to `Math.random()`. i.e.
// This doesn't work correctly var r = ~~Math.random() * 255;
Fortunately, there are other similarly effective bitwise operations that have the same flooring effect, but with lower operator precedence. One of them is `0 | n`. The pipe operator (bitwise OR) has a lower precedence than the multiplication operator so we can use it without the need for parentheses:
var r = 0 | Math.random() * 255;
So we can save a couple of characters! Joy!
There’s also the bitwise shift operators with similarly low precedence, e.g.
var r = Math.random() * 255 >> 0; var r = Math.random() * 255 << 0; var r = Math.random() * 255 >>> 0;
It’s definitely worth getting familiar with the various operator precedences in JavaScript. It’ll help you know when you’re wasting time with parentheses.
Mathias also gave us a JSPerf test case benchmarking all the various flooring solutions in JavaScript. Check it out!
Just to be clear, with all these strange bitwise flooring operations, we’re not interested in manipulating the bits of the 32-bit sequence at all. All we’re interested in is getting the integer produced by the internal `ToInt32` operation, hence why all bitwise flooring techniques are no-op bitwise operations: e.g. we bitwise-not and then bitwise-not again, causing a reversal of its effects (comparable to `!!true`). We bitwise-or with zero as an operand, meaning that for every bit-pair, the non-zero operand will win and thus nothing will change… and it’s the same deal with `n << 0` and `n & n`...
What's important is that accessing the internal ToInt32 via bitwise operations is much faster than via the `parseInt` function, as is clearly evident in Mathias' test case.
... and now for the "revelation":
Regarding the usage of these tricks: over time I've come to the opinion that they're almost entirely pointless. The performance differences, even though they may seem staggering, are entirely negligible in most cases. You should only sacrifice readability for performance if you really need to squeeze out those precious microseconds. The only other reason for using these bitwise tricks is to make your code look more complicated than it really is, which is probably a stupid reason. As mentioned, there are also edge cases to watch out for. You can't just replace all your current `Math.floor()` calls with `~~`. Things will likely fail. What's worse is that your test coverage probably isn't exhaustive enough to catch these edge cases!
Even though I shouldn't, I still use them though. They're "cool"...
After observing the JS “community” for a while and its various skirmishes I have come to the conclusion that, due to their capacity in attracting loud voices, these are the areas that JavaScript developers seem to care most about:
To clarify, there are a lot of really valuable discussions that occur surrounding the above topics, but there is also a lot of passionate rhetoric defending various sides with little basis in fact or pragmatism.
On the other side of the coin we have areas that are still cared about but are rarely fought over with such passion and rhetoric:
Somewhere in between these two extremities lies AMD.
This is just an obvervation… and I thought it worth posting. Did I miss anything?
Lots of people are doing this nowadays:
(function(window, $, undefined){ // my special module }(window, jQuery));
If you’re using this, it’s probably not needed. It’s usually just redundant cruft. The IIFE itself is okay (i.e. (function(){...}())). It’s the arguments that are the problem.
This strange concoction is used to protect a module’s scope from the environment in which its placed.
I have some bones to pick though…
If you can’t trust the window variable, then what can you trust? And you’re not even guaranteeing anything by passing it in. Some script could still overwrite it before you arrive. And the window object is still available for other scripts to mutate as they please, even after your have passed it in.
And you can’t trust jQuery either? You think some prototype.js imp is going to somehow travel into your code and re-assign the global dollar symbol? Ok ok, this may be permissible if you’re creating a third-party jQuery script, but certainly not if you have full control of your app.
Most importantly, who the hell overwrites undefined? Again, if you’re having to protect against this then you should deal with that issue directly. Go and knock on Bob’s door and tell him to stop overwriting undefined!
I know, I know. You’re writing a third-party script which may be placed in hostile environments. But here’s the thing: for every potential breach that you’re “protecting” yourself from there are a near-infinite amount of other things that someone could do to mess up your script, and you can’t protect yourself against all of them!
In my opinion, it’s acceptable for your code to be sensitive to the assumptions it makes about its environment. Yes, Bob, my module/plugin/library is going to mess up if you decide to overwrite undefined, and you should expect it to. Why should we protect ourselves from this imaginary (and probably non-existent) behaviour? I would love to know who overwrites undefined. Do you? If you do, then stop it.
I’m definitely not having a go at the general pattern of (i.e. the humble IIFE):
(function(){ }())
Actually, it’s incredibly useful in places. It allows me to create and run in a fresh scope which means I don’t have to risk polluting the global namespace.
Passing undefined though… The only possible benefits it gives are: a potential minuscule performance improvement due to a slightly lesser scope lookup (so miniscule that you’d be crazy to care). Also, it provides you with the possibility to use an alias like undef, but I’m not sure how helpful that really is anyway. And what’s wrong with var undef;?
Also, for readability’s sake, don’t pass so many things into your module’s main IIFE. It means the reader has to scroll all the way to the bottom just to see what each value is.
So, to sum up, this pattern:
(function(window, $, undefined){ // all ma code }(window, jQuery));
… is not the cure people claim it to be.