About Me

Having 12 years experience in Microsoft technologies.Since more than 7 years working in SharePoint technologies. Expert in providing consultation for SharePoint projects. Hands on with development and administration.

Tuesday 25 November 2014

SharePoint 2013 - Fronnt end & HTML/CSS coding standards

Here are HTML & CSS coding standards and mandatory to know before developing SharePoint 2013 apps. 
1.1               General
Many of the coding standards in this document are based off those used by Google.  These can be found at:
1.2               Indentation / Whitespace
Indentation should be 4 spaces at a time; tabs should not be used. 
Trailing whitespace should be removed as it can complicate diffs.
1.3               Encoding
An editor which uses UTF-8 as character encoding without a byte order mark (BOM) should be used.
The encoding in HTML templates and documents should be specified via <meta charset="utf-8">. The encoding of style sheets should not be specified as these assume UTF-8.
1.4               Separation of concerns
Structure, presentation, and behaviour should be kept strictly apart, and the interaction between the three kept to an absolute minimum.  HTML documents should contain only structural markup, anything presentational should be in stylesheets, and everything behavioural in scripts.

2.   HTML & CSS
2.1               Capitalisation
All code should be lowercase: This applies to HTML element names, attributes, attribute values (unless text/CDATA), CSS selectors, properties, and property values (with the exception of strings).
<!-- Not recommended -->
<A HREF="/">Home</A>
<!-- Recommended -->
<img src="logo.png" alt="Client Logo">
/* Not recommended */
color: #E5E5E5;
/* Recommended */
color: #e5e5e5;
 2.2               Comments
Comment should be placed where necessary to explain complex code or a decision, this will depend on the situation / project. 
HTML closing tags should not be commented “for clarity”; most editors will highlight selected tags or allow expanding/collapsing sections for this purpose.

