Archive | Uncategorized RSS feed for this section

Javascript Gurus to follow

10 Jun

As JavaScript developers, we have quite crazy requirements. The playing field is in a state of constant flux and one of the best ways to keep up is interacting with other developers and reading their code. Blogs, such as the one you’re reading are a perfect amalgamation of these two activities.

Today, I’d like to bring your attention to a number of blogs written by pretty well versed developers, focusing on JavaScript development, that you owe yourselves to bookmark.

  • Find his musings on JavaScript at his blog.
  • Inventor of the JavaScript language.
  • Remember to check out his podcast, as well.
  • Tweets at @BrendanEich
  • Find his musings on JavaScript at his blog.
  • Creator of the JS1K competition
  • Tweets at @kuvos
  • Find his musings on JavaScript at his blog.
  • Contributor to the jQuery and Modernizr projects.
  • Creator of so many jQuery plugins that we’re ethically obligated to use the word buttload.
  • Tweets at @cowboy

All about this keyword in javascript

31 Jul

Conceptual Overview of this
When a function is created, a keyword called this is created (behind the scenes), which links to the object in which the function operates. Said another way, this is available to the scope of its function, yet is a reference to the object of which that function is a property/method.
Let’s take a look at this object:

var cody = {
living:true,
age:23,
gender:’male’,
getGender:function(){return cody.gender;}
};

console.log(cody.getGender()); // logs ‘male’

Notice how inside of the getGender function, we are accessing the gender property using dot notation (e.g cody.gender) on the cody object itself. This can be rewritten using this to access the cody object because this points to the cody object.

var cody = {
living:true,
age:23,
gender:’male’,
getGender:function(){return this.gender;}
};

console.log(cody.getGender()); // logs ‘male’

The this used in this.gender simply refers to the cody object on which the function is
operating.
The topic of this can be confusing, but it does not have to be. Just remember that, in general, this is used inside of functions to refer to the object the function is contained within, as opposed to the function itself (exceptions include using the new keyword or call() and apply()).
Important Notes
The keyword this looks and acts like any other variable, except you can’t modify it.
– As opposed to arguments and any parameters sent to the function, this is a keyword (not a property) in the call/activation object.
How is the Value of this Determined?
The value of this, passed to all functions, is based on the context in which the function is called at runtime. Pay attention here, because this is one of those quirks you just need to memorize.
The myObject object in the code below is given a property called sayFoo, which points to the sayFoo function. When the sayFoo function is called from the global scope, this refers to the window object. When it is called as a method of myObject, this refers to myObject.
Since myObject has a property named foo, that property is used.

var foo = ‘foo’;
var myObject = {foo: ‘I am myObject.foo’};

var sayFoo = function() {
console.log(this[‘foo’]);
};

// give myObject a sayFoo property and have it point to sayFoo function
myObject.sayFoo = sayFoo;
myObject.sayFoo(); // logs ‘I am myObject.foo’ 12

sayFoo(); // logs ‘foo’

Clearly, the value of this is based on the context in which the function is being called. Consider that both myObject.sayFoo and sayFoo point to the same function. However, depending upon where (i.e. the context) sayFoo() is called from, the value of this is different.
If it helps, here is the same code with the head object (i.e window) explicitly used.

window.foo = ‘foo’;
window.myObject = {foo: ‘I am myObject.foo’};
window.sayFoo = function() { ! console.log(this.foo); };
window.myObject.sayFoo = window.sayFoo;
window.myObject.sayFoo();
window.sayFoo();

Make sure that as you pass around functions, or have multiple references to a function, you realize that the value of this will change depending upon the context in which you call the function.
Important Note
All variables except this and arguments follow lexical scope.
The this Keyword Refers to the Head Object in Nested Functions
You might be wondering what happens to this when it is used inside of a function that is contained inside of another function. The bad news is in ECMA 3, this loses its way and refers to the head object (window object in browsers), instead of the object within which the function is defined.

In the code below, this inside of func2 and func3 loses its way and refers not to myObject but instead to the head object.

var myObject = {
func1:function() {
console.log(this); //logs myObject
varfunc2=function() {
console.log(this); //logs window, and will do so from this point on
varfunc3=function() {
console.log(this); //logs window, as it’s the head object
}();
}();
}
};

