Tag Archives: javascript

19 Javascript String functions explained

1. escape(string):
The escape method returns a string value (in Unicode format) that contains the contents of [the argument]. All spaces, punctuation, accented characters, and any other non-ASCII characters are replaced with %xx encoding, where xx is equivalent to the hexadecimal number representing the character. For example, a space is returned as “%20.”
Use unescape() function to get back the original string.

2. unescape(string):
De-encodes a string that is encoded using escape() function.

3. encodeURI(string):
The encodeURI method returns an encoded URI. If you pass the result to decodeURI, the original string is returned. The encodeURI method does not encode the following characters: “:”, “/”, “;”, and “?”. Encodes a Uniform Resource Identifier (URI) by replacing each instance of certain characters by one, two, or three escape sequences representing the UTF-8 encoding of the character.

4. decodeURI(string):
De-encodes a string that is encoded using encodeURI() function.

5. charAt(n):
Returns the character at the position nth position.

6. charCodeAt(n):
Returns the encoded character at the nth position.

7. concat(string):
Returns a concatenated string.

8. String.fromCharCode(numX,numX,…,numX):
Returns a string created from Unicode values.

9. stringObject.indexOf(searchvalue,fromindex):
Returns the position of of a specified string value’s first occurrence in a string.

10. stringObject.lastIndexOf(searchvalue,fromindex):
Returns the position of of a specified string value’s last occurrence in a string.

11. stringObject.match(regexp):
Searches for a specified value in a string.

12. stringObject.replace(regexp/substr,newstring):
Replaces some characters with some other characters in a string.

13. stringObject.search(regexp):
Searches a string for a specified value.

14. stringObject.slice(begin,end):
Extracts a part of a string and returns the extracted part in a new string.

15. stringObject.split(separator, limit):
Splits a string into an array of strings.

16. stringObject.substr(start, length):
Extracts a specified number of characters in a string, from a start index.

17. stringObject.substring(indexA, indexB):
Extracts the characters in a string between two specified indices.

18. stringObject.toLowerCase():
Converts to Lower Case string.

19. stringObject.toUpperCase()
Converts to Upper Case string.

JSLint: The JavaScript Code Quality Tool


will hurt your feelings.

What is JSLint?

is a JavaScript program that looks for problems in JavaScript programs.
It is a code quality tool.

When C

was a young
programming language, there were several common programming errors that
were not caught by the primitive compilers, so an accessory program called
was developed that would scan a source file, looking for problems.

As the language matured, the definition of the language was
strengthened to eliminate some insecurities, and compilers got better
at issuing warnings. lint is no longer needed.

JavaScript is a young-for-its-age
language. It was originally intended to do small tasks in webpages, tasks
for which Java was too heavy and clumsy. But JavaScript is a very capable
language, and it is now being used in larger projects. Many of the features
that were intended to make the language easy to use are troublesome for
larger projects. A lint for JavaScript is needed: JSLint,
a JavaScript syntax checker and validator.

JSLint takes a JavaScript source and scans it. If it finds
a problem, it returns a message describing the problem and an approximate
location within the source. The problem is not necessarily a syntax error,
although it often is. JSLint looks at some style conventions
as well as structural problems. It does not prove that your program is
correct. It just provides another set of eyes to help spot problems.

JSLint defines a professional subset of JavaScript, a stricter
language than that defined by Third
Edition of the ECMAScript Programming Language Standard
. The
subset is related to recommendations found in Code
Conventions for the JavaScript Programming Language

JavaScript is a sloppy language, but inside it there is an elegant, better
language. JSLint helps you to program in that better language
and to avoid most of the slop.

JSLint can operate on JavaScript source, HTML source, or JSON


Global Variables

JavaScript’s biggest
is its dependence on global variables, particularly implied
global variables. If a variable is not explicitly declared (usually with
the var statement), then JavaScript assumes that the variable
was global. This can mask misspelled names and other problems.

JSLint expects that all variables and functions are declared
before they are used or invoked. This allows it to detect implied global
variables. It is also good practice because it makes programs easier to

Sometimes a file is dependent on global variables and functions that
are defined elsewhere. You can identify these to JSLint with a var statement that lists the global functions and objects
that your program depends on.

A global declaration can look like this:

var getElementByAttribute, breakCycles, hanoi;

The declaration should appears near the top of the file. It must appear before the use of the variables
it declares.

It is necessary to use a var statement to declare a variable before that variable is assigned to.