2.3               Graceful Degradation
If support is required for IE prior to version 9 (or otherwise non-HTML5-supporting older browsers), an HTML5 shiv/shim script should always be included.  If the project is built using a framework (eg. Bootstrap) or something lightweight is required then html5shiv is probably sufficient, otherwise Modernizer is recommended.
Newer technologies like CSS3 gradients should be used for extra polish, and ensure the styles still appear clear in older browsers.  Don’t leave the background displaying black on browsers which don’t support a gradient if the text is also black!
All dynamic content and multimedia should degrade gracefully.  Images should be provided for browsers which do not support <canvas>, alt content should always be provided for all images, and transcripts / captions for <video> and <audio> where available.  For pages where javascript is absolutely required for important tasks such as navigation, or the main content (not recommended), a <noscript> alternative should be provided.
Providing alternative contents is important for accessibility reasons: A blind user has few cues to tell what an image is about without alt, and other users may have no way of understanding what video or audio contents are about if these are disabled or unsupported by their browser.
2.4               HTML
HTML5 should be used for all HTML documents: <!DOCTYPE html>.  XHTML syntax should be used, that is all void elements should be closed (such as <br />).
Documents should always be served as text/html (not application/xhtml+xml or otherwise).
Validity should always be tested, using tools such as the W3C HTML validator.
Elements should always be used for their intended purpose, and the most appropriate element should always be used for the content; the HTML5 specification can be quite specific, or for an easier read there are sites such as html5doctor.
<!-- Not recommended -->
<div onclick="goToRecommendations();">All recommendations</div>
<!-- Recommended -->
<a href="recommendations/">All recommendations</a>
The type attributes should not be specified for style sheets (unless not using CSS) and scripts (unless not using JavaScript).  Specifying type attributes in these contexts is not necessary as HTML5 implies text/css and text/javascript as defaults. This can be safely done even for older browsers.
Although in HTML5 there are now some tags which do not have to have a closing tag, for example: html, head, body, p, dt, dd, li, option, thead, th, tbody, tr, td, tfoot, colgroup; for readability the closing tags for these should be used.
2.5               Omit the protocol from embedded resources.
The protocol portion (http:https:) should be omitted from URLs pointing to images and other media files, style sheets, and scripts unless the respective files are not available over both protocols.  Omitting the protocol—which makes the URL relative—prevents mixed content issues and results in minor file size savings.
<!-- Not recommended -->
<script src="http://www.site.com/js/gweb/analytics/autotrack.js"></script>
<!-- Recommended -->
<script src="//www.site.com/js/gweb/analytics/autotrack.js"></script>
/* Not recommended */
.example {
  background: url(http://www.site.com/images/example);
}
/* Recommended */
.example {
  background: url(//www.site.com/images/example);
}
2.6               Entity References
Although UTF-8 encoding should be used for all documents, for consistency and editor compatibility use of entity references like &mdash;, &rdquo;, or &#x263a; is advised (and required for HTML characters such as < and &).
2.7               CSS
Unless dealing with CSS validator bugs or requiring proprietary syntax, valid CSS code should be used. Tools such as the W3C CSS validator should be used to test.  Use of LESS is recommended, particularly if the project is also using a framework which uses it (like Bootstrap).
All CSS hosted in an environment beyond local development (ie. ‘test’ / production environments) should be minified for performance.
2.8               Reset
A CSS reset script should always come at the beginning of the first CSS script or be the first script included on the page - a recommended reset script is Eric Meyer’s Reset CSS 2.0.  If the project is using Bootstrap no additional reset is required as it is built to be cross-browser compatible.
2.9               Shorthand
Shorthand properties should be used where possible, for code efficiency and clarity.
/* Not recommended */
border-top-style: none;
font-family: palatino, georgia, serif;
font-size: 100%;
line-height: 1.6;
padding-bottom: 2em;
padding-left: 1em;
padding-right: 1em;
padding-top: 0;
/* Recommended */
border-top: 0;
font: 100%/1.6 palatino, georgia, serif;
padding: 0 1em 2em;
  
2.10            Naming
Words and abbreviations in selectors should not be concatenated by any characters (including none at all / camelCase) other than hyphens, in order to improve clarity.
/* Not recommended: does not separate the words “demo” and “image” */
.demoImage {}
 
/* Not recommended: uses underscore instead of hyphen */
.error_status {}
/* Recommended */
#video-id {}
.ads-sample {}
2.11            Code Formatting
Every declaration should be ended with a semicolon for consistency and extensibility reasons.  CSS minifiers will remove these later as necessary.
All block content should be indented to reflect hierarchy and improve clarity.
@media screen, projection {
 
  html {
    background: #fff;
    color: #444;
  }
 
}
Property and value should be separated by a single space (but no space between property and colon) for consistency.
/* Not recommended */
h3 {
  font-weight:bold;
}
/* Recommended */
h3 {
  font-weight: bold;
}
A single space should be used between the last selector and the opening brace that begins the declaration block.  The opening brace should be on the same line as the last selector in a given rule.
/* Not recommended: missing space */
#video{
  margin-top: 1em;
}
 
/* Not recommended: unnecessary line break */
#video
{
  margin-top: 1em;
}
/* Recommended */
#video {
  margin-top: 1em;
}
Instead of presentational or cryptic names, ID and class names that reflect the purpose of the element in question, or that are otherwise generic, should be used.  Names that are specific and reflect the purpose of the element should be preferred as these are most understandable and the least likely to change; generic names are simply a fallback for elements that have no particular or no meaning different from their siblings. They are typically needed as “helpers.”
/* Not recommended: meaningless */
#yee-1901 {}
 
/* Not recommended: presentational */
.button-green {}
.clear {}
/* Recommended: specific */
#gallery {}
#login {}
.video {}
 
/* Recommended: generic */
.aux {}
.alt {}
Unless necessary (for example with helper classes), element names in conjunction with IDs or classes should not be used.  Avoiding unnecessary ancestor selectors is useful for performance reasons.
/* Not recommended */
ul#example {}
div.error {}
/* Recommended */
#example {}
.error {}
2.12            Conditional CSS
Conditional CSS should be used sparingly, but there are certainly cases which warrant it (IE filters in older versions are an example); browser-specific CSS hacks are to be avoided wherever possible.  A separate stylesheet should be included for older versions of IE, through conditional comments, as necessary (IE 10 and above no longer support conditional comments).


 Happy programming....
Cheers!
Vamsi

SharePoint 2013 Apps - java script/jquery coding standards