myObject.func1();

The good news is that this will be fixed in ECMAScript 5. For now, you should be aware of this predicament, especially when you start passing functions around as values to other functions.
Consider the code below and what happens when passing an anonymous function to foo.func1. When the anonymous function is called inside of foo.func1 (a function inside of a function) the this value inside of the anonymous function will be a reference to the head object.

var foo = {
func1:function(bar){
bar(); //logs window, not foo
console.log(this);//the this keyword here will be a reference to foo object
}
};

foo.func1(function(){console.log(this)});

Now you will never forget: the this value will always be a reference to the head object when its host function is encapsulated inside of another function or invoked within the context of another function (again, this is fixed in ECMAScript 5).
Working Around the Nested Function Issue
So that the this value does not get lost, you can simply use the scope chain to keep a reference to this in the parent function. The code below demonstrates how, using a variable called that, and leveraging its scope, we can keep better track of function context.

var myObject = {
myProperty:’Icanseethelight’,
myMethod:function() {
var that=this; //store a reference to this (i.e.myObject) in myMethod scope varhelperFunctionfunction(){//childfunction
var helperFunction function() { //childfunction
//logs ‘I can see the light’ via scope chain because that=this
console.log(that.myProperty); //logs ‘I can see the light’
console.log(this); // logs window object, if we don’t use “that”
}();
}
}

myObject.myMethod(); // invoke myMethod

Controlling the Value of this
The value of this is normally determined from the context in which a function is called (except when the new keyword is used – more about that in a minute), but you can overwrite/control the value of this using apply() or call() to define what object this points to when invoking a function. Using these methods is like saying: “Hey, call X function but tell the function to use Z object as the value for this.” By doing so, the default way in which JavaScript determines the value of this is overridden.

Below, we create an object and a function. We then invoke the function via call() so that the value of this inside the function uses myObject as its context. The statements inside the myFunction function will then populate myObject with properties instead of populating the head object. We have altered the object to which this (inside of myFunction) refers.

var myObject = {};

var myFunction = function(param1, param2) {
//setviacall()’this’points to my Object when function is invoked
this.foo = param1;
this.bar = param2;
console.log(this); //logs Object{foo = ‘foo’, bar = ‘bar’}
};

myFunction.call(myObject, ‘foo’, ‘bar’); // invoke function, set this value to myObject

console.log(myObject) // logs Object {foo = ‘foo’, bar = ‘bar’}

In the example above, we are using call(), but apply() could be used as well. The difference between the two is how the parameters for the function are passed. Using call(), the parameters are just comma separated values. Using apply(), the parameter values are passed inside of an array. Below, is the same idea, but using apply().

var myObject = {};

var myFunction = function(param1, param2) {
//set via apply(), this points to my Object when function is invoked
this.foo=param1;
this.bar=param2;
console.log(this); // logs Object{foo=’foo’, bar=’bar’}
};

myFunction.apply(myObject, [‘foo’, ‘bar’]); // invoke function, set this value
console.log(myObject); // logs Object {foo = ‘foo’, bar = ‘bar’}

What you need to take away here is that you can override the default way in which JavaScript determines the value of this in a function’s scope.
Using the this Keyword Inside a User-Defined Constructor Function
When a function is invoked with the new keyword, the value of this — as it’s stated in the constructor — refers to the instance itself. Said another way: in the constructor function, we can leverage the object via this before the object is actually created. In this case, the default value of this changes in a way not unlike using call() or apply().
Below, we set up a Person constructor function that uses this to reference an object being created. When an instance of Person is created, this.name will reference the newly created object and place a property called name in the new object with a value from the parameter (name) passed to the constructor function.

var Person = function(name) {
this.name = name || ‘johndoe’; // this will refer to the instanc ecreated
}

var cody = new Person(‘Cody Lindley’); // create an instance, based on Person constructor

console.log(cody.name); // logs ‘Cody Lindley’

Again, this refers to the “object that is to be” when the constructor function is invoked using the new keyword. Had we not used the new keyword, the value of this would be the context in which Person is invoked — in this case the head object. Let’s examine this scenario.

