A practical walkthrough of using map/reduce with MongoDB to aggregate statistics for generating a report.
Jon Raasch's notes on Nicholas Zakas's Google Tech Talk "Speed Up Your JavaScript" in which he covers basic performance improvements like local variables for more expensive lookups, avoiding for in loops, casting DOM array-like objects into proper arrays, avoid touching the DOM, use classes to change CSS instead of inline styles.
Addy Osmani introduces backbone.js as one part of the toolkit for building mobile JavaScript web applications. Backbone is an MVC-like framework to structure your application, simplifies server-side persistence, decouples the DOM from data, succinctly separates apps into Models, views and routers and provides synchronisation between DOM, model and collections.
Klaus Komenda takes us through the history of development patterns of JavaScript demonstrating the pros and cons. Taking a typical JavaScript feature he starts with the old-school global functions method and iterates through a Singleton, Module Pattern, Revealing Module Pattern, Custom Objects and Lazy Function Definitions bringing the same feature up-to-date.
Ivo Wetzel covers some of the quirks of the JavaScript language. Some of these cause subtle bugs, some overturn conventional wisdom. It covers toString on numbers. Covers the advanced JavaScript features such as prototypal inheritance, this, closures, anonymous wrappers, type-casting, automatic semicolon insertion and hoisting of function and variable declarations.
JavaScript is coming more and more to the fore as a server-side language with a new generation of servers based on the CommonJS (ServerJS) standard. Kris Zyp one of the active members working on CommonJS gives us a summary of the state of play (from January 2010). This includes future directions such as concurrency, promises. And also includes a brief overview of many server-side JavaScript frameworks including Node.js
From Mozilla: An overview of the object-oriented capabilities of JavaScript. This covers OO concepts of classes and objects, instances, abstraction, encapsulation and polymorphism as done in JavaScript with functions and prototypal inheritance.
Based on Simon Willison's original 2005 eTech talk, Simon expands this into a full article covering the expressive functionality of JavaScript. He covers the basics of JavaScript: literals, variables, functions, scope, control flow, objects, classes, inner functions and closures. Everything a developer needs to know before diving into more advanced JavaScript.
John Resig explains JavaScript timers. Because of JavaScript's single-thread nature it is easy to write blocking code that makes pages unresponsive. Timers allow us a mechanism for yielding control back to the browser, queueing the code up to run a little later. John goes into depth on this particular topic.
Ben Cherry, web developer at Twitter, takes us step by step through the Module Pattern. He introduces the standard features of Anonymous Closures and avoiding global scope, and covers advanced concepts such as augmentation, cloning, inheritance, private state and sub-modules.
MSDN reports that 8.4% of all IE9 hangs recently are caused by XMLHttpRequest objects blocking the UI thread because they are using synchronous requests instead of asynchronous. This is a good example of the harm of working against the grain of asynchronous approach in a single-threaded JavaScript environment.
A simplified explanation of closures by Morris Johns: A closure is the local variables for a function - kept alive after the function has returned.
A stackoverflow community article explaining closures in plain simple English does a great job. Succinctly: a closure is created when inner function that gets returned. The inner function can still see the variables and methods defined in the outer function.
A clever hands-on interactive mini-course by Nathan Whitehead that guides you through bite-sized chunks from variables, to functions, to return values, to functions as first-class objects and right into closures and finally continuations. The hands-on exercises are JS Linted and unit-tested which gives you ample space to try out your new-found knowledge.
Angus Croll covers the new 'use strict' operator introduces in EcmaScript 5th edition and how to get started using it. He offers a set of unit test to see how well supported strict mode is in your browser.
Douglas Crockford explains the new strict mode introduced in the 5th edition of ECMAScript. It is an opt-in mode that repairs or removes some of the language's most problematic features such as: function scoping, implied global variables and global leakage, read-only variable failures, octal defaults and function arguments.
Angus Croll takes the reader step-by-step through some basic JavaScript code explaining what 'this' is in each step and why. He explains how 'this' depends on the execution context, and how it is manipulated by how JavaScript functions are called (or applied or bound with bind), and how Constructors create a new context.
Andrew Dupont's Mix 2011 presentation shares his experience with working with messy JavaScript and how to work towards maintainable JavaScript. He covers separation of concerns, using custom events, MVC, templating and developing modular code.
Remy Sharp dissects a piece of jQuery code pointing out the red flags. Each flag is taken in turn, explained and shown how to correct. Takes into account context and the flexibility of jQuery
PPK describes the this keyword as a reference to the owner of the function we are executing, or the object that a function is a method of. He then compares how attaching a function to an event in two different ways affects what the this keyword references.
Tim Caswell describes the JavaScript variable 'this', which is about current scope and current context. The only way to create scope in JavaScript is through function definitions, and in most cases the context is the receiver of the message (the object before the dot in the method call). He also talks about approaches to controlling what this references with call, apply and bind.
Mike Alsup builds up to an elegant plugin development pattern for jQuery plugins, starting with requirements and adding a piece at a time. By explaining the reasoning and though behind each piece of the puzzle, it explains a number of important good parts of the JavaScript language
Christian Heilmann lays out seven rules to better unobtrusive JavaScript, including not making assumptions about JavaScript, the browser and the document. Work with structured markup. If you are traversing a document, maybe there's a solution that can take advantage of CSS's selector mechanism instead. Work with browsers and users. Better understanding of events, and playing nice with namespace, scope, and patterns. And of course, think about the next developer, so keep the code maintainable.
Fellow co-worker Lawrence Carvalho discusses the Undo functionality, and as web based applications start to replace desktop ones, this crucial bit of functionality will become expected by application users. Lawrence talks about the Memento design pattern and guides us through designing objects that can undo their changes. He builds an undoable text widget.
Jim Ley covers the intricacies of type conversion, implicit and explicit. He covers type conversion into boolean, string, number, undefined, null; and parsing into floats and integers. This is backed up by conversion tables for quick reference. There's also a useful section on regular expressions for form field validation.
Andy Hume whittles away the various JavaScript libraries to produce a clear explanation of event delegation and how it works. Its a technique that reduces the number of event listeners attached to the document by attaching just one event listener to a container element. He presents a simple code example and talks about the benefits of event delegation, including performance and code maintenance. (Includes workarounds for IE and a Safari bug)
Cory Hudson sees callbacks as benefiting from currying JavaScript functions, and defines currying as turning a function with two arguments into a function with one argument that returns a function of one argument. He starts off with two functions and shows how to combine them into one curried function, and also builds a generic version. He shows a good usage of a curried function in an array map()
function, which is similar to Prototype's bind()
.
Jonathan Snook demonstrates when JavaScript passes by reference or passes by value. Essentially, primitive types are passed by value, objects are passed by reference. Passing functions however, makes things look like a pass by value if the this
keyword is being used in the code. Snook offers workarounds to this by passing objects so that the context is correct, or using the call()
function to ensure the context is correct.
Dan Webb describes curried functions as a way of creating reusable callback functions for event handlers or Ajax requests, or anything that takes a function as an argument. By using closures, curried functions have a simple way of persisting data between calls. He also offers an elegant way of running a lots of methods on objects, with a simple map function written as a curried function.
Svend Tofte discussed currying JavaScript functions, which he describes as a way to partially evaluate functions. Its a function that returns another function. In an example, one function either adds together two numbers, or if only one parameter is sent, returns a function that can be called later to supply the second number.
Tim describes another two different approaches to using the Module Pattern (a way of creating Singletons). The first example takes advantage of the natural indentation to clearly see which methods are private and which are public. The second is a curried function, a function that returns another function.
David Dorward compares dot notation and square bracket notation, where square bracket notation can be used where dot notation can't. Recommends using dot notation, because its easier to read, and square bracket notation when it can't be done with dot notation.
Tim Huegdon uses JavaScript to fix Safari's bug where clicking on a label doesn't set focus to the corresponding field element (a useful accessibility aid). Using YUI and event delegation Tim walks us through the development of this piece of code involving attaching an event listener, getting the target of an event, then finding the field that corresponds to the label, and focusing on it if its a text field, or activating / selecting the form element if its a radio button or checkbox.
Erik Arvidsson warns against extending the JavaScript Object with Object.prototype, as it can lead to breakages in third party code when they use the for(key in obj) method of iterating through any class (since they all are subclasses of Object). Instead Erik recommends extending the classes that directly benefit from the extending functions, and treat Object as a final constant. Erik also suggests that hashes and associative arrays should be done in JavaScript using Object, not Arrays.
Christian Heilmann offers another incremental improvement to the Module Pattern, and calls it the Revealing Module Pattern. This defines an anonymous object that contains a list of methods and properties that are publicly available. Christian notes that this method also allows you to set up a public property that's privately generated by a method. Christian's improvement makes it quickly clear which properties and methods are public.
Ryan Campbell of Particletree offers a step-by-step guide to getting started with JSON. Since JavaScript can use JSON to either send or receive from the server (both parts of an AJAX request), Ryan suggests getting started with sending JSON (after stringifying it) to the server and converting it to a server side object. Then sending that object back, encoded as JSON, to the client and process that. He offers working library code for both JavaScript and PHP (for the server part).
Simon Willison blogs about how JQuery won him over. From its faddish start based around CSS selectors (getElementsBySelector), and method chaining, Simon now sees the library in a new light. Simon shows how jQuery supports modern development best practice such as namespaces, giving a quick nod to the richness of jQuery selectors (DOM, CSS and XPath). JQuery's event handling looks natural and offers an event when the dom is ready. It exposes custom events for non-trivial Ajax requests. Simon's so convinced about jQuery that he's willing to overlook his rule that developers should know how a library works before using it.
Exploring the features of Firebug, with code examples covering using the console, timing code, stack traces, debugging and breakpoints, profiling, tracing HTTP requests. An excellent overview of Firebug's functionality
Christian Heilmann compares the Object Literal to Douglas Crockford's Module pattern and finds that the Module pattern fixes a major problem of the object literal - the difficult choice of using this or fully qualified references to functions in the same block. Christian also covers the improvements in the Module Pattern, like the decluttering of the return block, which makes the resulting a little easier to work with.
Eric Miraglia explains Douglas Crockford's Module pattern, a way of creating encapsulated JavaScript functions that offer private and public methods and properties. It uses an anonymous function that returns an object containing our methods, and avoids the big issue of cluttering up the global namespace with global functions. Its based on the Singleton pattern.
Klaus Komenda discusses a number of ways of encapsulating JavaScript functions into objects and namespaces, and shows how to use each pattern. He covers Singletons, Douglas Crockford's Module Pattern and Custom Objects, building the same functionality with each technique.
Tim Huegdon and Mark Aidan Thomas create an elegant wrapper to the YUI Connection Manager that manages repeating Ajax JSON requests. Tim describes the use of Custom Events, and the use of the Observer design pattern, dissects the code and offers a tidy demonstration of the working code. This simplifies JSON requests into declaring a simple function to process the returned JSON object, and a single line to fire off the request (within a setInterval if required)
A BetterExplained article that discusses how to reduce the initial load time of JavaScript files. Covers measuring load times, and a number of approaches to delaying the loading of a JavaScript file. Also covers minifying JavaScript and maintaining a debug version of code. Also covers an AJAX onLoad pattern to dynamically include JavaScript after page load, and HTTP caching of external JavaScript files
An evolt article that covers using Regular Expressions, including the difference between static and dynamic regular expressions (compiled at compile time or runtime respectively). Good selection of tables such as regex modifiers, patterns and escaping, look ahead, backreferences. Includes a short section on usage. A neat short cheatsheet for starting to use regular expressions.
As web pages become more and more like applications, code performance becomes more and more important. This article looks at a number of performance issues to avoid, in EcmaScript, DOM and AJAX requests. Covers eval, the with keyword, try/catch in performance-critical code, global variables, implicit object conversion, string concatenation, primitive operations over function calls, repainting and reflowing documents, modifying elements, using XPath.
Jack Slocum presents a simple recipe to avoid memory leaks, including setting onreadystatechange to null on completion of an XMLHttpRequest, clean up DOM Event handlers on unload, never put non-primitives into a DOM node.
Stuart Colville investigates the differences between form.getAttribute('action') and form.action, also the cross-browser differences, when the action is a relative URL. One way returns a relative URL, and the other returns a fully qualified URL.
Dean Edwards takes Mozilla's newly introduced forEach method, and implements it for non-Mozilla browsers, for enumerating over objects and arrays.
Another Douglas Crockford video. This time Douglas talks about the Document Object Model, about how Java failed, and JavaScript evolved thanks to DHTML and DOM. He talks about how to use DOM to traversing and manipulating elements in an HTML document, walking the DOM, making elements, innerHTML, as well as Events, memory leaks. He talks about the cracks in DOM, and how we must be prepared to back off when we hit the browser limits of DOM.
Douglas Crockford's presentation on Advanced JavaScript. He covers topics such as inheritance, modules, debugging, efficiency and JSON.
Douglas Crockford explains why global variables in JavaScript are evil, causing unreliability and insecurity. JavaScript is a block of text that is eval'ed which leaves artifacts in the window's global object. He talks about why Yahoo! chose to use the global variable YAHOO all in uppercase.
Douglas Crockford examines the need for minimising the size of JavaScript code and compares minification and obfuscation. Obfuscation has the side-effect of introducing bugs because it changes variable names. The recommended approach is minification along with GZip compression. Since JavaScript is sent along in source form, it is impossible to hide that from a determined hacker
Douglas Crockford's JavaScript code conventions. Covers indentation, line length, comments, variable and function declarations, minification, statements and labels, whitespace, scope and eval.
First in a series of talks from Douglas Crockford about the JavaScript language. These talks cover the JavaScript language, from the history, the language, advanced features, platforms, standards and programming style. Talks about inheritance, using functions to build objects, closures, as well as the basic JavaScript syntax. Also covers code conventions. JavaScript is a language that requires discipline.
Although JavaScript is a class-free, object-oriented language using prototypal inheritance, it can still be used in a classical object-oriented way. Douglas Crockford compares the two inheritance-based systems, adding syntactic sugar to JavaScript to allow classical inheritance, and demonstrates a number of patterns that are not available in classical languages.
An example of a Decorator pattern based on the flexibility of prototype to extend a JavaScript object. Decorating an object allows customised functions to be called before and after a method call, the real method call is wrapped between the before and after hooks. One method of Aspect-oriented programming with JavaScript
Matt Kruse's JavaScript Toolbox presents a number of excellent best practice ideas including: using var, feature detection, when to use square bracket notation, avoiding eval, referencing forms and form elements, avoiding the with keyword, using onclick instead of JavaScript pseudo-protocol, using unary + to type convert to numbers, avoiding document.all, not using HTML comments in script blocks, avoid cluttering the global namespace, avoiding prototype.js, avoiding synch Ajax calls, using JSON and the correct way to use script tags
Christian Heilmann describes an approach to building complex web application by basing them around events, particularly around YUI's CustomEvent class.
Joe Hewitt, in this Dr Dobbs article talks about using the Firebug extensions to inspect and debug Ajax applications (or any browser-based JavaScript application). It also has CSS inspecting capabilities, editing JavaScript on the fly, inspecting HTTP request and responses, logging, breakpoint debugging and profiling. A useful howto.
Tim explains object orientation in the context of JavaScript, covering concepts like object literal, encapsulation, inheritance using prototype, composition through association and aggregation, polymorphism. Useful read for OO-aware developers to grasp some of the potential of JavaScript.
Guides, notes, overviews, documentation for the Prototype library. Pathfinder compiles a list of useful resources for this library.
Christian Heilmann does a tree menu without using loops. It demonstrates the flexibility and power of Event delegation - catching events at a higher level in the document. It drastically cuts down on the number of events you need to add to a document. One event handler per menu, rather than one per link in the menu.
Ryan Campbell shows how to get the Prototype library up and running, and introduces and documents Protoype's $() function. Form helper functions, getElementsByClassName functions, Element helper functions, Ajax support, timer functions are all covered.
Michael Mahemoff runs into a problem with Protypes $$ function when looking for class names. Its taking over 90 seconds when more than 100 matches are returned. The advice is: Avoid $$(".classname") on large DOMs.
Svend Tofte puts together a detailed guide to setting up and using the Venkman debugger. From basic debugging to watchlists and call stacks, breakpoints, and more advanced techniques like meta comments and profiling. It also contains a list of other useful Venkman resources.
Stuart Langridge provides unobtrusive JavaScript that makes HTML tables sortable by their table headers. To enhance a table to be sortable requires the addition of the classname sorttable
Christian Heilmann demonstrates delegating events, and compares it to the main alternative of assigning event handlers to each individual node. Its a technique that's important for writing applications that can scale.
Dustin Diaz discusses the Object Literal form of JavaScript, pointing out benefits such as better organisation of code in a namespace / wrapper.
Douglas Crockford discusses how to create private members and methods, and using privileged methods to bridge the gap between public and private. It also contains the simplest and most understandable definition of closures I've ever seen.
Douglas Crockford discusses his method of exposing the powerful prototypal inheritance from JavaScript, using his object function which untangles JavaScript's classical-adopted constructor pattern.
An explanation of scope in terms of an execution context and scope chain. Also describes how we can alter the this reference using apply and call.
An overview of object literals and object oriented programming, referencing attributes and functions, prototype objects, creating singletons.
PPK describes the three main data formats for requesting data from the server, weighing up the advantages and disadvantages. In the ensuing discussion the general feeling is that JSON is the most popular and simplest method.
Ryan Campbell volume tests Prototype's each() Enumeration function and finds that although the code is more elegant than the for loops, the overhead is quite heavy, and the performance impact too high. The summary: If basic JavaScript will do the task, then use basic JavaScript
Gez Lemon reviews Christian Heilmann's recently published book. Its a thumbs up, and recommended for developers working with standards and accessibility, regardless of their JavaScript level.
A collection of gotchas and guidance in Greasemonkey scripting. Positioned as an addition to Mark Pilgrim's dive into Greasemonkey
Mark Pilgrim dissects the security issues of the 0.3 Greasemonkey, and describes how the new architecture of Greasemonkey works, pointing out pitfalls and how to address them.
A non-academic and understandable explanation of closures, with examples. 'In JavaScript, if you use the function keyword inside another function, you are creating a closure.'
Jeremy Keith describes unobtrusive JavaScript by talking about separating content, style and behaviour.
Dustin Diaz names his top ten list, which includes Scott Andrew's addEvent(), Dean Edwards' cssQuery(). The cookie manipulation functions take the first three places, and the Prototype $() gets an honourable mention. Dustin also includes a JavaScript file containing all 10 favourite methods.