background preloader

Build Library

Facebook Twitter

jQuery source viewer. JavaScript Array Loops. 1) JavaScript with Native Objects, Volume III of the five-volume Frontend Engineering series, or a good grounding in basic JavaScript. In JavaScript, an array is an object, commonly having property names (strings) that look like small, non-negative integer subscripts. Arrays are constructed using array literals or by calling the Array() constructor: var array0 = []; var array1 = ['cat', 'dog', 'mouse']; // not recommended: var array2 = new Array(); // not recommended, creates ghosts: var array3 = new Array(10); For the remainder of this page we use the word "object" as shorthand for "objects that are not arrays.

" JavaScript, born 1995, features two distinct loop types. First is the arithmetic loop, which comes straight from C, 1972 (see Genealogy of Programming Languages): The second type, an enumerated loop, is JavaScript-specific; variants are common in other languages of the late 20th century: The Conventional Wisdom Well, make that beginners and me, too. Reasons to Prefer for/in Loops. Callback Hell. Introduction to Map and Reduce in Javascript | 49buzz. Recently I held a short lecture on the use of functions in Javascript, and how it’s possible to use functionality like map, reduce, filter and Javascript’s amazing variable context.

I prefer to use underscore.js so that I can use the wonderful functionality even on old browsers. Lets start easy with _.map. Map is easy, what it does is take an input array, send each element into a function, and putting the result in a result array. The resulting array contains mapped versions of each element in the input array. var inputArray = [ 'apple' , 'banana' , 'pineapple' ]; var resultArray = []; for ( var i = 0 ; i < inputArray . length ; i ++){ resultArray . push ( inputArray [ i ] + 'man' ); } This would be equal to the following map statement: var inputArray = [ 'apple' , 'banana' , 'pineapple' ]; var resultArray = _ . map ( inputArray , function ( fruit ){ return fruit + 'man' ; }); Easy, ha?

That looks pretty good, right? Now, lets jump to reduce. A for loop almost never look clean. Searching with Array.prototype.some. Iterating over an array to search for an item is a pretty common task. With JavaScript, Array.prototype.forEach is often the popular choice. In some cases however, Array.prototype.some can be a better fit for the job if there is no need to search the entire array once a condition is fulfilled. There are at least three different ways to iterate over arrays and objects in JavaScript: for loops, array methods, listing property keys. If the iteration is being carried out to perform a search operation, it may lead to the following example: Without any guards and error checks, the code above is rather self-explanatory.

Now, since JavaScript Array has some powerful higher-order functions, one certainly can tweak the above code to look like this: Let us review what the specification says about Array.prototype.forEach (Section 15.4.4.18): callbackfn should be a function that accepts three arguments. forEach calls callbackfn once for each element present in the array, in ascending order.

JavaScript Callbacks are Pretty Okay - Andrew Kelley. I've seen a fair amount of callback bashing on Hacker News recently. Among the many proposed solutions, one of them strikes me as particularly clean: "asynchronous wait" or "wait and defer". iced-coffee-script had this a while ago. Kal just debuted with an identical solution, only differing in syntax. Supposedly LiveScript supports this with "backcalls". I must say, "asynchronous wait" or "monads" - whatever you want to call it - seems like an improvement over callbacks. I have 2 rules of thumb for code organization which makes clean callback based async code brainless: Avoid nontrivial anonymous functions. Example compile-to-js languages often show examples of deeply nested callback code to show how it can be refactored in the language. Yikes that does look a bit nested.

It's actually longer now, but it's much easier to parse. Here's another one taken from Kal (sorry to pick on you rzimmerman; you have good examples): Yep that is an eyesore. It gets worse. Conclusion. Best of Fluent 2012: Maintainable JavaScript.

JS Patterns

Scalable JavaScript Application Architecture. Cory Gross -- How To Create Your Own Chrome Extensions. I really like the Chrome browser. It wasn't until recently that I looked into creating extensions and was surprised by how simple it was. If you know basic HTML, CSS, JavaScript then you know all you need to be able to extend your Chrome browser in multitudes of ways. I decided to write up a simple guide explaining some of the basic ways you can easily extend Chrome. This is going to be a quick crash course to give you a general idea of what all you can easily do with Chrome extensions. Please let me know if you find any errors in the following. Getting Started With Extensions In order to get started creating a new extension all you need to do is create a new root directory for your extension. The Manifest Every extension must contain a file in the root directory with filename manifest.json.

Google has published a list of all the fields supported in manifest version 2.. Background Pages Most extensions will have an entry in the manfiest.json which looks like the following: Event Pages. Memory leak patterns in JavaScript. JavaScript is a powerful scripting language used to add dynamic content to Web pages. It is especially beneficial for everyday tasks such as password validation and creating dynamic menu components. While JavaScript is easy to learn and write, it is prone to memory leaks in certain browsers. In this introductory article we explain what causes memory leaks in JavaScript, demonstrate some of the common memory leak patterns to watch out for, and show you how to work around them. Note that the article assumes you are familiar with using JavaScript and DOM elements to develop Web applications. The article will be most useful to developers who use JavaScript for Web application development. Memory leaks in JavaScript JavaScript is a garbage collected language, meaning that memory is allocated to objects upon their creation and reclaimed by the browser when there are no more references to them.