var Person = function(name) {
this.name=name||’johndoe’;
}

var cody = Person(‘Cody Lindley’); // notice we did not use ‘new’
console.log(cody.name); // undefined, the value is actually set at window.name
console.log(window.name); // logs ‘Cody Lindley’

The Keyword this Inside a Prototype Method Refers to a Constructor instance
When used in functions added to a constructor’s prototype property, this refers to the instance on which the method is invoked. Say we have a custom Person() constructor function. As a parameter, it requires the person’s full name. In case we need to access the full name of the person, we add a whatIsMyFullName method to the Person.prototype, so that all Person instances inherit the method. When using this, the method can refer to the instance invoking it (and thus its properties).
Here I demonstrate the creation of two Person objects (cody and lisa) and the inherited whatIsMyFullName method that contains the this keyword to access the instance.

var Person = function(x){
if(x){this.fullName = x};
};

Person.prototype.whatIsMyFullName = function() {
return this.fullName; // ‘this’ refers to the instance created from Person()
}

var cody = new Person(‘cody lindley’);
var lisa = new Person(‘lisa lindley’);

// call the inherited whatIsMyFullName method, which uses this to refer to the instance
console.log(cody.whatIsMyFullName(), lisa.whatIsMyFullName());

/* The prototype chain is still in effect, so if the instance does not have a
fullName property, it will look for it in the prototype chain.
Below, we add a fullName property to both the Person prototype and the Object
prototype. See notes. */

Object.prototype.fullName = ‘John Doe’;
var john = new Person(); // no argument is passed so fullName is not added to instance
console.log(john.whatIsMyFullName()); // logs ‘John Doe’

The take away here is that the keyword this is used to refer to instances when used inside of a method contained in the prototype object. If the instance does not contain the property, the prototype lookup begins.
Notes
– If the instance or the object pointed to by this does not contain the property being referenced, the same rules that apply to any property lookup get applied and the property will be “looked up” on the prototype chain. So in our example, if the fullName property was not contained within our instance then fullName would be looked for at Person.prototype.fullName then Object.prototype.fullName.

Best Javascript Practice to Follow

11 Oct

Keep it short, stupid!

You have read this a zillion times already. As a programmer/webmaster you might have applied this tip multiple times too but never forget this in case of JavaScript.

  • Use comments and white spaces while in development mode to keep your code readable.
  • Remove white spaces and comments before publishing your scripts in live environment. Also, try to shorten your variable and function names.
  • Consider using third party tools to compress your JavaScript code before publishing the same.

Think before you touch object prototypes

Appending new properties to object prototypes is one of the most common reasons for script failures.

yourObject.prototype.anotherFunction = ‘Hello’;
yourObject.prototype.anotherMethod = function () { … };

In above case all variables will be affected as they are inherited from “yourObject”. Such usage might cause unexpected behaviour. Henceforth, it is suggested to delete such modifications right after its usage:

yourObject.prototype.anotherFunction = ‘Hello’;
yourObject.prototype.anotherMethod = function () { … };
test.anotherMethod();
delete yourObject.prototype.anotherFunction = ‘Hello’;
delete yourObject.prototype.anotherMethod = function () { … };

Debug JavaScript Code

Even the best programmers make mistakes. To limit them, run your JavaScript code through a JavaScript debugger to make sure that you haven’t made any silly blunders that can easily be prevented.

Avoid Eval

Your JavaScript can work well without the use of “eval” function. For those not aware, “eval” gives access to JavaScript compiler. If a string is passed as parameter of “eval” then its result can be executed.

This will degrade your code’s performance though it acts as a boon during development phase. Avoid “eval” in live environment.

Minimize DOM access

DOM is one of the most complex APIs that slows down the code execution process. At times the webpage might not load or it might load incompletely. Better to avoid DOM.

Learn JavaScript before using JavaScript libraries

Internet is chock full of JavaScript libraries that perform various functions. Programmers end up using JavaScript libraries without understanding the side effects of the same. It is strongly advisable to learn the basics of JavaScript before using third party JavaScript libraries; otherwise, be prepared for disastrous results.