It is required to know & understand coding standards of java script & jquery, because it is mandatory when you develop SharePoint 2013 apps.
1.1               Naming Conventions
·         Terminology and Definitions:
·         Camel Case (camelCase): The first letter of the word is lower case and then each first letter of the part of the word is upper case;
·         Pascal Case (PascalCase): The first letter of the word is upper case and then each first letter of the part of the word is upper case;
·         Underscode Prefix (_underscore): The word begins with underscore char and for the rest of the word use camelCase rule;
1.2               General Rules
·         Use Pascal Case for Class names:
Ex: public class HelloWorld { ... };
·         Use Pascal Case for Method names:
Ex: public void SayHello(string name) { ... };
·         Use Camel Case for variables and method parameters:
Ex:
int totalCount = 0;
void SayHello(string name)
{
string fullMessage = "Hello " + name;
...
}
·         Avoid all upper case or all lower case names;
Do not use Hungarian notation:
Example of Hungarian Notation:
string m_sName; (the prefix m_ means that is a member variable and s means that is a string data type);
·         Code Commenting
Adding comments to your work is without doubt one of the most important factor in team working. More than that, it also represents the best technique for keeping the code maintainable in time. Have a look at rules below:
·         General Rules
All comments should be written in the same language, be grammatically correct and contain appropriate punctuation;
Use // or /// but not /* … */;
Do not use flower box comments
Ex:
//***************************
// flower box
//***************************
Use inline comments to explain assumptions, known issues and algorithm insights;
Do not use inline comments to explain obvious code. Well written code is self-documenting; Always apply comment-blocks (///) to public, protected and internal
1.3               JavaScript Files
·         JavaScript programs should be stored in and delivered as .js files.
·         JavaScript code should not be embedded in HTML files unless the code is specific to a single session. Code in HTML adds significantly to page weight with no opportunity for mitigation by caching and compression.
·         <script src=filename.js> tags should be placed as late in the body as possible. This reduces the effects of delays imposed by script loading on other page components. There is no need to use the language or type attributes. It is the server, not the script tag, that determines the MIME type.
1.4               Indentation
·         The unit of indentation is four spaces. Use of tabs should be avoided because there still is not a standard for the placement of tab stops.
1.5               Line Length
·         Avoid lines longer than 80 characters. When a statement will not fit on a single line, it may be necessary to break it. Place the break after an operator, ideally after a comma. A break after an operator decreases the likelihood that a copy-paste error will be masked by semicolon insertion. The next line should be indented 8 spaces.
1.6               Comments
·         Be generous with comments. It is useful to leave information that will be read at a later time by people (possibly yourself) who will need to understand what you have done. The comments should be well-written and clear, just like the code they are annotating.
·         It is important that comments be kept up-to-date. Erroneous comments can make programs even harder to read and understand.
·         Make comments meaningful. Focus on what is not immediately visible. Don't waste the reader's time with stuff like
·             i = 0; // Set i to zero.
·         Generally use line comments. Save block comments for formal documentation and for commenting out.
1.7               Variable Declarations
·         All variables should be declared before used. JavaScript does not require this, but doing so makes the program easier to read and makes it easier to detect undeclared variables that may become implied global. Implied global variables should never be used.
·         The var statements should be the first statements in the function body.
·         It is preferred that each variable be given its own line and comment. They should be listed in alphabetical order.
    var currentEntry; // currently selected table entry
    var level;        // indentation level
    var size;         // size of table
·         JavaScript does not have block scope, so defining variables in blocks can confuse programmers who are experienced with other C family languages. Define all variables at the top of the function.
·         Use of global variables should be minimized. Implied global variables should never be used.
·         Use strict mode. The rules for declaring variables in JavaScript are fairly relaxed. If you omit the var keyword in a variable declaration, the variable is implicitly given global scope. This means you can accidentally declare a new global variable without realizing it, as illustrated in the following example:
function someFunction() {
   var errorCode = 100; // Declares a local variable named errorCode.
   count = 0; // Implicitly declares a global variable named count;
   ...
}
To avoid accidentally declaring global variables by omitting the var keyword, you can use strict mode as follows:
function someFunction() {
   "use strict";
    // Other statements.
}
When you use strict mode, you will get an error if you try to declare a variable without using var;
JavaScript will not automatically promote the variable to global scope.
·         Because JavaScript is very loose with rules concerning variable and object definitions, you should be sure to always use strict JavaScript in your apps. Strict JavaScript is an improved version of JavaScript. You can enable it by adding the line “use strict” at the top of any library or function. Strict JavaScript will prevent you from making many common mistakes in your code. The following lists some of the key restrictions enabled by strict JavaScript:
·         Cannot use a variable without declaring it
·         Cannot write to a read-only property
·         Cannot add properties to non-extensible objects
·         Cannot illegally delete functions and variables
·         Cannot define a property more than once in an object literal
·         Cannot use a parameter name more than once in a function
·         Cannot use reserved words, eval, or arguments, as names for functions and variables
·         The value of this in a function is no longer the window object
·         Cannot declare functions inside of statements
·         Cannot change the members of the arguments array
1.9               Function Declarations
·         All functions should be declared before they are used. Inner functions should follow the var statement. This helps make it clear what variables are included in its scope.
·         There should be no space between the name of a function and the ( (left parenthesis) of its parameter list. There should be one space between the ) (right parenthesis) and the { (left curly brace) that begins the statement body. The body itself is indented four spaces. The } (right curly brace) is aligned with the line containing the beginning of the declaration of the function.
    function outer(c, d) {
        var e = c * d;
        function inner(a, b) {
            return (e * a) + b;
        }
        return inner(0, 1);
    }
·         This convention works well with JavaScript because in JavaScript, functions and object literals can be placed anywhere that an expression is allowed. It provides the best readability with inline functions and complex structures.
    function getElementsByClassName(className) {
        var results = [];
        walkTheDOM(document.body, function (node) {
            var a;                  // array of class names
            var c = node.className; // the node's classname
            var i;                  // loop counter
// If the node has a class name, then split it into a list of simple names.
// If any of them match the requested name, then append the node to the set of results.
            if (c) {
                a = c.split(' ');
                for (i = 0; i < a.length; i += 1) {
                    if (a[i] === className) {
                        results.push(node);
                        break;
                    }
                }
            }
        });
        return results;
    }
·         If a function literal is anonymous, there should be one space between the word function and the ( (left parenthesis). If the space is omited, then it can appear that the function's name is function, which is an incorrect reading.
    div.onclick = function (e) {
        return false;
    };
    that = {
        method: function () {
            return this.datum;
        },
        datum: 0
    };
·         Use of global functions should be minimized.
·         When a function is to be invoked immediately, the entire invocation expression should be wrapped in parens so that it is clear that the value being produced is the result of the function and not the function itself.
var collection = (function () {
    var keys = [], values = [];
    return {
        get: function (key) {
            var at = keys.indexOf(key);
            if (at >= 0) {
                return values[at];
            }
        },
        set: function (key, value) {
               var at = keys.indexOf(key);
               if (at < 0) {
                               at = keys.length;
                }
                keys[at] = key;
                values[at] = value;
                },
                                 remove: function (key) {
                var at = keys.indexOf(key);
                if (at >= 0) {
                                keys.splice(at, 1);
                               values.splice(at, 1);
                }
                }
                               };
}());
1.10            Names
·         Names should be formed from the 26 upper and lower case letters (A .. Z, a .. z), the 10 digits (0 .. 9), and _ (underbar). Avoid use of international characters because they may not read well or be understood everywhere. Do not use $ (dollar sign) or \ (backslash) in names.
·         Most variables and functions should start with a lower case letter.
·         Constructor functions which must be used with the new prefix should start with a capital letter. JavaScript issues neither a compile-time warning nor a run-time warning if a required new is omitted. Bad things can happen if new is not used, so the capitalization convention is the only defense we have.
·         Global variables should be in all caps. (JavaScript does not have macros or constants, so there isn't much point in using all caps to signify features that JavaScript doesn't have.)
1.11            Statements
    Simple Statements
·         Each line should contain at most one statement. Put a ; (semicolon) at the end of every simple statement. Note that an assignment statement which is assigning a function literal or object literal is still an assignment statement and must end with a semicolon.
·         JavaScript allows any expression to be used as a statement. This can mask some errors, particularly in the presence of semicolon insertion. The only expressions that should be used as statements are assignments and invocations.
     Compound Statements
·         Compound statements are statements that contain lists of statements enclosed in { } (curly braces).
·         The enclosed statements should be indented four more spaces.
·         The { (left curly brace) should be at the end of the line that begins the compound statement.
·         The } (right curly brace) should begin a line and be indented to align with the beginning of the line containing the matching { (left curly brace).
·         Braces should be used around all statements, even single statements, when they are part of a control structure, such as an if or for statement. This makes it easier to add statements without accidentally introducing bugs.
     Whitespace
·         Blank lines improve readability by setting off sections of code that are logically related.
·         Blank spaces should be used in the following circumstances:
·         A keyword followed by ( (left parenthesis) should be separated by a space.
while (true) {
·         A blank space should not be used between a function value and its ( (left parenthesis). This helps to distinguish between keywords and function invocations.
·         All binary operators except . (period) and ( (left parenthesis) and [ (left bracket) should be separated from their operands by a space.
·         No space should separate a unary operator and its operand except when the operator is a word such as typeof.
·         Each ; (semicolon) in the control part of a for statement should be followed with a space.
·         Whitespace should follow every , (comma).
1.12            for-in loops
These loops are to be used only for iterating over keys in an object/map/hash. They are often incorrectly used to loop over the elements in an Array. This is however very error prone because it does not loop from 0 to length - 1 but over all the present keys in the object and its prototype chain. Here are a few cases where it fails:

function printArray(arr) {

  for (var key in arr) {

    print(arr[key]);

  }

}



printArray([0,1,2,3]);  // This works.



var a = new Array(10);

printArray(a);  // This is wrong.



a = document.getElementsByTagName('*');

printArray(a);  // This is wrong.



a = [0,1,2,3];

a.buhu = 'wine';

printArray(a);  // This is wrong again.



a = new Array;

a[3] = 3;

printArray(a);  // This is wrong again.
Always use normal for loops when using arrays.

function printArray(arr) {

  var l = arr.length;

  for (var i = 0; i < l; i++) {

    print(arr[i]);

  }

}
1.13            Associative arrays
Array should never be used as a map/hash/associative array.  Associative Arrays are not allowed - more precisely you are not allowed to use non number indexes for arrays. If a map/hash is required Object should be used instead of Array since the features that are required are actually features of Object and not of ArrayArray just happens to extend Object (like any other object in JS and therefore you might as well have used DateRegExp or String).
1.14            Multi-line strings
Slashes should not be used:
var myString = 'A rather long string of English text, an error message \
                actually that just keeps going and going -- an error \
                message to make the Energizer bunny blush (right through \
                those Schwarzenegger shades)! Where was I? Oh yes, \
                you\'ve got an error and all the extraneous whitespace is \
                just gravy.  Have a nice day.';
The whitespace at the beginning of each line can't be safely stripped at compile time; whitespace after the slash will result in tricky errors; and while most script engines support this, it is not part of ECMAScript.
String concatenation should be used instead:
var myString = 'A rather long string of English text, an error message ' +
    'actually that just keeps going and going -- an error ' +
    'message to make the Energizer bunny blush (right through ' +
    'those Schwarzenegger shades)! Where was I? Oh yes, ' +
    'you\'ve got an error and all the extraneous whitespace is ' +
    'just gravy.  Have a nice day.';
1.15            Array & Object Literals
Array and Object literals should be used instead of Array and Object constructors.  Array constructors are error-prone due to their arguments.

// Length is 3.

var a1 = new Array(x1, x2, x3);



// Length is 2.

var a2 = new Array(x1, x2);



// If x1 is a number and it is a natural number the length will be x1.

// If x1 is a number but not a natural number this will throw an exception.

// Otherwise the array will have one element with x1 as its value.

var a3 = new Array(x1);



// Length is 0.

var a4 = new Array();
Because of this, if someone changes the code to pass 1 argument instead of 2 arguments, the array might not have the expected length.
To avoid these kinds of weird cases, the more readable array literal should always be used.

var a = [x1, x2, x3];

var a2 = [x1, x2];

var a3 = [x1];

var a4 = [];
Object constructors don't have the same problems, but for readability and consistency object literals should be used.

var o = new Object();



var o2 = new Object();

o2.a = 0;

o2.b = 1;

o2.c = 2;

o2['strange key'] = 3;
Should be written as:

var o = {};



var o2 = {

  a: 0,

  b: 1,

  c: 2,

  'strange key': 3

};

1.16            Method and property definitions
While there are several ways to attach methods and properties to an object created via new, the preferred style for methods is:

Foo.prototype.bar = function() {

  /* ... */

};
The preferred style for other properties is to initialize the field in the constructor:

/** @constructor */

function Foo() {

  this.bar = value;

}
1.17            Browser-specific code / IE hacks
Browser-specific javascript objects or functions should not be used.
var f = function () {
    /*@cc_on if (@_jscript) { return 2* @*/  3; /*@ } @*/
};
Conditional Comments hinder automated tools as they can vary the JavaScript syntax tree at runtime.
1.18            Javascript Tips & Tricks
True and False Boolean Expressions
The following are all false in boolean expressions:
·         null
·         undefined
·         '' the empty string
·         0 the number
But be careful, because these are all true:
·         '0' the string
·         [] the empty array
·         {} the empty object

                    This means that instead of this:

while (x != null) {
                 you can write this shorter code (as long as you don't expect x to be 0, or the 
                 empty string, or false):

while (x) {
                   And if you want to check a string to see if it is null or empty, you could do this:

if (y != null && y != '') {
                    But this is shorter and nicer:

if (y) {
                 Caution: There are many unintuitive things about boolean expressions. Here are 
                 some of them:
·         Boolean('0') == true
'0' != true
·         0 != null
0 == []
0 == false
·         Boolean(null) == false
null != true
null != false
·         Boolean(undefined) == false
undefined != true
undefined != false
·         Boolean([]) == true
[] != true
[] == false
·         Boolean({}) == true
{} != true
{} != false
                  Instead of this:

if (val) {

  return foo();

} else {

  return bar();

}

                  you can write this:

return val ? foo() : bar();
                 The ternary conditional is also useful when generating HTML:

var html = '<input type="checkbox"' +

    (isChecked ? ' checked' : '') +

    (isEnabled ? '' : ' disabled') +

    ' name="foo">';

&& and ||
These binary boolean operators are short-circuited, and evaluate to the last evaluated term.
"||" has been called the 'default' operator, because instead of writing this:

/** @param {*=} opt_win */

function foo(opt_win) {

  var win;

  if (opt_win) {

    win = opt_win;

  } else {

    win = window;

  }

  // ...

}

                you can write this:

/** @param {*=} opt_win */

function foo(opt_win) {

  var win = opt_win || window;

  // ...

}

              "&&" is also useful for shortening code. For instance, instead of this:

if (node) {

  if (node.kids) {

    if (node.kids[index]) {

      foo(node.kids[index]);

    }

  }

}

              this could be used:

if (node && node.kids && node.kids[index]) {

  foo(node.kids[index]);

}

              or this:

var kid = node && node.kids && node.kids[index];

if (kid) {

  foo(kid);

}
Iterating over Node Lists
Node lists are often implemented as node iterators with a filter. This means that getting a property like length is O(n), and iterating over the list by re-checking the length will be O(n^2).

var paragraphs = document.getElementsByTagName('p');

for (var i = 0; i < paragraphs.length; i++) {

  doSomething(paragraphs[i]);

}
          It is better to do this instead:

var paragraphs = document.getElementsByTagName('p');

for (var i = 0, paragraph; paragraph = paragraphs[i]; i++) {

  doSomething(paragraph);

}
This works well for all collections and arrays as long as the array does not contain things that are treated as boolean false.
In cases of iterating over the childNodes, the firstChild and nextSibling properties can be used.

var parentNode = document.getElementById('foo');

for (var child = parentNode.firstChild; child; child = child.nextSibling) {

  doSomething(child);

}
1.20            Other common suggestions
             {} and []
·         Use {} instead of new Object (). Use [] instead of new Array ().
·         Use arrays when the member names would be sequential integers. Use objects when the member names are arbitrary strings or names.
             , (comma) Operator
·         Avoid the use of the comma operator except for very disciplined use in the control part of for statements. (This does not apply to the comma separator, which is used in object literals, array literals, var statements, and parameter lists.)
             Block Scope
·         In JavaScript blocks do not have scope. Only functions have scope. Do not use blocks except as required by the compound statements.
             Assignment Expressions
·         Avoid doing assignments in the condition part of if and while statements.
Is
if (a = b) {
a correct statement? Or was
  if (a == b) {
intended? Avoid constructs that cannot easily be determined to be correct.
=== and !== Operators.
·         It is almost always better to use the === and !== operators. The == and != operators do type coercion. In particular, do not use == to compare against falsy values.
             Confusing Pluses and Minuses
·         Be careful to not follow a + with + or ++. This pattern can be confusing. Insert parens between them to make your intention clear.
total = subtotal + +myInput.value;
is better written as
total = subtotal + (+myInput.value);
so that the + + is not misread as ++.
eval is Evil
·         The eval function is the most misused feature of JavaScript. Avoid it.
·         eval has aliases. Do not use the Function constructor. Do not pass strings to setTimeout or setInterval.
1.21            Exception Handling
             Error Objects
·         When an exception occurs, an object representing the error is created and thrown.  The JavaScript language defines seven types of built-in error objects.  These error types are the foundation for exception handling.  Each of the error types is described in detail below.
                   Error
·         The “Error” type is used to represent generic exceptions.  This type of exception is most often used for implementing user defined exceptions.  ”Error” objects are instantiated by calling their constructor as shown in the following example.
var error = new Error("error message");
·         “Error” objects contain two properties, “name” and “message”.  The “name” property specifies the type of exception (in this case “Error”).  The “message” property provides a more detailed description of the exception.  The “message” gets its value from the string passed to the exception’s constructor.  The remaining exception types represent more specific types of errors, but they are all used in the same fashion as the generic “Error” type.
                   RangeError
·         “RangeError” exceptions are generated by numbers that fall outside of a specified range.  For example, JavaScript numbers have a toFixed() method which takes a “digits” argument representing the number of digits to appear after a decimal point.  This argument is expected to be between 0 and 20 (although some browsers support a wider range).  If the value of “digits” is outside of this range, then a “RangeError” is thrown.  This scenario is shown in the following example.
var pi = 3.14159;
pi.toFixed(100000);  // RangeError
                   ReferenceError
·         A “ReferenceError” exception is thrown when a non-existent variable is accessed.  These exceptions commonly occur when an existing variable name is misspelled.  In the example below, a “ReferenceError” occurs when “bar” is accessed.  Note that this example assumes that “bar” does not exist in any active scope when the increment operation is attempted.
function foo() {
bar++;  // ReferenceError
}
                   SyntaxError
·         A “SyntaxError” is thrown when the rules of the JavaScript language are broken.  Developers who are familiar with languages such as C and Java are used to encountering syntax errors during the compilation process.  However, because JavaScript is an interpreted language, syntax errors are not identified until the code is executed.  Syntax errors are unique as they are the only type of exception that cannot be recovered from.  The following example generates a syntax error because the “if” statement is missing a closing curly brace.
if (foo) {  // SyntaxError
// the closing curly brace is missing
                   TypeError
·         A “TypeError” exception occurs when a value is not of the expected type.  Attempting to call a non-existent object method is a common cause of this type of exception.  The following example creates an empty object named “foo” and then attempts to invoke its bar() method.  Since bar() is not defined, a “TypeError” is thrown upon the attempted invocation.
var foo = {};
foo.bar(); // TypeError
                   URIError
·         A “URIError” exception is thrown by methods such as encodeURI () and decodeURI () when they encounter a malformed URI.  The following example generates a “URIError” while attempting to decode the string “%”.  The “%” character represents the beginning of a URI escape sequence.  Since nothing follows the “%” in this example, the string is an invalid escape sequence, and therefore a malformed URI component.
decodeURIComponent ("%"); // URIError

                   EvalError
·         “EvalError” exceptions are thrown when the eval() function is used improperly.  These exceptions are not used in the most recent version of the EcmaScript standard.  However, they are still supported in order to maintain backwards compatibility with older versions of the standard.
1.22            Handling Exceptions
·         Now that we know what exceptions are, it’s time to learn how to stop them from crashing our programs.  JavaScript handles exceptions via the “try…catch…finally” statement.  A generic example statement is shown below.
try {
// attempt to execute this code
} catch (exception) {
// this code handles exceptions
} finally {
// this code always gets executed
}
·         The first part of a “try…catch…finally” statement is the “try” clause.  The “try” clause is mandatory, and is used to delimit a block of code that the programmer suspects could generate an exception.  The “try” clause must be followed by one or both of the “catch” and “finally” clauses.
                   The “catch” Clause
·         The second part of “try…catch…finally” is the “catch” clause.  The “catch” clause is a block of code that is only executed if an exception occurs in the “try” clause.  Although the “catch” clause is optional, it isn’t possible to truly handle an exception without one.  This is because the “catch” clause stops the exception from propagating through the call stack, allowing the program to recover.  If an exception occurs within the “try” block, then control is immediately passed to the “catch” clause.  The exception that occurred is also passed to the “catch” block for processing.  The following example shows how a “catch” clause is used to handle a “ReferenceError”.  Note that the “ReferenceError” object is available in the “catch” clause via the “exception” variable.
try {
foo++;  // ReferenceError
} catch (exception) {
var message = exception.message;

 // handle the exception
}
·         Complex applications can generate a variety of exceptions.  In such cases, the “instanceof” operator can be used to differentiate between the various types of exceptions.  In the following example, assume that the “try” clause can generate several types of exceptions.  The corresponding “catch” clause uses “instanceof” to handle “TypeError” and “ReferenceError” exceptions separately from all other types of errors.
try {
// assume an exception occurs
} catch (exception) {
 if (exception instanceof TypeError) {
// Handle TypeError exceptions
 } else if (exception instanceof ReferenceError) {
 // Handle ReferenceError exceptions
} else {
 // Handle all other types of exceptions
 }
}
             The “finally” Clause
·         The last component of the “try…catch…finally” statement is the optional “finally” clause.  The “finally” clause is a block of code that is executed after the “try” and “catch” clauses, regardless of any errors.  The “finally” clause is useful for including clean up code (closing files, etc.) that needs to be executed no matter what.  Note that the “finally” clause is even executed if an exception occurs that is not caught.  In such a scenario, the “finally” clause is executed and then the thrown exception proceeds normally.
·         One interesting note about the “finally” clause is that it will be executed even if the “try” or “catch” clause executes a “return” statement.  For example, the following function returns false because the “finally” clause is the last thing to execute.
function foo() {
 try {
 return true;
 } finally {
return false;
}
}
         Throwing Exceptions
·         JavaScript allows programmers to throw their own exceptions via the appropriately named “throw” statement.  This concept can be somewhat confusing to inexperienced developers.  After all, developers strive to write code that is free of errors, yet the “throw” statement intentionally introduces them.  However, intentionally throwing exceptions can actually lead to code that is easier to debug and maintain.  For example, by creating meaningful error messages it becomes easier to identify and resolve problems.
·         Several examples of the “throw” statement are shown below.  There is no restriction on the type of data that can be thrown as an exception.  There is also no limit on the number of times that the same data can be caught and thrown.  In other words, an exception can be thrown, caught, and then thrown again.
throw true;
throw 5;
throw "error message";
throw null;
throw undefined;
throw {};
throw new SyntaxError("useful error message");
·         While the “throw” statement can be used with any data type, there are certain benefits to using the built-in exception types.  Firefox, for example, gives special treatment to those objects by adding debugging information such as the filename and line number where the exception occurred.
·         As an example scenario, assume that a division operation occurs somewhere in your application.  Division can be a nuisance because of the possibility of division by zero.  In JavaScript, such an operation results in “NaN”.  This can lead to confusing results that are tricky to debug.  Things would be much simpler if the application complained loudly about the division by zero.  The following “if” statement accomplishes this for us by throwing an exception.
if (denominator === 0)
  throw new Error("Attempted division by zero!");
Of course, it might be more appropriate to use a “RangeError” as shown below.
if (denominator === 0)
  throw new RangeError("Attempted division by zero!");
Custom Exception Objects
·         We’ve just learned how to generate customized error messages using the built-in exception types.  However, another approach is to create new exception types by extending the existing “Error” type.  Because the new type inherits from “Error”, it can be used like the other built-in exception types.  While the topic of inheritance in JavaScript is beyond the scope of this article, a simple technique is covered here.
·         The following example returns to the problem of dealing with division by zero.  Instead of using an “Error” or “RangeError” object as we did earlier, we are going to create our own type of exception.  In this example, we are creating the “DivisionByZeroError” exception type.  The function in the example acts as the constructor for our new type.  The constructor takes care of assigning the “name” and “message” properties.  The final two lines of the example cause the new type to inherit from the “Error” object.
function DivisionByZeroError(message) {
  this.name = "DivisionByZeroError";
  this.message = (message || "");
}
DivisionByZeroError.prototype = new Error();
DivisionByZeroError.prototype.constructor = DivisionByZeroError;
·         The power of jQuery, however, lies in the fact that the selector syntax is identical to that used in cascading style sheets (CSS). This means that you can use a rich, familiar selector syntax to reference any part of the DOM, which becomes a powerful and efficient way to manipulate the DOM elements.
·         Once you have selected DOM elements, you will want to manipulate them. This is where jQuery methods come into play. The jQuery library has a tremendous number of methods that perform all kinds of useful DOM manipulations. These manipulations are always performed on the collection of elements returned from the jQuery global function.
·         jQuery supports many methods for manipulating DOM elements beyond what is shown in Table 2-3. The complete reference of supported methods is available at http://api.jquery.com/category/manipulation. Furthermore, jQuery methods can be chained together so that you can perform several operations in a single line of code. The following code changes the inner HTML of an element, adds a class, and then displays the result, all in a single line:
$("displayDiv").html("<p>Hello</p>").addClass("emphasis").show();

Happy programming....

Cheers!
Vamsi