JSLint also recognizes a /*global */ comment that can indicate to JSLint that variables used in this file were defined in other files. The comment can contain a comma separated list of names. Each name can optionally be followed by a colon and either true or false, true indicated that the variable may be assigned to by this file, and false indicating that assignment is not allowed which is the default.

Some globals can be predefined for you. Select the Assume
a browser
(browser) option to
predefine the standard global properties that are supplied by web browsers,
such as document and alert. It has the same
effect as this comment:

/*global addEventListener: false, alert: false, blur: false, clearInterval: false, clearTimeout: false, close: false, closed: false, confirm: false, console: false, Debug: false, defaultStatus: false, document: false, event: false, focus: false, frames: false, getComputedStyle: false, history: false, Image: false, length: false, location: false, moveBy: false, moveTo: false, name: false, navigator: false, onblur: true, onerror: true, onfocus: true, onload: true, onresize: true, onunload: true, open: false, opener: false, opera: false, Option: false, parent: false, print: false, prompt: false, resizeBy: false, resizeTo: false, screen: false, scroll: false, scrollBy: false, scrollTo: false, setInterval: false, setTimeout: false, status: false, top: false, XMLHttpRequest: false */

The browser option does
not include the aliases of the global object, window and

Select the Assume Rhino (rhino) option

to predefine the global properties provided by the Rhino environment.
It has the same effect as this statement:

/*global defineClass: false, deserialize: false, gc: false, help: false, load: false, loadClass: false, print: false, quit: false, readFile: false, readUrl: false, runCommand: false, seal: false, serialize: false, spawn: false, sync: false, toint32: false, version: false */

Select the Assume a Yahoo Widget (widget)
option to predefine the global properties provided
by the Yahoo! Widgets environment. It has the same effect as this statement:

/*global alert: true, animator: true, appleScript: true, beep: true, bytesToUIString: true, Canvas: true, chooseColor: true, chooseFile: true, chooseFolder: true, closeWidget: true, COM: true, convertPathToHFS: true, convertPathToPlatform: true, CustomAnimation: true, escape: true, FadeAnimation: true, filesystem: true, Flash: true, focusWidget: true, form: true, FormField: true, Frame: true, HotKey: true, Image: true, include: true, isApplicationRunning: true, iTunes: true, konfabulatorVersion: true, log: true, md5: true, MenuItem: true, MoveAnimation: true, openURL: true, play: true, Point: true, popupMenu: true, preferenceGroups: true, preferences: true, print: true, prompt: true, random: true, Rectangle: true, reloadWidget: true, ResizeAnimation: true, resolvePath: true, resumeUpdates: true, RotateAnimation: true, runCommand: true, runCommandInBg: true, saveAs: true, savePreferences: true, screen: true, ScrollBar: true, showWidgetPreferences: true, sleep: true, speak: true, Style: true, suppressUpdates: true, system: true, tellWidget: true, Text: true, TextArea: true, Timer: true, unescape: true, updateNow: true, URL: true, Web: true, widget: true, Window: true, XMLDOM: true, XMLHttpRequest: true, yahooCheckLogin: true, yahooLogin: true, yahooLogout: true */


JavaScript uses a C-like syntax which requires the use of semicolons to delimit
statements. JavaScript attempts to make semicolons optional with a semicolon
insertion mechanism. This is dangerous.