Never use “SetTimeOut” and “SetInterval” as alternatives to “Eval”

setTimeOut( “document.getID(‘value’)”, 3000);

In above code document.getID(‘value’) is used as a string that is processed within the “setTimeOut” function. This is similar to “eval” function which executes a string during every execution of code thus degrading performance. Henceforth, it is suggested to pass a function within such functions:

setTimeOut(yourFunction, 3000);

[] is better than “new Array();”

“A common error in JavaScript programs is to use an object when an array is required or an array when an object is required. The rule is simple: when the property names are small sequential integers, you should use an array. Otherwise, use an object.” – Douglas Crockford, writer of JavaScript: Good Parts.

Suggested:

var a = [‘1A’,’2B’];

Avoid:

var a = new Array();
a[0] =  “1A”;
a[1] = “2B”;

Never use “var” multiple times

While initializing every variable programmers tend to use “var” keyword. Instead, it is suggested that you use commas to avoid redundancy of keywords and reduce code size:

var variableOne = ‘string 1’,
variableTwo = ‘string 2’,
variableThree = ‘string 3’;

Never Miss Semicolons

This is one of the programming bugs that can consume hours of debugging. Personally, I have spent hours looking for problems in my code when the reason was the missing semicolon

Introduction to Javascript and Javascript Scope and Inheritance

27 Jun

http://www.youtube.com/watch?v=ljNi8nS5TtQ&feature=relmfu

Plain English explanation of Big O

18 Jun

I came across this in stackoverflow and thought it was wonderful to share…
The simplest definition I can give for Big-O notation is this:

Big-O notation is a relative representation of the complexity of an algorithm.

There are some important and deliberately chosen words in that sentence:

relative: you can only compare apples to apples. You can’t compare an algorithm to do arithmetic multiplication to an algorithm that sorts a list of integers. But two algorithms that do arithmetic operations (one multiplication, one addition) will tell you something meaningful;
representation: Big-O (in its simplest form) reduces the comparison between algorithms to a single variable. That variable is chosen based on observations or assumptions. For example, sorting algorithms are typically compared based on comparison operations (comparing two nodes to determine their relative ordering). This assumes that comparison is expensive. But what if comparison is cheap but swapping is expensive? It changes the comparison; and
complexity: if it takes me one second to sort 10,000 elements how long will it take me to sort one million? Complexity in this instance is a relative measure to something else.

Come back and reread the above when you’ve read the rest.

The best example of Big-O I can think of is doing arithmetic. Take two numbers (123456 and 789012). The basic arithmetic operations we learnt in school were:

addition;
subtraction;
multiplication; and
division.

Each of these is an operation or a problem. A method of solving these is called an algorithm.

Addition is the simplest. You line the numbers up (to the right) and add the digits in a column writing the last number of that addition in the result. The ‘tens’ part of that number is carried over to the next column.

Let’s assume that the addition of these numbers is the most expensive operation in this algorithm. It stands to reason that to add these two numbers together we have to add together 6 digits (and possibly carry a 7th). If we add two 100 digit numbers together we have to do 100 additions. If we add two 10,000 digit numbers we have to do 10,000 additions.

See the pattern? The complexity (being the number of operations) is directly proportional to the number of digits n in the larger number. We call this O(n) or linear complexity.

Subtraction is similar (except you may need to borrow instead of carry).

Multiplication is different. You line the numbers up, take the first digit in the bottom number and multiply it in turn against each digit in the top number and so on through each digit. So to multiply our two 6 digit numbers we must do 36 multiplications. We may need to do as many as 10 or 11 column adds to get the end result too.

If we have two 100-digit numbers we need to do 10,000 multiplications and 200 adds. For two one million digit numbers we need to do one trillion (1012) multiplications and two million adds.

As the algorithm scales with n-squared, this is O(n2) or quadratic complexity. This is a good time to introduce another important concept:

We only care about the most significant portion of complexity.

The astute may have realized that we could express the number of operations as: n2 + 2n. But as you saw from our example with two numbers of a million digits apiece, the second term (2n) becomes insignificant (accounting for 0.00002% of the total operations by that stage).

The Telephone Book

