JavaScript – The Good Parts

I started to play around with the programming language Dart today so I figure would start putting together a guide on the finer points of JavaScript.

Closures

In a nutshell closures are functions with embedded other functions.   There are plenty of potential uses for closures but one common role is acting like a private variables.  Here is a basic structure of a closure to see how this works.

// This counter function was based of an example by Alex Russell from his Learning to Love JavaScript 2011 Google I/O presentation.
function counter() {
var count = 0; // count - Variable to store the current count

return function() { // The counter function returns a new function
console.log(++count) // Post-increments the hidden count variable and sends the count to console.log
} }

Read anything by Michael Bolin or on closure tools if you want learn about working with closures.

Duck Typing

If it quacks like a duck its probably a duck.  Similar as in Python, everything in JavaScript is an object.  If an passed in object looks like a string of characters then object will be viewed as a string.  Over at Paul Irish blog has great article on using duck typing in jQuery called Duck Punching.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s