Archive for June, 2010

string.match – matches a string and a RE – use g flag for all occurrences
var m = “this is my text is this”.match(“is”); // m.length returns only 1
m = “this is my text is this”.match(/(is)/g); // m.length returns 4 – whole word match
m = “this is my text is this”.match(/[is]/g); // m.length returns 8 – individual char match
m = ‘<html><head><title>hi</title></head><body>bye</body></html>’.match(/(<[a-zA-Z]+>)|(<\/[a-zA-Z]+>)/g); // m.length returns 8 – matches all html tags        
string.replace –  use g flag for all occurrences
var p = ‘(555)666-1212’.replace(/\((\d{3})\)/g,’$1-‘); //555-666-1212
// $ has special meaning when it is part of the replaceValue Ex: $1, $$, $&, $`, $’
p = ‘(555)666-1212′.replace(/\((\d{3})\)/g,’$$’); //$-666-1212
p = ‘(555)666-1212′.replace(/\((\d{2})\)/g,’$&’); //(555)666-1212 – replaces with the same matched text
p = ‘1(555)666-1212′.replace(/\((\d{3})\)/g,’$`’); // 11666-1212  – replaces with preceding text of the matched text
p = ‘(555)666-1212’.replace(/\((\d{3})\)/g,”$'”); //666-1212666-1212 – replaces with following text of the matched text

Function.prototype.method = function (name, func) {
        this.prototype[name] = func;
    //return this;
String.method(‘entityfy’, function() {
    var chars = {‘<‘:’&lt;’, ‘<‘:’&gt;’, ‘&’:’&amp;’, ‘”‘:’&quot;’};
    return function() {return this.replace(/[<>&]/g, function(c) {return chars[c];});};
var text = “search in this text”;
var pos =; // pos = 4

var words = text.split(/( )/); // words.length – 7, spaces also exist in array
var words2 = text.split(” “); // words2.length – 4, spaces not exist in array

//Other interesting string functions

//string.toLocaleUpperCase() // locale specific
//string.toLocaleLowerCase() // locale specific
//string.charCodeAt() // returns 67 for C
var a = String.fromCharCode(67, 97, 116); // a = Cat

regexp.exec – powerful and slowest methods of RE. If it successfully matches then it returns an array with 0th element matched substring, 1st element text captured by group1, 2nd element text captured by group2

var re = /(<[a-zA-Z]+>)|(<\/[a-zA-Z]+>)/g;
var result = re.exec(“<html><head><title>hi</title></head><body>bye</body></html>”); // result.length – 3 – does not match all occurances
var a;
while((a = re.exec(“<html><head><title>hi</title></head><body>bye</body></html>”))) {
    // a.length – gives 3 for 8 times due to 8 matched tags

regexp.test – simplest and fastest method of RE
var b = re.test(“<html><head><title>hi</title></head><body>bye</body></html>”); // b is true

//JS allows basic types of the lang 2 b augmented with new functionality & this can be done on Object, Function, String, Number, Regular expressions & booleans

// Ex: Augment Function.prototype with method that makes it available for any function, which can save us typing prototype name while using
Function.prototype.method = function (name, func) {
this.prototype[name] = func;
//return this;

// Augment integer method to Number.prototype
Number.method(‘integer’, function () { return Math[this < 0 ? ‘ceil’ : ‘floor’](this); });

document.writeln((-10 / 3).integer() + “<br/>”);

// Augment trim method to String.prototype
String.method(‘trim’, function () { return this.replace(/^\s+|\s+$/g, ”); });
document.writeln(‘”‘ + ”    neat   “.trim() + ‘”‘);

//Note – You can directly test this post by copying everything 2 a .js file and refer it in .htm page

// function in JS are objects linked to function.prototype which itself linked 2 Object.prototype
// Every fn is created with 2 additioinal hidden properties – fn’s context, code that implements the fn’s behavior
// Function literal
var add = function (a, b) {
return a + b;

// Along with declared parameters fns receive 2 more parameters as arguments – this & arguments
// You can excess or less arguments while calling function than the defined arguments, you can use arguments to get all parameters in case of less
// parameters it will give undefined when accessing the non passed parameters
// function if it does not return anything then it will return “this”

var sum = function () {
var sum = 0; // name does not interfere with the variable defined outside
for (i = 0; i < arguments.length; i++) // arguments is not an array but is array like obj, it has length property but it lacks all other array methods
sum += arguments[i];
return sum;

document.writeln(sum(2, 3, 4, 6, 7, 8) + “<br/>”);

// 4 patterns function invocation
// 1. Method invocation pattern
var myObject = {
value : 0,
increment : function (inc) {
this.value += typeof inc === ‘number’ ? inc : 1;

document.writeln(myObject.value + “<br/>”);

document.writeln(myObject.value + “<br/>”);

// 2. Function invocation pattern – when a fn is not the property of an object
var newsum = add(3, 4);

// This kind of function is bound 2 global obj (mistake in design of lang)
// due to this mistake “this” can not be used in the inner function to access stuff of the employed function
// workaround is assign this to a variable in the main function

// Augment myObject with a double method
myObject.double = function () {
var that = this;
var helper = function () {
that.value = add(that.value, that.value);

document.writeln(myObject.value + “<br/>”);

// 3. Construction invocation – by creating constructor fn (fns that are intended 2 be used with the new prefix are called constructors)
// JS is a prototypal inheritance lang i.e. objs can inherit properites directly from other objects which makes js as class-free
// If a fn is invoked with the new prefix then a new object will be created with a hidden link to the value of the fn’s prototype member
// & this will be bound 2 that new obj

//  By convention use capital start letter for variable
var Quo = function (string) {
this.status = string;

Quo.prototype.get_Status = function () {
return this.status;

var myQuo = new Quo(“confused”);

document.writeln(myQuo.get_Status() + “<br/>”);

// 4. Apply invocation pattern
// bcos js is a functional oo lang, fns can methods

// Apply lets us construct an array of arguments 2 use 2 invoke a fn. Apply takes 2 arguments, first one we can specify value for “this”, second is array of params

var array = [3, 4];

document.writeln(add.apply(null, array) + “<br/>”);

var newStatusObj = {
status : “called thru apply”

// newStatusObj does not inherit from Quo.prototype but we can invoke get_status method on newStatusObj eventhough it does not have it
document.writeln(Quo.prototype.get_Status.apply(newStatusObj) + “<br/>”);

// Exception handling – throw {}, try {}catch(e) {}

var newadd = function (a, b) {
if (typeof a !== ‘number’ || typeof b !== ‘number’)
throw { name: ‘TypeError’, message: ‘pass numbers’ };
return a + b;

var try_it = function () {
try {
newadd(‘fool it’);
} catch (e) { document.writeln( + “: ” + e.message + “<br/>”); }



Posted: June 17, 2010 in JSON

JSON (an acronym for JavaScript Object Notation) is a lightweight text-based open standard designed for human-readable data interchange. It is derived from the JavaScript programming language for representing simple data structures and associative arrays, called objects.

The JSON format is often used for serializing and transmitting structured data over a network connection. It is primarily used to transmit data between a server and web application, serving as an alternative to XML.

Note: var mydata = eval(‘(‘+myJSONText+’)’); will work. But eval has security issues so use JSON.parse which will throw an exception if the text contains anything dangerous.

JSONP or “JSON with padding” is a complement to the base JSON data format, a usage pattern that allows a page to request and more meaningfully use JSON from a server other than the primary server. JSONP is an alternative to a more recent method called Cross-Origin Resource Sharing.

Under the same origin policy, a web page served from cannot normally connect to or communicate with a server other than An exception is HTML <script> tags. Taking advantage of the open policy for <script> tags, some pages use them to retrieve JSON from other origins

To see how that works, let’s consider a URL that, when requested, returns a JSON statement. In other words, a browser requesting the URL would receive something like:

 {“Name”: “Cheeso”, “Rank”: 7}
The Basic Idea: Retrieving JSON via Script Tags
It’s possible to specify any URL, including a URL that returns JSON, as the src attribute for a <script> tag.

Specifying a URL that returns plain JSON as the src-attribute for a script tag, would embed a data statement into a browser page. It’s just data, and when evaluated within the browser’s javascript execution context, it has no externally detectable effect.

One way to make that script have an effect is to use it as the argument to a function. invoke( {“Name”: “Cheeso”, “Rank”: 7}) actually does something, if invoke() is a function in Javascript.

And that is how JSONP works. With JSONP, the browser provides a JavaScript “prefix” to the server in the src URL for the script tag; by convention, the browser provides the prefix as a named query string argument in its request to the server, e.g.,

 <script type=”text/javascript”

The server then wraps its JSON response with this prefix, or “padding”, before sending it to the browser. When the browser receives the wrapped response from the server it is now a script, rather than simply a data declaration. In this example, what is received is

   parseResponse({“Name”: “Cheeso”, “Rank”: 7})

…which can cause a change of state within the browser’s execution context, because it invokes a method.

Read more from here

Java Script – Object based dynamic typing language

first-class functions, inner functions, closures and prototypes are interesting areas which gives strong knowledge on javascript and helps in building efficient client side frameworks.

inner functions & closures – Inner functions (functions defined within other functions) are created each time the outer function is invoked, and variables of the outer functions for that invocation continue to exist as long as the inner functions still exist, even after that invocation is finished (e.g. if the inner function was returned, it still has access to the outer function’s variables) — this is the mechanism behind closures within JavaScript. Inner functions get access to the parameters and variables of the functions they are defined within.

prototypes – Every object is linked to a prototype object from which it can inherit properties. JS uses prototypes instead of classes for inheritance. It is possible to simulate many class-based features with prototypes in JS.  The prototype link is used only in retrieval. If we try to retrieve a property value from an object, and if the object lacks the property name, then JS attempts 2 retrieve the property value from the prototype object. And if that object is lacking the property, then it goes to its prototype, and so on until the procfess finally bottoms out withObject.prototype. If the desired property exists nowhere in the prototype chain then the result is the undefined value. This is called delegation. The prototype relationship is dynamic relationship. If we add a new property 2 a prototype, that property will immediately be visible in all of the objects that are based on that prototype.

functions as object constructors – Functions double as object constructors along with their typical role. Prefixing a function call with new creates a new object and calls that function with its local this keyword bound to that object for that invocation. The constructor’s prototype property determines the object used for the new object’s internal prototype. JavaScript’s built-in constructors, such as Array, also have prototypes that can be modified.

functions as methods – Unlike many object-oriented languages, there is no distinction between a function definition and a method definition. Rather, the distinction occurs during function calling; a function can be called as a method. When a function is called as a method of an object, the function’s local this keyword is bound to that object for that invocation.

Global Variables – Use it for maintaining application level assets. Following are the ways 2 define global variables

1. var a = 1;
2. window.a =1;  (window global object, a container for all global variables),
3. a = 1; (without declaration)

To be manageable always use single global variable and augment it with what ever new assets you want to add to the same variable at the later point of time. This will save us avoiding bad interactions with other applications, widgets or libraries.

var MYAPP = {};

MYAPP.myvar = 1;

MYAPP.user = {‘first-name’ : ‘vj’, ‘last-name’:’mahankali’};

MYAPP.myfunction = function(){};

Scope – A variable declared in a block is visible everywhere in the function containing the block. So its better to declare variable at the top of the function in stead of the site of first use.

Reserved words – (like try, class, if, protected … etc) can not be used to name variables or parameters. When they used as keys in object literals, they must be quoted.

Unicode – JS characters are 16 bits. This is enough to cover 65, 536 characters and to represent over it JS uses pair of characters. Unicode considers the pair to be a single character.

parseInt – Use radix parameter to see different results for parseInt(“08”), parseInt(“09”). Ex: parseInt(“08”, 10). Useful for date related operations.

Floating Point – 0.1 + 0.2 is not equal to 0.3, so for correct calculations scale them to integer arithmetic. Ex: instead of using 1.25$ use it as 125 cents.


typeof NaN === ‘number’ //is true even though NaN is not a number
NaN === NaN // false
NaN !== NaN // true
isNaN(NaN) // true
isNaN(0), isNaN(‘0’) // false
isNaN(‘oops’) // true

Falsy Values

NaN – Number type, null – Object type, undefined – Undefined type

== Vs ===, != Vs !==

Always use === or !== bcos these two will correctly validate the comparision correctly based on both operand type and their value.
Some of confusing validations with == operator…

” == ‘0’ // false
0 == ” // true
false == ‘false’ // false
false == ‘0’ // true
null == undefined //true

With statement

Avoid using With to avoid confusion and for better performance
Ex: with (obj) { a = b; } is same as
a = b;
a = obj.b;
obj.a = b;
obj.a = obj.b;

eval – Used for run time evaluation

1. Avoid using eval due to security (grants too much authority to eval’d text), performance reasons.
2. Function constructor is another form of eval and should be avoided. Declare and pass correct values to function as a 2 parameter function can be called with single or two parameters but its not a good idea to pass single parameter.
3. Giving string arguments to setTimeout, setInterval methods will make them act as eval, so avoid it.

Typed Wrappers –

Avoid using them as it is unnecessary and confusing.
Ex: Use {}, [] instead of new Object, new Array. No need of new Boolean(false), new Number, new String.

void – Is a operator that takes operand and returns undefined. This is not useful and confusing so avoid it.

Bitwise Operators

JS does not have integers, it only has double precision floating-point numbers. So the bitwise operators convert their number operands into integers and after the operation they convert them back. It gives performance issues as they are very far from the hardware, so avoid using it.

Function Statement Vs Function Expression

1. function statement is shorthand for a var statement with a function value.
function foo() {}
var foo= function foo() {} // foo is a variable which has function value
Second one is ideal use of language as functions are values assigned to a variable.
2. In JS we don’t need to declare function before using it (as they always be moved to the top of scope in which it is defined), which makes us to keep javascript file includes at the end of the web page for better performance.
3. The first thing in a statement cannot be a function expression bcos the official grammer assumes that a statement that starts with the word function is a function statement. Workaround is wrap function expression in parentheses.

Array –

Known common operations – pop, push, reverse, concat, join, sort (default is string based, need to write custom implementation for numbers)
Other interesting operations …

shift – removes first element for array and returns it, returns undefined for empty array, slower than pop
unshift – like push except it puts items onto the front, returns new length
slice – makes a shallow copy of a portion of an array
splice – removes elements n adds elements at specified position

Enumeration – for in statement (for(val in myobj)) can be used 2 loop over all of the properties, functions in an object and on its prototype. To filter out necessary stuff use reflection (typeof or hasOwnProperty) to validate. There is no guarantee on the order of the names that returns, for getting it in proper order avoid using for in statement and use for.

Read other interesting stuff from here


Posted: June 14, 2010 in CSS
Tags: ,

50 New Useful CSS Techniques, Tools & Tutorials

I am posting this right from the Silverlight 4 pre-conference session by Jeff Prosise in TechEd 2010, New Orleans, LA …:)

Download ppt presentation used in this session from here

Download all samples demonstrated in this session from here

Silverlight is going to be better replacement for Flash and other browser based plug-ins and is only the one which supports multithreading and uses multi core h/w advantage for parallel processing and gives lot of performance boost for loading the silverlight app.