Pair program with me! profile for carousel at Stack Overflow, Q&A for professional and enthusiast programmers

2/28/2013

Rethinking about function objects in javascript

Traditional way of learning about functions in javascript is that we look at  them as objects with properties and methods.

So you can write:

// function declaration
function car(){
    // some code
};

// add properties to car function
car.color = function(color){
    return "This car color is: " + color;
};

car.color("blue")  // returns "This car color is blue"


Now you have static property of car function/object.

That is something you can't find in other popular languages. In other languages,  functions are usually treated as behaviour attached to some class or object.That way, they are just serving one purpose  in the kingdom of the nouns.


The role of functions ( as objects) in javascript is pretty non conventional and unusuall. Many developers are having trouble seeing them as objects.

But other then that ( which is considered strange and liberal ) , there is one more  definition which brings totally new way of thinking  about functions.
And that is where the real power of language lives.

They can be seen as behaviour that caries data instead of data that caries behavoiur. It is a very important concept that must be well understood.

Lets look at code:

// function declaration with nested func inside
function car(){
    var color = "blue"

    return function(){
        return "This car color is: " + color;
    };

};

// call

var color = car();

color() // returns "This car color is blue";



So we have exactly same result, but what is the difference ?  This time instead of assigning static properties to function object, we created closure with nested function. That closure behaves as object,  memorizing properties from the parent scope. You can put everything in closure - objects, functions. All kind of data. Now behaviour ( nested function ) carries data around from it's environment.


Happy coding.




2/26/2013

jQuery.fn.init constructor - this is where the fun begins

Below you can see a point of entrance into the jQuery API - fn.init constructor:

// jQuery.fn.init constructor

init:function ( selector, context, rootjQuery ) {
  var match, elem, ret, doc;

  // Handle $(""), $(null), $(undefined), $(false)
  if ( !selector ) {
   return this;
  }

  // Handle $(DOMElement)
  if ( selector.nodeType ) {
   this.context = this[0] = selector;
   this.length = 1;
   return this;
  }

  // Handle HTML strings
  if ( typeof selector === "string" ) {
   if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
    // Assume that strings that start and end with <> are HTML and skip the regex check
    match = [ null, selector, null ];

   } else {
    match = rquickExpr.exec( selector );
   }

   // Match html or make sure no context is specified for #id
   if ( match && (match[1] || !context) ) {

    // HANDLE: $(html) -> $(array)
    if ( match[1] ) {
     context = context instanceof jQuery ? context[0] : context;
     doc = ( context && context.nodeType ? context.ownerDocument || context : document );

     // scripts is true for back-compat
     selector = jQuery.parseHTML( match[1], doc, true );
     if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
      this.attr.call( selector, context, true );
     }

     return jQuery.merge( this, selector );

    // HANDLE: $(#id)
    } else {
     elem = document.getElementById( match[2] );

     // Check parentNode to catch when Blackberry 4.6 returns
     // nodes that are no longer in the document #6963
     if ( elem && elem.parentNode ) {
      // Handle the case where IE and Opera return items
      // by name instead of ID
      if ( elem.id !== match[2] ) {
       return rootjQuery.find( selector );
      }

      // Otherwise, we inject the element directly into the jQuery object
      this.length = 1;
      this[0] = elem;
     }

     this.context = document;
     this.selector = selector;
     return this;
    }

   // HANDLE: $(expr, $(...))
   } else if ( !context || context.jquery ) {
    return ( context || rootjQuery ).find( selector );

   // HANDLE: $(expr, context)
   // (which is just equivalent to: $(context).find(expr)
   } else {
    return this.constructor( context ).find( selector );
   }

  // HANDLE: $(function)
  // Shortcut for document ready
  } else if ( jQuery.isFunction( selector ) ) {
   return rootjQuery.ready( selector );
  }

  if ( selector.selector !== undefined ) {
   this.selector = selector.selector;
   this.context = selector.context;
  }

  return jQuery.makeArray( selector, this );
 }
 

 When you call $ function for example:

// call $ function with one argument ( html p element as a string ):

$("p")

You are calling a constructor that will return p element, wrapped in new jQuery object. That returned object is stored in prototype property of init constructor, so all instances will automatically inherit all properties and methods from it.

Main responsibilities of init constructor function are:
  1. to receive argument provided by API (application programming interface ) user ( usually developer )
  2. to handle response based on type of argument. - -for example handle arguments as variables (document.body ) or as strings ("div")
  3. to wrap argument into new jQuery object and return as array ( in javascript arrays are objects too )
  4. to provide subclass relationship and inheritance chain.

Last point is very confusing for many people. There is a question  why jQuery is using external ( static ) fn.init property to enable inheritance part ? If you look at code, you can notice that jQuery.prototype and jQuery.fn.init.prototype are referencinng same object. If you add some properties or methods to $.prototype object, it will be automatically added to all instances of init constructor.  So jQuery has two constructors nested. You can call main function  with keyword new, (new $("selector") or more commonly without keyword ($("selector")).

After that,  chosen element is ready for traversing, manipulation, effects and all other goodies provided by jQuery init prototype object  - which is a property of init constructor function.

It is just one part of jQuery story. Other part includes helper functions like Ajax, extend, each, data... They represent advanced part of library and they are usually called and connected with the rest of the code in jQuery implementation, but can be used as standalone methods.
Each method can be used to iterate over some custom collection ( object or array ), but it can be found as a part of lot of internal functions and methods.

Happy Coding.

2/24/2013

A closer look at operator precedence

Classic definition of order of precedence from the Wiki is, as follows:
In mathematics and computer programming, the order of operations (sometimes called operator precedence) is a rule used to clarify which procedures should be performed first in a given mathematical expression

You can find this and similar definitions in all beginner programming books, along with tables that shows it graphically.
Here is a one such table. I like it because it is compressed, and it shows all important operators in C, grouped by types related precedence. It is not so visually nice, but it will do the job. There are more detailed tables, specific to different languages (  for example here you can't find dot ( "." ) operator from the OOP paradigm ...), but I think that we  should first learn the basics:


() [] -> .
! ~ ++ -- + - * & sizeof
* / %
+ -
<< >>
< <= >= >
== !=
&
^
|
&&
||
?:
= += -= *= /= %= &= ^= |= <<= >>=
,

Closely related with precedence is associativity  - which describes how operators of the same precedence are grouped in the absence of parentheses. There is left or right associativity.


Now that you know the basics, there are some interesting things that can be learned by looking in this table.

For example why operator of assignment has a lowest priority ? And why in OOP paradigm operator dot ( "." ) has highest priority ?
That's because dot operator is potentially capable to give one of the highest level of abstraction to data, compared to all other operators. What does it mean ?

Well,  if we declare and define object in javascript like this:


// object literal
var obj = {};

You are actually providing opportunity to program to move further from basic  values which are building blocks of programs. As we know, all expression must be evaluated before usage. So if you have expression in classic math:
 5 +  10 * 20 
We know that we are talking about evaluation which leads to some result.

Same thing is happening in programming. All expressions needs to be evaluated to some basic values, in order to work with them. Lets see example in javacript:


//object literal with one property
var obj= {

    prop: "Hello Operators"

    }

If we want to access obj prop property, we'll have to use our dot (".") operator. Why ? Because prop is abstracted or moved away more from the language that computer understand.
So it needs to be evaluated to some basic ground, before it can be used.

I am talking here about built in data types in most popular  languages, which serves as a point of evaluation. On a deeper level, everything gets translated to binary, but that is not important for this topic.

What about assignment operator ( = ) ? Well, in table it has one of the lowest priority. Why is that ? Assignment is directly connected with memory in most imperative style programming languages. In fact, when you assign a value to some variable, using assignment operator, you are creating a memory address and a space for that varible on a machine level. That variable is carrying a value of some basic type. We can say that assignment operator is standing last in line, waiting all operations to be done, before it can assign a value to some name. If obj.prop appears somewhere else in a code for example:



// conditional statement that evaluates  property value
if ( obj.prop) {

    // do something

}




It will again be evaluated to it's actual value ( "Hello Operators" string ).

In this post I looked at two extreme positions in a table of operator precedence. By comparing their behaviour, we can see why they have different precedence, and also what is happening with all other operators. They  appear everywhere in language, and they are connective tissue of values. So it is important to be familiar with them more then it can be found in classic examples. Here I tried to fill some gaps, which were missing for me to completely understand them.

I hope it will help you also.

Happy Coding.







2/23/2013

Recursion with palindrome example

Today I found a great example of recursion function with palindrome word.  If you don't know what is palindrome, here is a wiki quote:
palindrome is a word, phrase, number, or other sequence of units that may be read the same way in either direction, with general allowances for adjustments to punctuation andword dividers.
Recursion function:


// recursive function declaration

function isPalindrome(text){ if (text.length <= 1) return true;
    if (text.charAt(0) != text.charAt(text.length -1)) return false;
    return isPalindrome(text.substr(1,text.length -2));
};

Now, if try to call recursive function with some palindrome, for example madam you'll get true, and madams will return false. Inner algorithm is fun and brain teasing.

2/22/2013

JSLint - javascript code-quality tool from terminal

If you wanna make art of your code, take a look at JSLint. It is a javascript code quality tool, created by Douglas Crockford - world famous js evangelist and author.

Here is a way how to download it with NPM ( node package manager ) and test your code:

In terminal type :
sudo npm install jslint -g

I suppose you know what is nodejs, and you that are using linux or mac.
If you are on windows take a look around, there is a guide somewhere, I am sure.
Next, create a js file, and put some code inside. I am sure that you'll be surprised with the result after testing.  Now move to that folder ( where the file is ) and type jslint name of file.js and learn from the results.

Update to post:

If you are using Vim with syntastic plugin, than JSLint which you installed globally ( with -g flag ) will check all your js script during coding in vim.

Happy Coding.

2/20/2013

What is a helper method ?

You probably heard about them, and use them but you didn't know that. Helper methods are usually  provided by the library. Underscore.js _.each function is widely used helper method throught many libraries.

Here's a nice definiton, from the classic perspective:

Helpers are one consequence of composed methods. If you are going to divide big methods into several smaller ones, you need those smaller methods. These are the helpers. Their purpose is to make larger-scale computations more readable by hiding temporarily irrelevant details and giving you a chance to express your intention through the name of the method. Helpers are typically declared private, moving to protected if the class is intended to be refined by subclassing.
 And example from Backbone.js library:

 
 
  function (attributes, options) {
    var defaults;
    var attrs = attributes || {};
    this.cid = _.uniqueId('c');
    this.attributes = {};
    if (options && options.collection) this.collection = options.collection;
    if (options && options.parse) attrs = this.parse(attrs, options) || {};
    if (defaults = _.result(this, 'defaults')) {
      attrs = _.defaults({}, attrs, defaults);
    }
    this.set(attrs, options);
    this.changed = {};
    this.initialize.apply(this, arguments);
  }
Above, you can see Backbone.Model method, which needs to be instantiated. Model is full of properties, but it is not ment to serve as constructor. For that purpose we use Backbone.Model.extend method, which simply helps establishing inheritance and providing bridge between Model and instance:
function (protoProps, staticProps) {
    var parent = this;
    var child;

    // The constructor function for the new subclass is either defined by you
    // (the "constructor" property in your `extend` definition), or defaulted
    // by us to simply call the parent's constructor.
    if (protoProps && _.has(protoProps, 'constructor')) {
      child = protoProps.constructor;
    } else {
      child = function(){ return parent.apply(this, arguments); };
    }

    // Add static properties to the constructor function, if supplied.
    _.extend(child, parent, staticProps);

    // Set the prototype chain to inherit from `parent`, without calling
    // `parent`'s constructor function.
    var Surrogate = function(){ this.constructor = child; };
    Surrogate.prototype = parent.prototype;
    child.prototype = new Surrogate;

    // Add prototype properties (instance properties) to the subclass,
    // if supplied.
    if (protoProps) _.extend(child.prototype, protoProps);

    // Set a convenience property in case the parent's prototype is needed
    // later.
    child.__super__ = parent.prototype;

    return child;
  }

It is possible to keep together Model and extend. It is not good design approach, cause we will sacrifice modular approach (among others pitfalls). Choosing to separate main method on two loose coupled parts, we are making extend methond reusable to other parts of our code. As you can see, Backbone authors did exactly that - you can extend Model,View,Router,History and Collection with one helper function.

Happy Coding

2/19/2013

Recursion demystified

Recursion is one of the main programming construct, that is very powerfull but sometimes it is not easy to understand.
I found one great example of recursive call:


// self invoking recursive function

(function foo(i) {
    if (i === 3) {
        return;
    }
    else {
        foo(++i);
    };
    console.log(i);
}(0));

Copy and paste it in chrome dev tools or in js interpreted environment. As  you can see it's not fibonacci, which is often used. This example is more straight-forward and simpler.

The output is 3,2,1.  It shows the way recursion works.
In short here is what is happening  - the inner function keeps calling outer function untill it reaches base case.
What is base case ? It is a number of calls which must be provided, usually expressed like a condition. If there is no base case, infinite loop will happen, which is not what we want. Since inner and outer function are same, we have a situation in which a function calls ifself. Foo inside will keep calling itself with provided arguments until it reaches base case.
And now important part: do you wonder why the output is inverted ? What don't we have 1,2,3 instead of 3,2,1 ?
That's because inner foo function is keeping results of calculation ( incrementing i ) somewhere in memory , but it can't provide output since it is called over and over again untill it reaches base case. That memory is called recursive stack, and it is a form of data structure, in which last data entrance is removed of called first. So when inner foo finally reaches base case, it is ready to "unwound" memory stack from the last to the first result giving 3,2,1 output.

Recursion is widely used in functional programming paradigm and it is considered for alternative to iteration. 

2/18/2013

Underscore js rocks

Hello World;

It's time for enlightnement.
Let me introduce you Underscore.js. It's a  small js library that provides lot of functional programming features, which is missing in native js implementations.

How to install it? Very simply - just copy file from this page
http://underscorejs.org/

or from git:
https://github.com/documentcloud/underscore

Put a file in you project folder, link to  it from the main page. In my case it looks like this:


// link to your underscore file



Now you should have new global js object named Backbone. Test it in chrome dev.tools:


// examine Backbone object

    dir(Backbone);

And finally lets see underscore in action (btw shorthand for library is_" ) with one example:

   Range function:


// assign the result to variable range

    var range = _.range(5,10,2)

// log in developer tools

    console.log(range);

         Output is [5,7,9]

Guess what is happening ?
Hint: pay attention to third paramater.

Underscorejs if full of utility functions that you can find in languages like Python of PHP. It is bringing more power and flexibility to Javascript and to your projects in general.
Also, it is a important part of jQuery and Backbone.
Feel free to experiment, it is fun with this great library.

Happy Coding.

2/16/2013

more vim tips & tricks

These days I'm digging deeper into wonderfull world of our favourite editor .
So here's what I discover:

Nerd commenter plugin

commands:
    - ,cc  comment a line of selected text
    - ,ca change comment style ( nerd will recognize language )
    - ,ci toggle comment
 
There is more ofcourse. Very helpfull plugin for production.
Here is a link for downloads.

http://www.vim.org/scripts/script.php?script_id=1218

Easy motion

basic commands:
    - ,,w mark a text so you can easily skip whereever you want
    - ,,k mark  backword

  http://www.vim.org/scripts/script.php?script_id=3526

Happy coding