Javascript 45 best tips and tricks

17 Jul

In this article, I’ll share a set of JavaScript tips, tricks and best practices that should be known by all JavaScript developers regardless of their browser/engine or the SSJS (Server Side JavaScript) interpreter.

Note that the code snippets in this article have been tested in the latest Google Chrome version 30, which uses the V8 JavaScript Engine (V8 3.20.17.15).

1 – Don’t forget var keyword when assigning a variable’s value for the first time.

Assignment to an undeclared variable automatically results in a global variable being created. Avoid global variables.

2 – use === instead of ==

The == (or !=) operator performs an automatic type conversion if needed. The === (or !==) operator will not perform any conversion. It compares the value and the type, which could be considered faster than ==.

[10] === 10 // is false
[10] == 10 // is true
'10' == 10 // is true
'10' === 10 // is false
[] == 0 // is true
[] === 0 // is false
'' == false // is true but true == "a" is false
'' === false // is false

3 – undefined, null, 0, false, NaN, ” (empty string) are all falsy.

4 – Use Semicolons for line termination

The use of semi-colons for line termination is a good practice. You won’t be warned if you forget it, because in most cases it will be inserted by the JavaScript parser. For more details about why you should use semi-colons, take a look to this artice: http://davidwalsh.name/javascript-semicolons.

5 – Create an object constructor

function Person(firstName, lastName){
this.firstName = firstName;
this.lastName = lastName;
}

var Saad = new Person("Saad", "Mousliki");

6 – Be careful when using typeof, instanceof and constructor.

typeof : a JavaScript unary operator used to return a string that represents the primitive type of a variable, don’t forget that typeof null will return “object”, and for the majority of object types (Array, Date, and others) will return also “object”.
constructor : is a property of the internal prototype property, which could be overridden by code.
instanceof : is another JavaScript operator that check in all the prototypes chain the constructor it returns true if it’s found and false if not.

var arr = ["a", "b", "c"];
typeof arr; // return "object"
arr instanceof Array // true
arr.constructor(); //[]

7 – Create a Self-calling Function

This is often called a Self-Invoked Anonymous Function or Immediately Invoked Function Expression (IIFE). It is a function that executes automatically when you create it, and has the following form:

(function(){
// some private code that will be executed automatically
})();
(function(a,b){
var result = a+b;
return result;
})(10,20)

8 – Get a random item from an array

var items = [12, 548 , 'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' , 2145 , 119];

var randomItem = items[Math.floor(Math.random() * items.length)];

9 – Get a random number in a specific range

This code snippet can be useful when trying to generate fake data for testing purposes, such as a salary between min and max.

var x = Math.floor(Math.random() * (max - min + 1)) + min;

10 – Generate an array of numbers with numbers from 0 to max

var numbersArray = [] , max = 100;

for( var i=1; numbersArray.push(i++) < max;); // numbers = [1,2,3 ... 100]

11 – Generate a random set of alphanumeric characters

function generateRandomAlphaNum(len) {
var rdmString = "";
for( ; rdmString.length < len; rdmString += Math.random().toString(36).substr(2));
return rdmString.substr(0, len);

}

12 – Shuffle an array of numbers

var numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];
numbers = numbers.sort(function(){ return Math.random() - 0.5});
/* the array numbers will be equal for example to [120, 5, 228, -215, 400, 458, -85411, 122205] */

A better option could be to implement a random sort order by code (e.g. : Fisher-Yates shuffle), than using the native sort JavaScript function. For more details take a look to this discussion.

13 – A string trim function

The classic trim function of Java, C#, PHP and many other language that remove whitespace from a string doesn’t exist in JavaScript, so we could add it to the String object.

String.prototype.trim = function(){return this.replace(/^s+|s+$/g, "");};

A native implementation of the trim() function is available in the recent JavaScript engines.

14 – Append an array to another array

var array1 = [12 , "foo" , {name "Joe"} , -2458];

var array2 = ["Doe" , 555 , 100];
Array.prototype.push.apply(array1, array2);
/* array1 will be equal to [12 , "foo" , {name "Joe"} , -2458 , "Doe" , 555 , 100] */

15 – Transform the arguments object into an array

var argArray = Array.prototype.slice.call(arguments);

16 – Verify that a given argument is a number

function isNumber(n){
return !isNaN(parseFloat(n)) && isFinite(n);
}

