Learning JavaScript the right way™, part 1

I’ve been thinking about writing this for a while and I’ve finally decided to bite the bullet. This is going to be very dense and terse, I’ll go deep into details whenever I feel necessary. This whole series is all about avoiding the bad parts of JavaScript and focusing on the good ones. There isn’t any lack of explanations online about how a for loop works, so I’m assuming that the reader already knows:

  • The structures of imperative programming (for, while, if, else, return, etc.)
  • The principles of Object Oriented Programming (class, instance, interface, method, etc.)
  • Simple data structures (arrays, lists, hashmaps)
  • Big-O notation on a basic level (O(1) vs O(n), etc)

The style recommendations (do’s and don’ts) are my own opinion of what makes JS code readable and maintainable.


  1. Basic types
  2. Arrays
  3. Objects
  4. Functions and Scope
  5. Prototypes
  6. Good JS practices

Continue reading

My new favorite sort algorithm

I haven’t laughed that much in a while.

I just learned about 4chan’s brilliant Sleep Sort algorithm (2011): start a thread for each integer in the array and make it sleep X seconds where X is the value of the integer. When the thread resumes, add that integer to the end of the sorted array. Time complexity is left as an exercise for the reader.

My asynchronous JS implementation:

Array.prototype.sleepsort = function(callback){
    var self = this,
        sorted = [];
    for (var i=0,len=self.length;i<len;i++){
                if (sorted.length === self.length){
            }, self[i]);

[85, 91, 25, 72, 37, 27, 24, 42, 38, 18].sleepsort(function(arr){
    console.log(arr); // [18, 24, 25, 27, 37, 38, 42, 72, 85, 91]

The original bash version:

function f() {
    sleep "$1"
    echo "$1"
while [ -n "$1" ]
    f "$1" &

Original 4chan thread
Code golf on Stack Overflow
Mandatory XKCD reference