Like C, JavaScript has ++ and -- and ( operators
which can be prefixes or suffixes. The disambiguation is done by the semicolon.

In JavaScript, a linefeed can be whitespace or it can act as a semicolon.
This replaces one ambiguity with another.

JSLint expects that every statement be followed by ; except
for for, function, if, switch, try, and
while. JSLint does not expect to see unnecessary semicolons or the
empty statement.

Line Breaking

As a further defense against the semicolon insertion mechanism, JSLint
expects long statements to be broken only after one of these punctuation
characters or operators:

, . ; : { } ( [ = < > ? ! + - * / % ~ ^ | &

== != <= >= += -= *= /= %= ^= |= &= << >>

|| &&

=== !== <<= >>= >>> >>>=

JSLint does not expect to see a long statement broken after
an identifier, a string, a number, closer, or a suffix operator:

) ] ++ --

JSLint allows you to turn on the Tolerate sloppy line
(laxbreak) option.

Semicolon insertion can mask copy/paste errors. If you always break lines
after infix operators, then JSLint can do better at finding errors.


The comma operator can lead to excessively tricky expressions. It can also
mask some programming errors.

JSLint expects to see the comma used as a separator, but not as an
operator (except in the initialization and incrementation parts of the for
statement). It does not expect to see elided elements in array literals. Extra
commas should not be used. A comma should not appear after the last element
of an array literal or object literal because it can be misinterpreted by some


In many languages, a block introduces a scope. Variables introduced in
a block are not visible outside of the block.

In JavaScript, blocks do not introduce a scope. There is only function-scope.
A variable introduced anywhere in a function is visible everywhere in
the function. JavaScript’s blocks confuse experienced programmers and
lead to errors because the familiar syntax makes a false promise.

JSLint expects blocks with function, if,
switch, while, for, do,
and try statements and nowhere else.

In languages with block scope, it is usually recommended that variables
be declared at the site of first use. But because JavaScript does not
have block scope, it is wiser to declare all of a function’s variables
at the top of the function. It is recommended that a single var
statement be used per function. This can be enforced with the onevar

Required Blocks

JSLint expects that if, while,
do and for statements will be made with blocks
{that is, with statements enclosed in braces}.

JavaScript allows an if to be written like this:

if (condition)

That form is known to contribute to mistakes in projects where many programmers
are working on the same code. That is why JSLint expects the use of
a block:

if (condition) {

Experience shows that this form is more resilient.

Expression Statements

An expression statement is expected to be an assignment or a function/method
call or delete. All other expression statements are considered
to be errors.

for in

The for in statement allows for looping through
the names of all of the properties of an object. Unfortunately,
it also loops through all of the members which were inherited through
the prototype chain.
This has the bad side effect of serving up method
functions when the interest is in data members.

The body of every for in statement should be
wrapped in an if statement that does filtering. It can select
for a particular type or range of values, or it can exclude functions,
or it can exclude properties from the prototype. For example,

for (name in object) {
    if (object.hasOwnProperty(name)) {



A common
in switch statements is to forget to place a break
statement after each case, resulting in unintended fall-through. JSLint

expects that the statement before the next case or default
is one of these: break, return, or throw.


JavaScript allows var definitions to occur anywhere
within a function. JSLint is more strict.

JSLint expects that a var will be declared
only once, and that it will be declared before it is used.

JSLint expects that a function
will be declared before it is used.

JSLint expects that parameters will not also be declared
as vars.

JSLint does not expect the arguments array to be declared
as a var.

JSLint does not expect that a var will be defined in a block.
This is because JavaScript blocks do not have block scope. This can have
unexpected consequences. Define all variables at the top of the function.


The with statement was intended to provide a shorthand in accessing
members in deeply nested objects. Unfortunately, it behaves very
when setting new members. Never use the with statement. Use
a var instead.

JSLint does not expect to see a with statement.


JSLint does not expect to see an assignment statement in
the condition part of an if or for or while

or do statement. This is because it is more
likely that

if (a = b) {

was intended to be

if (a == b) {

It is difficult to write correct programs while using idioms that are
hard to distinguish from obvious errors. If you really intend an assignment,
wrap it in another set of parens:

if ((a = b)) {

== and !=

The == and != operators do type coercion before
comparing. This is bad because it causes ' \t\r\n' == 0 to
be true. This can mask type errors.

When comparing to any of the following values, use the ===

or !== operators (which do not do type coercion): 0
'' undefined null false true

If you only care that a value is truthy or falsy,
then use the short form. Instead of

(foo != 0)

just say


and instead of

(foo == 0)



The === and !== operators are preferred. There
is an eqeqeq option that requires
the use of === and !== in all cases.


JavaScript allows any statement to have a label, and labels have a
separate name space. JSLint is more strict.

JSLint expects labels only on statements that interact
with break: switch, while,
do, and for. JSLint expects that labels
will be distinct from vars and parameters.

Unreachable Code

JSLint expects that
a return, break, continue,
or throw statement will be followed by
a } or case or default.

Confusing Pluses and Minuses

JSLint expects that + will not be followed by
+ or ++, and that - will not be followed
by - or --. A misplaced space can turn + + into ++, an error that is difficult to see. Use parens to avoid confusion..

++ and --

The ++ (increment) and -- (decrement)
operators have been known to contribute to bad code by encouraging excessive
trickiness. They are second only to faulty architecture in enabling to
viruses and other security menaces. There is a plusplus option

that prohibits the use of these operators.

Bitwise Operators

JavaScript does not have an integer type, but it does have bitwise operators.
The bitwise operators convert their operands from floating point to integers
and back, so they are not as efficient as in C or other languages. They
are rarely useful in browser applications. The similarity to the logical
operators can mask some programming errors. The bitwise option
prohibits the use of these operators: << >> >>>
~ & |

eval is evil

The eval function (and its relatives, Function,
setTimeout, and setInterval) provide access
to the JavaScript compiler. This is sometimes necessary, but in most cases
it indicates the presence of extremely bad coding. The eval
function is the most misused feature of JavaScript.


In most C-like languages, void is a type. In
JavaScript, void is a prefix operator that always
returns undefined. JSLint does not expect to
see void because it is confusing and not very useful.

Regular Expressions

Regular expressions are written in a terse and cryptic notation. JSLint
looks for problems that may cause portability problems. It also attempts
to resolve visual ambiguities by recommending explicit escapement.

JavaScript’s syntax for regular expression literals overloads the /
character. To avoid ambiguity, JSLint expects that the character
preceding a regular expression literal is a ( or =

or : or , character.

Constructors and new

Constructors are functions that are designed to be used with the new
prefix. The new prefix creates a new object based on the
function’s prototype, and binds that object to the function’s
implied this parameter. If you neglect to use the new

prefix, no new object will be made and this will be bound
to the global object. This is a serious

JSLint enforces the convention that constructor functions
be given names with initial uppercase. JSLint does not expect
to see a function invocation with an initial uppercase name unless it
has the new prefix. JSLint does not expect to
see the new prefix used with functions whose names do not
start with initial uppercase. This can be controlled with the newcap


JSLint does not expect to see the wrapper forms new Number,
new String, new Boolean.

JSLint does not expect to see new Object (use {}


JSLint does not expect to see new Array (use []

Unsafe Characters

There are characters that are handled inconsistently in browsers, and
so must be escaped when placed in strings.


Not Looked For

JSLint does not do flow analysis to determine that variables are assigned
values before used. This is because variables are given a value (undefined)
which is a reasonable default for many applications.

JSLint does not do any kind of global analysis. It does
not attempt to determine that functions used with new are
really constructors (except by enforcing capitalization
), or that property names are spelled correctly (except
for matching against the /*members */ comment


JSLint is able to handle HTML text. It can inspect the JavaScript content
contained within <script></script> tags. It
also inspects the HTML content, looking for problems that are known to interfere
with JavaScript:

  • All tag names must be in lower case.
  • All tags that can take a close tag (such as </p>)
    must have a close tag.
  • All tags are correctly nested.
  • The entity &lt; must be used for literal '<'.

JSLint is less anal than the sycophantic conformity demanded
by XHTML, but more strict than the popular browsers.

JSLint also checks for the occurrence of '</' in
string literals. You should always write '<\/' instead.
The extra backslash is ignored by the JavaScript compiler but not by the
HTML parser. Tricks like this should not be necessary, and yet they are.

There is a cap option that allows
use of upper case tag names. There is also an on option

that allows the use of inline HTML event handlers.

There is a fragment option that can
inspect a well formed HTML fragment. If the adsafe option
is also used, then the fragment must be a <div> that
conforms to the ADsafe widget rules.


JSLint can inspect CSS files. It expects the first line
of a CSS file to be

@charset "UTF-8";

This feature is experimental. Please report any problems or limitations.
There is a css option that will tolerate
some of the non-standard-but-customary workarounds.


JSLint provides several options that control its operation and
its sensitivity. In the web edition, the
options are selected with several checkboxes and two fields. Clicking on
the button will give
you the ideal settings.

It also provides assistance in constructing /*jslint*/

When JSLINT is called as a function, it accepts an option object
parameter that allows you to determine the subset of JavaScript that is
acceptable to you. The web page version of JSLint at http://www.JSLint.com/
does this for you.

Options can also be specified within a script with a /*jslint */


/*jslint nomen: true, debug: true,
    evil: false, onevar: true */

An option specification starts with /*jslint. Notice that
there is no space before the j. The specification contains
a sequence of name value pairs, where the names are JSLint
options, and the values are true or false. The
indent option can take a number. A /*jslint */

comment takes precedence over the option object.

Description option Meaning
ADsafe adsafe true if ADsafe

rules should be enforced. See http://www.ADsafe.org/.

Disallow bitwise operators bitwise true if bitwise operators should not be allowed. (more)
Assume a browser browser true if the standard browser globals should be predefined.
Tolerate HTML case cap true if upper case HTML should be allowed.
Require Initial Caps for constructors newcap true if Initial Caps must be used with constructor
functions. (more)
Tolerate CSS workarounds css true if CSS workarounds should be tolerated. (more)
Tolerate debugger statements debug true if debugger statements should be
allowed. Set this option to false before going into production.
Disallow == and != eqeqeq true if === should be required. (more)
Tolerate eval evil true if eval should be allowed. (more)
Tolerate unfiltered for in forin true if unfiltered for in

statements should be allowed. (more)

Tolerate HTML fragments fragment true if HTML fragments should be allowed. (more)
Require parens around immediate invocations immed true if immediate function invocations must be wrapped
in parens
Strict white space indentation indent The number of spaces used for indentation (default is 4)
Tolerate sloppy line breaking laxbreak true if statement breaks should not be checked. (more)
Maximum number of errors maxerr The maximum number of warnings reported (default is 50)
Maximum line length maxlen The maximum number of characters in a line
Disallow dangling _ in identifiers nomen true if names should be checked for initial or trailing underbars
Tolerate HTML event handlers on true if HTML event handlers should be allowed. (more)
Allow one var statement per function onevar true if only one var statement per function
should be allowed. (more)
Stop on first error passfail true if the scan should stop on first error.
Disallow ++ and -- plusplus true if ++ and -- should
not be allowed. (more)
Predefined ( , separated) predef An array of strings, the names of predefined global variables.
predef is used with the option object, but not
with the /*jslint */ comment. Use the var

statement to declare global variables in a script file.

Disallow insecure . and [^]. in /RegExp/ regexp true if . and [^] should not be allowed in RegExp
literals. These forms should not be used when validating in secure applications.
Assume Rhino rhino true if the Rhino
environment globals should be predefined. (more)
Safe Subset safe true if the safe subset rules are enforced. These rules
are used by ADsafe. It enforces
the safe subset rules but not the widget structure rules.
Assume a Windows Sidebar Gadget sidebar true if the Windows
Sidebar Gadgets
globals should be predefined. (more)
Require "use strict"; strict true if the ES5 "use strict"; pragma
is required.
Tolerate inefficient subscripting sub true if subscript notation may be used for expressions
better expressed in dot notation.
Disallow undefined variables undef true if variables must be declared before used. (more)
Strict white space white true if strict whitespace rules apply.
Assume a Yahoo Widget widget true if the Yahoo
globals should be predefined. (more)


Since JavaScript is a loosely-typed, dynamic-object language, it is not
possible to determine at compile time if property names are spelled correctly.
JSLint provides some assistance with this.

At the bottom of its report, JSLint displays a /*members*/
comment. It contains all of the names and string literals that were used
with dot notation, subscript notation, and object literals to name the
members of objects. You can look through the list for misspellings. Member
names that were only used once are shown in italics. This is to make misspellings
easier to spot.

You can copy the /*members*/ comment into your script file.
JSLint will check the spelling of all property names against
the list. That way, you can have JSLint look for misspellings
for you.


If JSLint is able to complete its scan, it generates a function
report. It lists for each function:

  • The line number on which it starts.
  • Its name. In the case of anonymous functions, JSLint
    will "guess" the name.
  • The parameters.
  • Closure: The variables and parameters that are declared in
    the function that are used by its inner functions.
  • Variables: The variables that are declared in the function
    that are used only by the function.
  • Exceptions: The variables that are declared by try statements.
  • Unused: The variables that are declared in the function that
    are not used. This may be an indication of an error.
  • Outer: Variables used by this function that are declared in
    another function.
  • Global: Global variables that are used by this function. Keep
    these to a minimum.
  • Label: Statement labels that are used by this function.

The report will also include a list of all of the member
that were used. There is a list of JSLint


Please let me know if JSLint is useful for you. Is it too
strict? Is there a check or a report that could help you to improve the
quality of your programs? douglas@crockford.com

I intend to continue to adapt JSLint based on your comments.
Keep watching for improvements. Updates are announced at http://tech.groups.yahoo.com/group/jslint_com/.

Try it

Try it. Paste your script
into the window and click the

button. The analysis is done by a script running on your machine.
Your script is not sent over the network. You can set the options used.
The button in the
Options area will preset the best options for you.
JSLint is also available in a WSH Command Line version.
JSLint is also available in a Rhino Command Line


Code Conventions for the JavaScript Programming Language

The long-term value of software to an organization is in direct proportion to the quality of the codebase. Over its lifetime, a program will be handled by many pairs of hands and eyes. If a program is able to clearly communicate its structure and characteristics, it is less likely that it will break when modified in the never-too-distant future.

Code conventions can help in reducing the brittleness of programs.

All of our JavaScript code is sent directly to the public. It should always be of publication quality.

Neatness counts.

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 pageweight with no opportunity for mitigation by caching and compression.

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.


The unit of indentation is four spaces. Use of tabs should be avoided because (as of this writing in the 21st Century) there still is not a standard for the placement of tabstops. The use of spaces can produce a larger filesize, but the size is not significant over local networks, and the difference is eliminated by minification.

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.


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. An occasional nugget of humor might be appreciated. Frustrations and resentments will not.

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.

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

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) {
t = c.split(‘ ‘);
for (i = 0; i > t <= 0) {
return value[at];
set: function (key, value) {
var at = keys.indexOf(key);
if (at = 0) {
keys.splice(at, 1);
value.splice(at, 1);


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.

Do not use _ (underbar) as the first character of a name. It is sometimes used to indicate privacy, but it does not actually provide privacy. If privacy is important, use the forms that provide private members. Avoid conventions that demonstrate a lack of competence.

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


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.


Statement labels are optional. Only these statements should be labeled: while, do, for, switch.

return Statement

A return statement with a value should not use ( ) (parentheses) around the value. The return value expression must start on the same line as the return keyword in order to avoid semicolon insertion.

if Statement

The if class of statements should have the following form:

if (condition) {

if (condition) {
} else {

if (condition) {
} else if (condition) {
} else {

for Statement

A for class of statements should have the following form:

for (initialization; condition; update) {

for (variable in object) {
if (filter) {

The first form should be used with arrays and with loops of a predeterminable number of iterations.

The second form should be used with objects. Be aware that members that are added to the prototype of the object will be included in the enumeration. It is wise to program defensively by using the hasOwnProperty method to distinguish the true members of the object:

for (variable in object) {
if (object.hasOwnProperty(variable)) {

while Statement

A while statement should have the following form:

while (condition) {

do Statement

A do statement should have the following form:

do {
} while (condition);

Unlike the other compound statements, the do statement always ends with a ; (semicolon).

switch Statement

A switch statement should have the following form:

switch (expression) {
case expression:

Each case is aligned with the switch. This avoids over-indentation.

Each group of statements (except the default) should end with break, return, or throw. Do not fall through.
try Statement

The try class of statements should have the following form:

try {
} catch (variable) {

try {
} catch (variable) {
} finally {

continue Statement

Avoid use of the continue statement. It tends to obscure the control flow of the function.
with Statement

The with statement should not be used.


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

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


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.

Twelve Simple Ways To Write Search-Friendly HTML Code

The common mistakes developers make when coding HTML. These boneheaded mistakes can cause search engines to choke when it comes to indexing your websites. And its easy to avoid making these mistakes. Here’s how:

1. Don’t repeat yourself. Use server side includes for headers, footers, menus, and standard items such as links to CSS documents and external JavaScript files.
2. Balance tags in server side includes. If an include file starts with

it should end with

. This way each file can be viewed in Dreamweaver design view, and includes files do not depend on each other.
3. Place JavaScript in external files and reference them as needed.
4. Each page must have a unique and . Don’t put these in server side includes.
5. The title should be Name of Company – Name of Page or Name of Company – Name of Category – Name of Page unless you are told otherwise.
6. The description should be the first one or two meaningful sentences of content unless you are told otherwise.
7. Please make all links and references to images, CSS and JavaScript root relative by starting them with a slash, “/”. If you use Dreamweaver, set the “Links relative” option to “Site root” in the Site Definition wizard. Root relative links don’t break when files are moved from one directory to another.
8. Too many files in one directory makes things hard to find. Use subdirectories.
9. Run your code through a validator and keep it clean. Removing trivial errors makes real errors easier to spot.
10. Use CSS with HTML elements like div, span, p, h1 tags and so on, to format things. Only use layout tables when they produce better results or cleaner code than CSS.
11. Use heading tags, unordered lists and numbered lists to organize content rather than spacer graphics and nested tables..
12. Consistently use the simplest URLs. Link to “/” instead of “/index.php” or “/news/” instead of “/news/index.php”.

These recommendations may help sites work better, make pages look good on different browsers and mobile devices, cause pages to load faster, save money, and boost search traffic.