17 – Verify that a given argument is an array

function isArray(obj){
return Object.prototype.toString.call(obj) === '[object Array]' ;
}

Note that if the toString() method is overridden, you will not get the expected result using this trick.

Or use…

Array.isArray(obj); // its a new Array method

You could also use instanceof if you are not working with multiple frames. However, if you have many contexts, you will get a wrong result.

var myFrame = document.createElement('iframe');
document.body.appendChild(myFrame);

var myArray = window.frames[window.frames.length-1].Array;
var arr = new myArray(a,b,10); // [a,b,10]

// instanceof will not work correctly, myArray loses his constructor
// constructor is not shared between frames
arr instanceof Array; // false

18 – Get the max or the min in an array of numbers

var numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];
var maxInNumbers = Math.max.apply(Math, numbers);
var minInNumbers = Math.min.apply(Math, numbers);

19 – Empty an array

var myArray = [12 , 222 , 1000 ];
myArray.length = 0; // myArray will be equal to [].

20 – Don’t use delete to remove an item from array

Use splice instead of using delete to delete an item from an array. Using delete replaces the item with undefined instead of the removing it from the array.

Instead of…

var items = [12, 548 ,'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' ,2154 , 119 ];
items.length; // return 11
delete items[3]; // return true
items.length; // return 11
/* items will be equal to [12, 548, "a", undefined × 1, 5478, "foo", 8852, undefined × 1, "Doe", 2154, 119] */

Use…

var items = [12, 548 ,'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' ,2154 , 119 ];
items.length; // return 11
items.splice(3,1) ;
items.length; // return 10
/* items will be equal to [12, 548, "a", 5478, "foo", 8852, undefined × 1, "Doe", 2154, 119] */

The delete method should be used to delete an object property.

21 – Truncate an array using length

Like the previous example of emptying an array, we truncate it using the length property.

var myArray = [12 , 222 , 1000 , 124 , 98 , 10 ];
myArray.length = 4; // myArray will be equal to [12 , 222 , 1000 , 124].

As a bonus, if you set the array length to a higher value, the length will be changed and new items will be added with undefined as a value. The array length is not a read only property.

myArray.length = 10; // the new array length is 10
myArray[myArray.length - 1] ; // undefined

22 – Use logical AND/ OR for conditions

var foo = 10;
foo == 10 && doSomething(); // is the same thing as if (foo == 10) doSomething();
foo == 5 || doSomething(); // is the same thing as if (foo != 5) doSomething();

The logical OR could also be used to set a default value for function argument.

function doSomething(arg1){
arg1 = arg1 || 10; // arg1 will have 10 as a default value if it’s not already set
}

23 – Use the map() function method to loop through an array’s items

var squares = [1,2,3,4].map(function (val) {
return val * val;
});
// squares will be equal to [1, 4, 9, 16]

24 – Rounding number to N decimal place

var num =2.443242342;
num = num.toFixed(4); // num will be equal to 2.4432

NOTE : the toFixed() function returns a string and not a number.

25 – Floating point problems

0.1 + 0.2 === 0.3 // is false
9007199254740992 + 1 // is equal to 9007199254740992
9007199254740992 + 2 // is equal to 9007199254740994

Why does this happen? 0.1 +0.2 is equal to 0.30000000000000004. What you need to know is that all JavaScript numbers are floating points represented internally in 64 bit binary according to the IEEE 754 standard. For more explanation, take a look to this blog post.

You can use toFixed() and toPrecision() to resolve this problem.

26 – Check the properties of an object when using a for-in loop

This code snippet could be useful in order to avoid iterating through the properties from the object’s prototype.

for (var name in object) {
if (object.hasOwnProperty(name)) {
// do something with name
}
}

27 – Comma operator

var a = 0;
var b = ( a++, 99 );
console.log(a); // a will be equal to 1
console.log(b); // b is equal to 99

28 – Cache variables that need calculation or querying

In the case of a jQuery selector, we could cache the DOM element.

var navright = document.querySelector('#right');
var navleft = document.querySelector('#left');
var navup = document.querySelector('#up');
var navdown = document.querySelector('#down');

29 – Verify the argument before passing it to isFinite()

isFinite(0/0) ; // false
isFinite("foo"); // false
isFinite("10"); // true
isFinite(10); // true
isFinite(undefined); // false
isFinite(); // false
isFinite(null); // true !!!