The next best example I can think of is the telephone book, normally called the White Pages or similar but it’ll vary from country to country. But I’m talking about the one that lists people by surname and then initials or first name, possibly address and then telephone numbers.

Now if you were instructing a computer to look up the phone number for “John Smith”, what would you do? Ignoring the fact that you could guess how far in the S’s started (let’s assume you can’t), what would you do?

A typical implementation might be to open up to the middle, take the 500,000th and compare it to “Smith”. If it happens to be “Smith, John”, we just got real lucky. Far more likely is that “John Smith” will be before or after that name. If it’s after we then divide the last half of the phone book in half and repeat. If it’s before then we divide the first half of the phone book in half and repeat. And so on.

This is called a binary search and is used every day in programming whether you realize it or not.

So if you want to find a name in a phone book of a million names you can actually find any name by doing this at most 21 or so times (I might be off by 1). In comparing search algorithms we decide that this comparison is our ‘n’.

For a phone book of 3 names it takes 2 comparisons (at most).
For 7 it takes at most 3.
For 15 it takes 4.

For 1,000,000 it takes 21 or so.

That is staggeringly good isn’t it?

In Big-O terms this is O(log n) or logarithmic complexity. Now the logarithm in question could be ln (base e), log10, log2 or some other base. It doesn’t matter it’s still O(log n) just like O(2n2) and O(100n2) are still both O(n2).

It’s worthwhile at this point to explain that Big O can be used to determine three cases with an algorithm:

Best Case: In the telephone book search, the best case is that we find the name in one comparison. This is O(1) or constant complexity;
Expected Case: As discussed above this is O(log n); and
Worst Case: This is also O(log n).

Normally we don’t care about the best case. We’re interested in the expected and worst case. Sometimes one or the other of these will be more important.

Back to the telephone book.

What if you have a phone number and want to find a name? The police have a reverse phone book but such lookups are denied to the general public. Or are they? Technically you can reverse lookup a number in an ordinary phone book. How?

You start at the first name and compare the number. If it’s a match, great, if not, you move on to the next. You have to do it this way because the phone book is unordered (by phone number anyway).

So to find a name:

Best Case: O(1);
Expected Case: O(n) (for 500,000); and
Worst Case: O(n) (for 1,000,000).

The Travelling Salesman

This is quite a famous problem in computer science and deserves a mention. In this problem you have N towns. Each of those towns is linked to 1 or more other towns by a road of a certain distance. The Travelling Salesman problem is to find the shortest tour that visits every town.

Sounds simple? Think again.

If you have 3 towns A, B and C with roads between all pairs then you could go:

A -> B -> C
A -> C -> B
B -> C -> A
B -> A -> C
C -> A -> B
C -> B -> A

Well actually there’s less than that because some of these are equivalent (A -> B -> C and C -> B -> A are equivalent, for example, because they use the same roads, just in reverse).

In actuality there are 3 possibilities.

Take this to 4 towns and you have (iirc) 12 possibilities. With 5 it’s 60. 6 becomes 360.

This is a function of a mathematical operation called a factorial. Basically:

5! = 5 * 4 * 3 * 2 * 1 = 120
6! = 6 * 5 * 4 * 3 * 2 * 1 = 720
7! = 7 * 6 * 5 * 4 * 3 * 2 * 1 = 5040

25! = 25 * 24 * … * 2 * 1 = 15,511,210,043,330,985,984,000,000

50! = 50 * 49 * … * 2 * 1 = 3.04140932… × 10^64

So the Big-O of the Travelling Salesman problem is O(n!) or factorial or combinatorial complexity.

By the time you get to 200 towns there isn’t enough time left in the universe to solve the problem with traditional computers.

Something to think about.

Polynomial Time

Another point I wanted to make quick mention of is that any algorithm that has a complexity of O(na) is said to have polynomial complexity or is solvable in polynomial time.

Traditional computers can solve polynomial-time problems. Certain things are used in the world because of this. Public Key Cryptography is a prime example. It is computationally hard to find two prime factors of a very large number. If it wasn’t, we couldn’t use the public key systems we use.

Anyway, that’s it for my (hopefully plain English) explanation of Big O (revised).