What's wrong with circular references? Listing 1. Another memory leak pattern Listing 2. Back to top. A Programmer's Ride: How to properly write JavaScript libraries. I've seen JavaScript code written in all the possible ways. The reason there are so many ways to do it is because JavaScript is incredibly flexible. But that flexibility makes people write really ugly code. Examples of ugly, unreadable, error-prone code: (function(window, undefined) { var myLibrary = (function () { var someProp = "... Your JavaScript Library. Google Closure: How not to write JavaScript.

At the Edge of the Web conference in Perth last week I got to catch up with Dmitry Baranovskiy, the creator of the Raphaël and gRaphaël JavaScript libraries. Perhaps the most important thing these libraries do is make sophisticated vector graphics possible in Internet Explorer, where JavaScript performance is relatively poor. Dmitry, therefore, has little patience for poorly-written JavaScript like the code he found in Google’s just-released Closure Library. Having delivered a talk on how to write your own JavaScript library (detailed notes) at the conference, Dmitry shared his thoughts on the new library over breakfast the next morning.

“Just what the world needs—another sucky JavaScript library,” he said. When I asked him what made it ‘sucky’, he elaborated. “It’s a JavaScript library written by Java developers who clearly don’t get JavaScript.” “I’ll make you a deal,” I told him. The Slow Loop From array.js, line 63: for (var i = fromIndex; i < arr.length; i++) { return ! Return ! Dmitry Baranovskiy's talk on Your JavaScript Library • Passing Curiosity. There are my notes from Dmitry Baranovkiy’s session called Your JavaScript Library. Dmitry is a JavaScript developer at Atlassian, creator of Raphaël and gRaphaël JavaScript libraries. You can see the slides on slideshare. Introduction Unlike the server-side, you don’t have a choice on client-end development: you pretty much must use JavaScript. At Atlassian, they’ve got a number of products and have abstracted their own JavaScript library out of those code bases. Why should I write a library of my own? Everyone has snippets of JS they use on every project (trim, $=getElementById).

Roughly divided into: low level: taking care of nitty, gritty things like abstracting over DOM.high level:toolboxes:widgets: API & Functionality The API is more important than functionality. Spend 80% on API, 20% on functionality. Your library is the answer. Who is the target? A good API looks as simple as the functionality it provides. JavaScript is your friend. Performance Some tips: Animation Don’t trust setTimeout(). A JavaScript Library Template - Jeremy Kahn's Dev Blog.

I really like to write JavaScript libraries. This is because low-level programming interests me a lot. Although JavaScript is an inherently high-level language, I find writing the abstractions that “just work” like magic for others to be really fascinating. I’ve written a number of libraries of varying complexity, and I’ve developed a pretty good pattern that gives me a lot of flexibility when developing them. Building a library to scale is a much different challenge than building an application to scale, and it’s not discussed very much.

Libraries versus apps End users are the audience for applications. To achieve this, library code must be optimized for size and performance. Introducing lib-tmpl lib-tmpl is a small project that I wrote. Built to scale, built for sanity For a project of any size, structure is paramount. Another way to structure a library codebase is to divide it up into modules. “Best practices” “Best practices” is kind of a weird, nebulous concept. ‪write JavaScript library‬ - -Google. Creating your own JavaScript Library | One of the phases I went through while learning about JavaScript was the intense desire to write my own library, similar to jQuery (but massively scaled down). My library has gone through several major revisions — and more than one complete re-write, but now is exactly what I started out hoping it would be: functional, clean, small, and a solid learning experience.

I’d like to share what I learned from this project, and I hope you share back with me through the comments! Finished project demo Step 1: Identify the purpose of your library This might just be one of the toughest parts of the whole process! If you are to the point in your JavaScript knowledge that you would like to build your own library, than you’ve likely used jQuery, mooTools, Prototype, or any number of other popular libraries. I use jQuery extensively in my projects, and know that it is very capable in many aspects, including: animation, user input validation, AJAX loading/submitting, event handling, etc. Final thoughts. Build Your First JavaScript Library. Ever marvelled at the magic of Mootools? Ever wondered how Dojo does it? Ever been curious about jQuery's gymnastics? In this tutorial, we’re going to sneak behind the scenes and try our hand at building a super-simple version of your favorite library.

We use JavaScript libraries nearly every day. We’re wrapping the elements in an object because we want to be able to create methods for the object. In this tutorial, we’re going to take a (decidedly shallow) stab at building one of these libraries from scratch. This won’t be a completely full-featured library. One more thing: while we won’t be writing tests for this library, I did that when first developing this.

We’ll start with some wrapper code, which will contain our whole library. As you can see, we’re calling our library Dome, because it’s primarily a DOM library. We’ve got a couple of things going on here. Then, we have our dome object, which is our actual library object; as you can see, it’s returned at the end there. Toward Modern Web Apps with ECMAScript 6. ECMAScript, the official name for the language we all know as JavaScript, has enjoyed tremendous success over the last couple of years. With convergent standard support, performance boosts from modern JavaScript engines, as well as its foray into the server-side stack, ECMAScript has gained significant traction and redefined the scope of HTML5 applications.

The final requirement for world domination is the modernization of its syntax and run-time, which is coming in ECMAScript 6 and is the subject of this post. To understand the language progress within ECMAScript 6, first we need to understand how it is developed. The official ECMAScript specification, also known as ECMA-262, is defined by a standard body called Ecma International. The TC39 group within ECMA is responsible for formalizing the language specification (TC stands for Technical Committee). The ECMAScript 6 specification is still in the draft stage. “I Can See Clearly Now” The use of the second argument, y, can be confusing.