30 – Avoid negative indexes in arrays

var numbersArray = [1,2,3,4,5];
var from = numbersArray.indexOf("foo") ; // from is equal to -1
numbersArray.splice(from,2); // will return [5]

Make sure that the arguments passed to splice are not negative.

31 – Serialization and deserialization (working with JSON)

var person = {name :'Saad', age : 26, department : {ID : 15, name : "R&D"} };
var stringFromPerson = JSON.stringify(person);
/* stringFromPerson is equal to "{"name":"Saad","age":26,"department":{"ID":15,"name":"R&D"}}" */
var personFromString = JSON.parse(stringFromPerson);
/* personFromString is equal to person object */

32 – Avoid the use of eval() or the Function constructor

Use of eval or the Function constructor are expensive operations as each time they are called script engine must convert source code to executable code.

var func1 = new Function(functionCode);
var func2 = eval(functionCode);

33 – Avoid using with() (The good part)

Using with() inserts a variable at the global scope. Thus, if another variable has the same name it could cause confusion and overwrite the value.

34 – Avoid using for-in loop for arrays

Instead of using…

var sum = 0;
for (var i in arrayNumbers) {
sum += arrayNumbers[i];
}

…it’s better to use…

var sum = 0;
for (var i = 0, len = arrayNumbers.length; i < len; i++) {
sum += arrayNumbers[i];
}

As a bonus, the instantiation of i and len is executed once because it’s in the first statement of the for loop. Thsi is faster than using…

for (var i = 0; i = 50):
category = "Old";
break;
case (age <= 20):
category = "Baby";
break;
default:
category = "Young";
break;
};
return category;
}
getCategory(5); // will return "Baby"

38 – Create an object whose prototype is a given object

It’s possible to write a function that creates an object whose prototype is the given argument like this…

function clone(object) {
function OneShotConstructor(){};
OneShotConstructor.prototype= object;
return new OneShotConstructor();
}
clone(Array).prototype ; // []

39 – An HTML escaper function

function escapeHTML(text) {
var replacements= {"": ">","&": "&", """: """};
return text.replace(/[&"]/g, function(character) {
return replacements[character];
});
}

40 – Avoid using try-catch-finally inside a loop

The try-catch-finally construct creates a new variable in the current scope at runtime each time the catch clause is executed where the caught exception object is assigned to a variable.

Instead of using…

var object = ['foo', 'bar'], i;
for (i = 0, len = object.length; i <len; i++) {
try {
// do something that throws an exception
}
catch (e) {
// handle exception
}
}

…use…

var object = [‘foo’, ‘bar’], i;
try {
for (i = 0, len = object.length; i <len; i++) {
// do something that throws an exception
}
}
catch (e) {
// handle exception
}

41 – Set timeouts to XMLHttpRequests

You could abort the connection if an XHR takes a long time (for example, due to a network issue), by using setTimeout() with the XHR call.

var xhr = new XMLHttpRequest ();
xhr.onreadystatechange = function () {
if (this.readyState == 4) {
clearTimeout(timeout);
// do something with response data
}
}
var timeout = setTimeout( function () {
xhr.abort(); // call error callback
}, 60*1000 /* timeout after a minute */ );
xhr.open('GET', url, true);

xhr.send();

As a bonus, you should generally avoid synchronous XHR calls completely.

42 – Deal with WebSocket timeout

Generally when a WebSocket connection is established, a server could time out your connection after 30 seconds of inactivity. The firewall could also time out the connection after a period of inactivity.

To deal with the timeout issue you could send an empty message to the server periodically. To do this, add these two functions to your code: one to keep alive the connection and the other one to cancel the keep alive. Using this trick, you’ll control the timeout.

Add a timerID…

var timerID = 0;
function keepAlive() {
var timeout = 15000;
if (webSocket.readyState == webSocket.OPEN) {
webSocket.send('');
}
timerId = setTimeout(keepAlive, timeout);
}
function cancelKeepAlive() {
if (timerId) {
cancelTimeout(timerId);
}
}

The keepAlive() function should be added at the end of the onOpen() method of the webSocket connection and the cancelKeepAlive() at the end of the onClose() method.

43 – Keep in mind that primitive operations can be faster than function calls. Use VanillaJS.

For example, instead of using…

var min = Math.min(a,b);
A.push(v);

…use…

var min = a < b ? a : b;
A[A.length] = v;

44 – Don’t forget to use a code beautifier when coding. Use JSLint and minification (JSMin, for example) before going live.

45 – JavaScript is awesome: Best Resources To Learn JavaScript

Code Academy JavaScript tracks: http://www.codecademy.com/tracks/javascript
Eloquent JavaScript by Marjin Haverbeke: http://eloquentjavascript.net/
Advanced JavaScript by John Resig: http://ejohn.org/apps/learn/

What is clearfix?

18 Jun

This was long overdue,I always quiz about clearfix and is something that I feel every Frontend Developer should know about. But surprisingly almost 50% of candidate could never answer this thing and hence this post

A clearfix is a way for an element to automatically clear its child elements, so that you don’t need to add additional markup. It’s generally used in float layouts where elements are floated to be stacked horizontally.

The clearfix is a way to combat the zero-height container problem for floated elements

A clearfix is performed as follows:

.clearfix:after {
   content: " "; /* Older browser do not support empty content */
   visibility: hidden;
   display: block;
   height: 0;
   clear: both;
}

Or, if you don’t require IE

.clearfix:after {
  content: "";
  display: table;
  clear: both;
}

Normally you would need to do something as follows:


    <div style="float: left;">Sidebar

    <div style="clear: both;">
 

With clearfix, you only need to

<div class="clearfix">
    <div style="float: left;" class="clearfix">Sidebar

    

I hope this helps in understanding the magic behind clearfix.

Creating and running a simple Node.js server

12 Jun
Building a server in JavaScript?

If you’re using lots of JavaScript for the client-side of your app, it may make sense for you to also use JavaScript for the server. Such is the convenience of Node.js.

In this article we’ll go over all the setup and code needed to get a Node.js server loading an index.html file from localhost into your web browser.

What you’ll need

Install Homebrew if you don’t already have it.

Run brew install node in your Terminal. This will install both node andnpm.

Now, run npm install express ––save to install Express.

A simple server.js file

Here’s is all the code you’ll need to serve your index.html page when you visit localhost:8000 in your web browser. Save this server.js file in the same directory as your index.html file.

/* *****************
 * Require Imports *
 * *****************/

var express = require('express');
var path = require('path');

/* ***********************
 * Initialize Middleware *
 * **********************/

// Instantiate the express object
var app = express();

// Use the static assets from the same directory as this server.js file
app.use(express.static(path.resolve("./")));

/* **************
 * GET Requests *
 * **************/

// index.html
app.get('/', function(req, res) {
  res.sendFile('index.html');
});

/* ******************
 * Start the server *
 * ******************/

var port = process.env.PORT || 8000;

var server = app.listen(port, function() {
  console.log('Listening on port:', port);
});

Running the Node.js server
Now, execute the command node server.js in your Terminal to run the JavaScript file that will serve up our index.html page.

Finally, open your browser and navigate to localhost:8000.

And you are done…..

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

What Every Frontend Developer Should Know About Webpage Rendering

2 Jul

Rendering has to be optimized from the very beginning, when the page layout is being defined, as styles and scripts play the crucial role in page rendering. Professionals have to know certain tricks to avoid performance problems.

This arcticle does not study the inner browser mechanics in detail, but rather offers some common principles. Different browser engines work differently, this would make a browser-specific study even more complicated.

How do browsers render a web page

We start with an overview of browser actions when rendering a page:

The DOM (Document Object Model) is formed from the HTML that is received from a server.
Styles are loaded and parsed, forming the CSSOM (CSS Object Model).
On top of DOM and CSSOM, a rendering tree is created, which is a set of objects to be rendered (Webkit calls each of those a “renderer” or “render object”, while in Gecko it’s a “frame”). Render tree reflects the DOM structure except for invisible elements (like the tag or elements that have display:none; set). Each text string is represented in the rendering tree as a separate renderer. Each of the rendering objects contains its corresponding DOM object (or a text block) plus the calculated styles. In other words, the render tree describes the visual representation of a DOM.
For each render tree element, its coordinates are calculated, which is called “layout”. Browsers use a flow method which only required one pass to layout all the elements (tables require more than one pass).
Finally, this gets actually displayed in a browser window, a process called “painting”.
When users interact with a page, or scripts modify it, some of the aforementioned operations have to be repeated, as the underlying page structure changes.

Repaint

When changing element styles which don’t affect the element’s position on a page (such as background-color, border-color, visibility), the browser just repaints the element again with the new styles applied (that means a “repaint” or “restyle” is happening).

Reflow

When the changes affect document contents or structure, or element position, a reflow (or relayout) happens. These changes are usually triggered by:

DOM manipulation (element addition, deletion, altering, or changing element order);
Contents changes, including text changes in form fields;
Calculation or altering of CSS properties;
Adding or removing style sheets;
Changing the “class” attribute;
Browser window manipulation (resizing, scrolling);
Pseudo-class activation (:hover).
How browsers optimize rendering

Browsers are doing their best to restrict repaint/reflow to the area that covers the changed elements only. For example, a size change in an absolute/fixed positioned element only affects the element itself and its descendants, whereas a similar change in a statically positioned element triggers reflow for all the subsequent elements.

Another optimization technique is that while running pieces of JavaScript code, browsers cache the changes, and apply them in a single pass after the code was run. For example, this piece of code will only trigger one reflow and repaint:

var $body = $(‘body’);
$body.css(‘padding’, ‘1px’); // reflow, repaint
$body.css(‘color’, ‘red’); // repaint
$body.css(‘margin’, ‘2px’); // reflow, repaint
// only 1 reflow and repaint will actually happen
However, as mentioned above, accessing an element property triggers a forced reflow. This will happen if we add an extra line that reads an element property to the previous block:

var $body = $(‘body’);
$body.css(‘padding’, ‘1px’);
$body.css(‘padding’); // reading a property, a forced reflow
$body.css(‘color’, ‘red’);
$body.css(‘margin’, ‘2px’);
As a result, we get 2 reflows instead of one. Because of this, you should group reading element properties together to optimize performance (see a more detailed example on JSBin).

There are situations when you have to trigger a forced reflow. Example: we have to apply the same property (“margin-left” for example) to the same element twice. Initially, it should be set to 100px without animation, and then it has to be animated with transition to a value of 50px. You can study this example on JSBin right now, but I’ll describe it here in more detail.

We start by creating a CSS class with a transition:

.has-transition {
-webkit-transition: margin-left 1s ease-out;
-moz-transition: margin-left 1s ease-out;
-o-transition: margin-left 1s ease-out;
transition: margin-left 1s ease-out;
}
Then proceed with the implementation:

// our element that has a “has-transition” class by default
var $targetElem = $(‘#targetElemId’);

// remove the transition class
$targetElem.removeClass(‘has-transition’);

// change the property expecting the transition to be off, as the class is not there
// anymore
$targetElem.css(‘margin-left’, 100);

// put the transition class back
$targetElem.addClass(‘has-transition’);

// change the property
$targetElem.css(‘margin-left’, 50);
This implementation, however, does not work as expected. The changes are cached and applied only at the end of the code block. What we need is a forced reflow, which we can achieve by making the following changes:

// remove the transition class
$(this).removeClass(‘has-transition’);

// change the property
$(this).css(‘margin-left’, 100);

// trigger a forced reflow, so that changes in a class/property get applied immediately
$(this)[0].offsetHeight; // an example, other properties would work, too

// put the transition class back
$(this).addClass(‘has-transition’);

// change the property
$(this).css(‘margin-left’, 50);
Now this works as expected.

Practical advice on opmitization

Summarizing the available information, I could recommend the following:

Create valid HTML and CSS, do not forget to specify the document encoding. Styles should be included into , and scripts appended to the end of the tag.
Try to simplify and optimize CSS selectors (this optimization is almost universally ignored by developers who mostly use CSS preprocessors). Keep nesting levels at a minimum. This is how CSS selectors rank according to their performance (starting from the fastest ones):
Identificator: #id
Class: .class
Tag: div
Adjacent sibling selector: a + i
Parent selector: ul > li
Universal selector: *
Attribute selector: input[type=”text”]
Pseudoclasses and pseudoelements: a:hover You should remember that browsers process selectors from right to left, that’s why the rightmost selector should be the fastest one — either #id or .class:
div * {…} // bad
.list li {…} // bad
.list-item {…} // good
#list .list-item {…} // good
In your scripts, minimize DOM manipulation whenever possible. Cache everything, including properties and objects (if they are to be reused). It’s better to work with an “offline” element when performing complicated manipulations (an “offline” element is one that is disconnected from DOM and only stored in memory), and append it to DOM afterwards.
If you use jQuery to select elements, follow jQuery selectors best practices.
To change element’s styles, modifying the “class” attribute is one of the most performant ways. The deeper in the DOM tree you perform this change, the better (also because this helps decouple logic from presentation).
Animate only absolute/fixed positioned elements if you can.
It is a good idea to disable complicated :hover animations while scrolling (e.g. by adding an extra “no-hover” class to ). Read an article on the subject.
For a more detailed overview, have a look at these articles:

How browsers work
Rendering: repaint, reflow/relayout, restyle
I hope you find this article useful!

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).

The Best Website Taglines Around the Internet

7 Jun

This is My first blog and wanted to start with something interesting. We all browse internet and sometime you stumble upon some jewels. Here are some of the best tag-lines that I have came across on the internet. Some of them are funny, some are clever; but all of them deliver the message! Hopefully it will serve as inspiration.

  1. The Straight Dope: Fighting Ignorance since 1973 (It’s taking longer than we thought).
  2. Maxim Philippines: The best thing that ever happened to men … after women!
  3. The Consumerist: Shoppers bite back.
  4. Random Acts of Reality: Trying to kill as few people as possible…
  5. Joshuaink: Same old shit, different day.
  6. The Superficial: Because you’re ugly.
  7. Smashing Magazine: We smash you with information that will make your life easier. Really.
  8. The Best Page in the Universe: This page is about me and why everything I like is great. If you disagree with anything you find on this page, you are wrong.
  9. Scaryduck: Not scary. Not a duck.
  10. The Art of Rhysisms: Chronologically inept since 2060.
  11. Needcoffee.com: We are the Internet equivalent of a triple espresso with whipped cream. Mmmm…whipped cream.
  12. Ample Sanity: Life is short. Make fun of it.
  13. Rathergood.com: The Lair of the Crab of Ineffable Wisdom – a load of stuff by Joel Veitch that will probably crush your will to live.
  14. The Breakfast Blog: In search of the best eggs in town.
  15. Dooce: Not even remotely funny.
  16. Pink is the new blog: Everybody’s business is my business.
  17. Shoemoney: Skills to pay the bills.
  18. Oh No They Didnt’t!: The celebrities are disposable, the content is priceless.
  19. YouTube: Broadcast Yourself.
  20. Waiter Rant: Do you want Pommes Frite with that?
  21. Newshounds: We watch FOX so you don’t have to.
  22. Sabrina Faire: All the fun of a saucy wench, none of the overpriced beer.
  23. Defective Yeti: A maze of twisty passages, all alike.
  24. All About George: All about George Kelly… you know, if you go in for that sort of thing.
  25. Go Fug Yourself: Fugly is the new pretty.
  26. kottke.org: Home of fine hypertext products.
  27. Slashdot: News for nerds. Stuff that matters.
  28. Gawker: Daily Manhattan media news and gossip. Reporting live from the center of the universe.
  29. Get Rich Slowly: Personal finance that makes cents.
  30. hi5: Who’s in?
  31. Fotolog: Share your world with the world.
  32. Jezebel: Celebrity, Sex, Fashion for Women, Without Aribrushing.
  33. Autoblog: We obssessibely cover the auto industry.
  34. Boing Boing: A directory of wonderful things.
  35. Perez Hilton: Celebrity Juice. Not from concentrate.
  36. DumbLittleMan: So what do we do here? Well, it’s simple. 15 to 20 times per week we provide tips that will save you money, increase your productivity, or simply keep you sane.
  37. Lifehacker: Don’t live to geek, geek to live!
  38. Gizmodo: The gadget guide. So much in love with shiny new toys, it’s unnatural.
  39. John Cow Dot Com: Make Moooney Online with John Cow Dot Com
  40. WebWorkerDaily: Rebooting the workforce.
  41. The Simple Dollar: Financial talk for the rest of us.
  42. TrafficBunnies: Making your hits multiply like rabbits.
  43. Mighty Girl: Famous among dozens.
  44. The Sneeze: Half zine. Half blog. Half not good with fractions.
  45. Buzz Marketing: Because everyone is entitled to my opinion