Coding Std for html

Embed Size (px)

Citation preview

  • 8/9/2019 Coding Std for html

    1/22

     

    Page 1 of 22 

    Why have coding standards?

    Coding standards help avoid common coding errors, improve the readability of code, and simplify

    modification. They ensure that files within the project appear as if they were created by a single

    person.

    Following the standards means anyone will be able to understand a section of code and modify it, if

    needed, without regard to when it was written or by whom.

    HTML

    Validation

    All HTML pages should be verified against the W3C validator to ensure that the markup is well

    formed. This in and of itself is not directly indicative of good code, but it helps to weed out problems

    that are able to be tested via automation. It is no substitute for manual code review.

    Self-closing Elements

    All tags must be properly closed. For tags that can wrap nodes such as text or other elements,

    termination is a trivial enough task. For tags that are self-closing, the forward slash should have

    exactly one space preceding it:

    1

    Rather than the compact but incorrect:

    1

    The W3C specifies that a single space should precede the self-closing slash (source).

    Attributes and Tags

    All tags and attributes must be written in lowercase. Additionally, attribute values should be

    lowercase when the purpose of the text therein is only to be interpreted by machines. For instances

    in which the data needs to be human readable, proper title capitalization should be followed.

    For machines:

    1

    For humans:

    1 Example.com

    http://validator.w3.org/http://validator.w3.org/http://validator.w3.org/http://w3.org/TR/xhtml1/#C_2http://w3.org/TR/xhtml1/#C_2http://w3.org/TR/xhtml1/#C_2http://w3.org/TR/xhtml1/#C_2http://validator.w3.org/

  • 8/9/2019 Coding Std for html

    2/22

     

    Page 2 of 22 

    Quotes

    According to the W3C specifications for XHTML, all attributes must have a value, and must use

    double- or single-quotes (source). The following are examples of proper and improper usage of

    quotes and attribute/value pairs.

    Correct:

    1

    2

    Incorrect:

    1

    In HTML, attributes do not all have to have values, and attribute values do not always have to be

    quoted. While all of the examples above are valid HTML, failing to quote attributes can lead to

    security vulnerabilities. Always quote attributes.

    Indentation

    As with PHP, HTML indentation should always reflect logical structure. Use tabs and not spaces.

    When mixing PHP and HTML together, indent PHP blocks to match the surrounding HTML code.

    Closing PHP blocks should match the same indentation level as the opening block.

    Correct:

    1

    2

    3

    4

    5

    6

    7

    89

    Not Found

    Apologies, but no results were found.

    Incorrect:

    1

    2

    3

    Not Found

    http://www.w3.org/TR/xhtml1/#h-4.4http://www.w3.org/TR/xhtml1/#h-4.4http://www.w3.org/TR/xhtml1/#h-4.4http://www.w3.org/TR/xhtml1/#h-4.4

  • 8/9/2019 Coding Std for html

    3/22

     

    Page 3 of 22 

    4

    5

    67

    8

    9

    Apologies, but no results were found.

    CSS

    Like any coding standard, the purpose of the CSS Coding Standards is to create a baseline for

    collaboration and review within various aspects of the project, from core code to themes to plugins.

    Files within a project should appear as though created by a single entity. Above all else, create code

    that is readable, meaningful, consistent, and beautiful.

    Within core stylesheets, inconsistencies will often be found. We are working on addressing these and

    make every effort to have patches and commits from this point forward follow the CSS coding

    standards. More information on the above and contributing to UI/front-end development will be

    forthcoming in a separate set of guidelines.

    Structure

    There are plenty of different methods for structuring a stylesheet. With the CSS in core, it is important

    to retain a high degree of legibility. This enables subsequent contributors to have a clear

    understanding of the flow of the document.

      Use tabs, not spaces, to indent each property.

      Add two blank lines between sections and one blank line between blocks in a section.

      Each selector should be on its own line, ending in either a comma or an opening curly brace.

    Property-value pairs should be on their own line, with one tab of indentation and an endingsemicolon. The closing brace should be flush left, using the same level of indentation as the

    opening selector.

    Correct:

    1

    2

    3

    #selector-1,

    #selector-2,

    #selector-3 {

  • 8/9/2019 Coding Std for html

    4/22

     

    Page 4 of 22 

    4

    5

    6

    background: #fff;

    color: #000;

    }

    Incorrect:

    1

    2

    3

    4

    5

    6

    #selector-1, #selector-2, #selector-3 {

    background: #fff;

    color: #000;

    }

    #selector-1 { background: #fff; color: #000; }

    Selectors

    With specificity, comes great responsibility. Broad selectors allow us to be efficient, yet can have

    adverse consequences if not tested. Location-specific selectors can save us time, but will quickly lead

    to a cluttered stylesheet. Exercise your best judgement to create selectors that find the right balance

    between contributing to the overall style and layout of the DOM.

      Similar to the Standards for file names, use lowercase and separate words with hyphens when

    naming selectors. Avoid camelcase and underscores.

      Use human readable selectors that describe what element(s) they style.

      Attribute selectors should use double quotes around values

     

    Refrain from using over-qualified selectors, div.container can simply be stated as .container 

    Correct:

    1

    2

    3

    4

    5

    6

    7

    #comment-form {

    margin: 1em 0;

    }

    input[type="text"] {

    line-height: 1.1;

    }

    Incorrect:

    1

    2

    3

    4

    5

    #commentForm { /* Avoid camelcase. */

    margin: 0;

    }

    #comment_form { /* Avoid underscores. */

  • 8/9/2019 Coding Std for html

    5/22

     

    Page 5 of 22 

    6

    7

    8

    910

    11

    12

    13

    14

    15

    16

    17

    18

    19

    margin: 0;

    }

    div#comment_form { /* Avoid over-qualification. */margin: 0;

    }

    #c1-xr { /* What is a c1-xr?! Use a better name. */

    margin: 0;

    }

    input[type=text] { /* Should be [type="text"] */

    line-height: 110% /* Also doubly incorrect */

    }

    Properties

    Similar to selectors, properties that are too specific will hinder the flexibility of the design. Less is

    more. Make sure you are not repeating styling or introducing fixed dimensions (when a fluid solution

    is more acceptable).

      Properties should be followed by a colon and a space.

      All properties and values should be lowercase, except for font names and vendor-specific

    properties.  Use hex code for colors, or rgba() if opacity is needed. Avoid RGB format and uppercase, and

    shorten values when possible: #fff instead of #FFFFFF.

      Use shorthand (except when overriding styles) for background, border, font, list-style, margin, and

    padding values as much as possible. (For a shorthand reference, see  CSS Shorthand.)

    Property Ordering

    “Group like properties together, especially if you have a lot of them.” 

    — Nacin

    Above all else, choose something that is meaningful to you and semantic in some way. Randomordering is chaos, not poetry. Our choice is logical or grouped ordering, wherein properties are

    grouped by meaning and ordered specifically within those groups. The properties within groups are

    also strategically ordered to create transitions between sections, such as background directly before

    color. The baseline for ordering is:

      Display

      Positioning

    http://codex.wordpress.org/CSS_Shorthandhttp://codex.wordpress.org/CSS_Shorthandhttp://codex.wordpress.org/CSS_Shorthandhttp://codex.wordpress.org/CSS_Shorthand

  • 8/9/2019 Coding Std for html

    6/22

  • 8/9/2019 Coding Std for html

    7/22

     

    Page 7 of 22 

    Values

    There are numerous ways to input values for properties. Follow the guidelines below to help us retain

    a high degree of consistency.

      Space before the value, after the colon

      Do not pad parentheses with spaces

      Always end in a semicolon

      Use double quotes rather than single quotes, and only when needed, such as when a font name

    has a space.

      0 values should not have units unless necessary, such as with transition-duration.

      Line height should also be unit-less, unless necessary to be defined as a specific pixel value. This is

    more than just a style convention, but is worth mentioning here. Moreinformation:http://meyerweb.com/eric/thoughts/2006/02/08/unitless-line-heights/ 

      Use a leading zero for decimal values, including in rgba().

      Multiple comma-separated values for one property should be separated by either a space or a

    newline, including within rgba(). Newlines should be used for lengthier multi-part values such as

    those for shorthand properties like box-shadow and text-shadow. Each subsequent value after the

    first should then be on a new line, indented to the same level as the selector and then spaced over

    to left-align with the previous value.

    Correct:

    12

    3

    4

    5

    6

    7

    8

    9

    10

    .class { /* Correct usage of quotes */background-image: url(images/bg.png);

    font-family: "Helvetica Neue", sans-serif;

    }

    .class { /* Correct usage of zero values */

    font-family: Georgia, serif;

    text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.5),

    0 1px 0 #fff;

    }

    Incorrect:

    1

    2

    3

    4

    5

    6

    .class { /* Avoid missing space and semicolon */

    background:#fff

    }

    .class { /* Avoid adding a unit on a zero value */

    margin: 0px 0px 20px 0px;

    http://meyerweb.com/eric/thoughts/2006/02/08/unitless-line-heights/http://meyerweb.com/eric/thoughts/2006/02/08/unitless-line-heights/http://meyerweb.com/eric/thoughts/2006/02/08/unitless-line-heights/http://meyerweb.com/eric/thoughts/2006/02/08/unitless-line-heights/

  • 8/9/2019 Coding Std for html

    8/22

     

    Page 8 of 22 

    7 }

    Media Queries

    Media queries allow us to gracefully degrade the DOM for different screen sizes. If you are adding

    any, be sure to test above and below the break-point you are targeting.

      It is generally advisable to keep media queries grouped by media at the bottom of the stylesheet.

      An exception is made for the wp-admin.css file in core, as it is very large and each section

    essentially represents a stylesheet of its own. Media queries are therefore added at the bottom

    of sections as applicable.

      Rule sets for media queries should be indented one level in.

    Example:

    1

    2

    3

    4

    @media all and (max-width: 699px) and (min-width: 520px) {

    /* Your selectors */

    }

    Commenting

     

    Comment, and comment liberally. If there are concerns about file size, utilize minified files and theSCRIPT_DEBUG constant. Long comments should manually break the line length at 80 characters.

      A table of contents should be utilized for longer stylesheets, especially those that are highly

    sectioned. Using an index number (1.0, 1.1, 2.0, etc.) aids in searching and jumping to a location.

      Comments should be formatted much as PHPDoc is. The CSSDoc standard is not necessarily widely

    accepted or used but some aspects of it may be adopted over time. Section/subsection headers

    should have newlines before and after. Inline comments should not have empty newlines

    separating the comment from the item to which it relates.

    For sections and subsections:

    1

    2

    3

    4

    5

    6

    7

    8

    /**

    * #.# Section title

    *

    * Description of section, whether or not it has media queries, etc.

    */

    .selector {

    float: left;

    http://cssdoc.net/http://cssdoc.net/http://cssdoc.net/http://cssdoc.net/

  • 8/9/2019 Coding Std for html

    9/22

     

    Page 9 of 22 

    9 }

    For inline:

    12

    3

    4

    5

    6

    /* This is a comment about this selector */

    .another-selector {

    position: absolute;

    top: 0 !important; /* I should explain why this is so !important */

    }

    Best Practices

    Stylesheets tend to get long in length. Focus slowly gets lost whilst intended goals start repeating andoverlapping. Writing smart code from the outset helps us retain the overview whilst remaining

    flexible throughout change.

      If you are attempting to fix an issue, attempt to remove code before adding more.

      Magic Numbers are unlucky. These are numbers that are used as quick fixes on a one-off basis.

    Example: .box { margin-top: 37px }.

      DOM will change over time, target the element you want to use as opposed to “finding it” through

    its parents. Example: Use .highlight on the element as opposed to .highlight a (where the selector is

    on the parent)

      Know when to use the height property. It should be used when you are including outside elements

    (such as images). Otherwise use line-height for more flexibility.  Do not restate default property & value combinations (for instance display: block; on block-level

    elements).

     JavaScript Coding Standards

    JavaScript has become a critical component in developing Web-based applications. Standards areneeded for formatting and styling JavaScript code to maintain the same code consistency as the Web

    standards provide for core PHP, HTML, and CSS code.

    All code in any code-base should look like a single person typed it, no matter how many people

    contributed. – Principles of Writing Consistent, Idiomatic JavaScript 

    https://github.com/rwaldron/idiomatic.js/https://github.com/rwaldron/idiomatic.js/https://github.com/rwaldron/idiomatic.js/https://github.com/rwaldron/idiomatic.js/

  • 8/9/2019 Coding Std for html

    10/22

     

    Page 10 of 22 

    The JavaScript Coding Standards are adapted from the  jQuery JavaScript Style Guide. Our standard

    differs from the jQuery guidelines in the following ways:

      We use single quotation marks for string declarations.

     

    Case statements are indented within switch blocks.

      Function contents are consistently indented, including full-file closure wrappers.

      Some whitespace rules differ, for consistency with the PHP coding standards.

       jQuery’s 100-character hard line limit is encouraged, but not strictly enforced.

    Many of the examples below have been adapted directly from the jQuery style guide; these

    differences have all been integrated into the examples on this page. Any of the below standards and

    examples should be considered best practice for Javascript code, unless explicitly noted as anti-

    patterns.

    Code Refactoring

    “Code refactoring should not be done just because we can.” – Lead Developer Andrew Nacin

    Many parts of the code structure for JavaScript are inconsistent in their style. So we need to be

    refactoring it as code evolves.

    While the coding standards are important, refactoring older .js files simply to conform to the

    standards is not an urgent issue. “Whitespace-only” patches for older files are strongly discouraged.

    All new or updated JavaScript code should be reviewed to ensure it conforms to the standards, and

    passes JSHint.

    Spacing

    Use spaces liberally throughout your code. “When in doubt, space it out.” 

    These rules encourage liberal spacing for improved developer readability. The minification process

    creates a file that is optimized for browsers to read and process.

      Indentation with tabs.

      No whitespace at the end of line or on blank lines.

      Lines should usually be no longer than 80 characters, and should not exceed 100 (counting tabs as 4

    spaces). This is a “soft” rule, but long lines generally indicate unreadable or disorganized code. 

      if /else/for/while/try blocks should always use braces, and always go on multiple lines.

      Unary special-character operators (e.g., ++, --) must not have space next to their operand.

      Any , and ; must not have preceding space.

    http://contribute.jquery.org/style-guide/jshttp://contribute.jquery.org/style-guide/jshttp://contribute.jquery.org/style-guide/jshttp://make.wordpress.org/core/2011/03/23/code-refactoring/http://make.wordpress.org/core/2011/03/23/code-refactoring/http://make.wordpress.org/core/2011/03/23/code-refactoring/http://make.wordpress.org/core/2011/03/23/code-refactoring/http://contribute.jquery.org/style-guide/js

  • 8/9/2019 Coding Std for html

    11/22

     

    Page 11 of 22 

      Any ; used as a statement terminator must be at the end of the line.

      Any : after a property name in an object definition must not have preceding space.

      The ? and : in a ternary conditional must have space on both sides.

     

    No filler spaces in empty constructs (e.g., {}, [], fn()).  There should be a new line at the end of each file.

      Any ! negation operator should have a following space.* 

      All function bodies are indented by one tab, even if the entire file is wrapped in a closure. * 

      Spaces may align code within documentation blocks or within a line, but only tabs should be used

    at the start of a line.* 

    *: The JavaScript standards prefer slightly broader whitespace rules than the jQuery style guide. These

    deviations are for consistency between the JavaScript files codebase.

    Whitespace can easily accumulate at the end of a line  – avoid this, as trailing whitespace is caught as

    an error in JSHint. One way to catch whitespace buildup is enabling visible whitespace characters

    within your text editor.

    Objects

    Object declarations can be made on a single line if they are short (remember the line length

    guidelines). When an object declaration is too long to fit on one line, there must be one property per

    line. Property names only need to be quoted if they are reserved words or contain special characters:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    // Preferred

    var map = {

    ready: 9,

    when: 4,

    'you are': 15

    };

    // Acceptable for small objects

    var map = { ready: 9, when: 4, 'you are': 15 };

    // Bad

    var map = { ready: 9,

    when: 4, 'you are': 15 };

    Arrays and Function Calls

    Always include extra spaces around elements and arguments:

    1

    2

    array = [ a, b ];

  • 8/9/2019 Coding Std for html

    12/22

     

    Page 12 of 22 

    3

    4

    5

    67

    8

    9

    foo( arg );

    foo( 'string', object );

    foo( options, object[ property ] );

    foo( node, 'property', 2 );

    Exceptions:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    1617

    18

    19

    20

    21

    22

    23

    24

    25

    2627

    28

    29

    30

    31

    32

    // For consistency with our PHP standards, do not include a space around

    // string literals or integers used as key values in array notation:

    prop = object['default'];

    firstArrayElement = arr[0];

    // Function with a callback, object, or array as the sole argument:

    // No space on either side of the argument

    foo(function() {

    // Do stuff

    });

    foo({

    a: 'alpha',

    b: 'beta'

    });

    foo([

    'alpha',

    'beta'

    ]);

    // Function with a callback, object, or array as the first argument:

    // No space before the first argument

    foo(function() {

    // Do stuff

    }, options );

    // Function with a callback, object, or array as the last argument:

    // No space after after the last argument

    foo( data, function() {

    // Do stuff

    });

  • 8/9/2019 Coding Std for html

    13/22

     

    Page 13 of 22 

    Examples of Good Spacing

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    1112

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    var i;

    if ( condition ) {

    doSomething( 'with a string' );

    } else if ( otherCondition ) {

    otherThing({

    key: value,

    otherKey: otherValue

    });

    } else {

    somethingElse( true );

    }

    // This is also done to conform to our PHP standards.

    while ( ! condition ) {

    iterating++;

    }

    for ( i = 0; i < 100; i++ ) {

    object[ array[ i ] ] = someFn( i );

    $( '.container' ).val( array[ i ] );}

    try {

    // Expressions

    } catch ( e ) {

    // Expressions

    }

    Semicolons

    Use them. Never rely on Automatic Semicolon Insertion (ASI).

  • 8/9/2019 Coding Std for html

    14/22

     

    Page 14 of 22 

    Indentation and Line Breaks

    Indentation and line breaks add readability to complex statements.

    Tabs should be used for indentation. Even if the entire file is contained in a closure (i.e., an

    immediately invoked function), the contents of that function should be indented by one tab:

    1

    2

    3

    4

    5

    6

    7

    (function( $ ) {

    // Expressions indented

    function doSomething() {

    // Expressions indented

    }

    })( jQuery );

    Blocks and Curly Braces

    if , else, for, while, and try blocks should always use braces, and always go on multiple lines. The

    opening brace should be on the same line as the function definition, the conditional, or the loop. The

    closing brace should be on the line directly following the last statement of the block.

    1

    2

    3

    45

    6

    7

    8

    9

    var a, b, c;

    if ( myFunction() ) {

    // Expressions} else if ( ( a && b ) || c ) {

    // Expressions

    } else {

    // Expressions

    }

    Multi-line Statements

    When a statement is too long to fit on one line, line breaks must occur after an operator.

    1

    2

    3

    4

    5

    6

    // Bad

    var html = '

    The sum of ' + a + ' and ' + b + ' plus ' + c

    + ' is ' + ( a + b + c );

    // Good

    var html = '

    The sum of ' + a + ' and ' + b + ' plus ' + c +

  • 8/9/2019 Coding Std for html

    15/22

     

    Page 15 of 22 

    7 ' is ' + ( a + b + c );

    Lines should be broken into logical groups if it improves readability, such as splitting each expression

    of a ternary operator onto its own line, even if both will fit on a single line.

    1

    2

    3

    4

    5

    6

    7

    // Acceptable

    var baz = ( true === conditionalStatement() ) ? 'thing 1' : 'thing 2';

    // Better

    var baz = firstCondition( foo ) && secondCondition( bar ) ?

    qux( foo, bar ) :

    foo;

    When a conditional is too long to fit on one line, successive lines must be indented one extra level to

    distinguish them from the body.

    1

    2

    3

    4

    if ( firstCondition() && secondCondition() &&

    thirdCondition() ) {

    doStuff();

    }

    Chained Method Calls

    When a chain of method calls is too long to fit on one line, there must be one call per line, with the

    first call on a separate line from the object the methods are called on. If the method changes the

    context, an extra level of indentation must be used.

    1

    2

    3

    4

    5

    6

    elements

    .addClass( 'foo' )

    .children()

    .html( 'hello' )

    .end()

    .appendTo( 'body' );

     Assignments and Globals

    Declaring Variables With var

    Each function should begin with a single comma-delimited var statement that declares any local

    variables necessary. If a function does not declare a variable using var, that variable can leak into an

  • 8/9/2019 Coding Std for html

    16/22

     

    Page 16 of 22 

    outer scope (which is frequently the global scope, a worst-case scenario), and can unwittingly refer to

    and modify that data.

    Assignments within the var statement should be listed on individual lines, while declarations can be

    grouped on a single line. Any additional lines should be indented with an additional tab. Objects and

    functions that occupy more than a handful of lines should be assigned outside of the var statement,

    to avoid over-indentation.

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    // Good

    var k, m, length,

    // Indent subsequent lines by one tab

    value = 'Sweet Ride';

    // Bad

    var foo = true;

    var bar = false;

    var a;

    var b;

    var c;

    Globals

    All globals used within a file should be documented at the top of that file. Multiple globals can be

    comma-separated.

    This example would make passwordStrength an allowed global variable within that file:

    1 /* global passwordStrength:true */

    The “true” after passwordStrength means that this global is being defined within this file. If you are

    accessing a global which is defined elsewhere, omit :true to designate the global as read-only.

    Common Libraries 

    Backbone, jQuery, Underscore, and the global wp object are all registered as allowed globals in the

    root .jshintrc file.

    Backbone and Underscore may be accessed directly at any time. jQuery should be accessed

    through $ by passing the jQuery object into an anonymous function:

    1

    2

    3

    (function( $ ) {

    // Expressions

    })( jQuery );

  • 8/9/2019 Coding Std for html

    17/22

     

    Page 17 of 22 

    This will negate the need to call .noConflict(), or to set $ using another variable.

    Files which add to, or modify, the wp object must safely access the global to avoid overwriting

    previously set properties:

    1

    2

    // At the top of the file, set "wp" to its existing value (if present)

    window.wp = window.wp || {};

    Naming Conventions

    Variable and function names should be full words, using camel case with a lowercase first letter.

    Constructors intended for use with new should have a capital first letter (UpperCamelCase).

    Names should be descriptive, but not excessively so. Exceptions are allowed for iterators, such as theuse of i to represent the index in a loop.

    Comments

    Comments come before the code to which they refer, and should always be preceded by a blank line.

    Capitalize the first letter of the comment, and include a period at the end when writing full sentences.

    There must be a single space between the comment token (//) and the comment text.

    Single line comments:

    1

    2

    3

    4

    someStatement();

    // Explanation of something complex on the next line

    $( 'p' ).doSomething();

    Multi-line comments should be used for long comments:

    1

    2

    3

    4

    /*

    This is a comment that is long enough to warrant being stretched

    over the span of multiple lines.

    */Inline comments are allowed as an exception when used to annotate special arguments in formal

    parameter lists:

    1

    2

    3

    function foo( types, selector, data, fn, /* INTERNAL */ one ) {

    // Do stuff

    }

  • 8/9/2019 Coding Std for html

    18/22

     

    Page 18 of 22 

    Equality

    Strict equality checks (===) must be used in favor of abstract equality checks (==). The only  exception

    is when checking for both undefined and null by way of null.

    1

    2

    3

    4

    // Check for both undefined and null values, for some important reason.

    if ( undefOrNull == null ) {

    // Expressions

    }

    Type Checks

    These are the preferred ways of checking the type of an object:

      String: typeof object === 'string' 

      Number: typeof object === 'number' 

      Boolean: typeof object === 'boolean' 

      Object: typeof object === 'object' or _.isObject( object ) 

      Plain Object: jQuery.isPlainObject( object ) 

      Function: _.isFunction( object) or jQuery.isFunction( object ) 

      Array: _.isArray( object ) or jQuery.isArray( object ) 

      Element: object.nodeType or _.isElement( object ) 

      null: object === null 

      null or undefined: object == null 

      undefined:

      Global Variables: typeof variable === 'undefined' 

      Local Variables: variable === undefined 

      Properties: object.prop === undefined 

      Any of the above: _.isUndefined( object ) 

    Anywhere Backbone or Underscore are already used, you are encouraged to use Underscore.js‘s type

    checking methods over jQuery’s. 

    Strings

    Use single-quotes for string literals:

    1 var myStr = 'strings should be contained in single quotes';

    http://underscorejs.org/#isElementhttp://underscorejs.org/#isElementhttp://underscorejs.org/#isElementhttp://underscorejs.org/#isElement

  • 8/9/2019 Coding Std for html

    19/22

     

    Page 19 of 22 

    When a string contains single quotes, they need to be escaped with a backslash (\):

    1

    2

    // Escape single quotes within strings:

    'Note the backslash before the \'single quotes\'';

    Switch Statements

    The usage of switch statements is generally discouraged, but can be useful when there are a large

    number of cases – especially when multiple cases can be handled by the same block, or fall-through

    logic (the default case) can be leveraged.

    When using switch statements:

     – Use a break for each case other than default. When allowing statements to “fall through,” note thatexplicitly.

     – Indent case statements one tab within the switch.

    1

    2

    3

    4

    5

    6

    7

    89

    10

    11

    12

    13

    switch ( event.keyCode ) {

    // ENTER and SPACE both trigger x()

    case $.ui.keyCode.ENTER:

    case $.ui.keyCode.SPACE:

    x();

    break;

    case $.ui.keyCode.ESCAPE:y();

    break;

    default:

    z();

    }

    It is not recommended to return a value from within a switch statement: use the case blocks to set

    values, then returnthose values at the end.

    1

    2

    3

    4

    5

    6

    7

    8

    9

    function getKeyCode( keyCode ) {

    var result;

    switch ( event.keyCode ) {

    case $.ui.keyCode.ENTER:

    case $.ui.keyCode.SPACE:

    result = 'commit';

    break;

    case $.ui.keyCode.ESCAPE:

  • 8/9/2019 Coding Std for html

    20/22

     

    Page 20 of 22 

    10

    11

    12

    1314

    15

    16

    17

    result = 'exit';

    break;

    default:

    result = 'default';}

    return result;

    }

    Best Practices

    Arrays

    Creating arrays in JavaScript should be done using the shorthand [] constructor rather than the new

    Array() notation.

    1 var myArray = [];

    You can initialize an array during construction:

    1 var myArray = [ 1, 'My Blog', 2, 'Blog' ];

    In JavaScript, associative arrays are defined as objects.

    Objects

    There are many ways to create objects in JavaScript. Object literal notation, {}, is both the most

    performant, and also the easiest to read.

    1 var myObj = {};

    Object literal notation should be used unless the object requires a specific prototype, in which case

    the object should be created by calling a constructor function with new.

    1 var myObj = new ConstructorMethod();

    Object properties should be accessed via dot notation, unless the key is a variable, a reserved word, 

    or a string that would not be a valid identifier:

    1

    2

    3

    4

    prop = object.propertyName;

    prop = object[ variableKey ];

    prop = object['default'];

    prop = object['key-with-hyphens'];

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Reserved_Wordshttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Reserved_Wordshttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Reserved_Wordshttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Reserved_Words

  • 8/9/2019 Coding Std for html

    21/22

     

    Page 21 of 22 

    “Yoda” Conditions 

    Whenever you are comparing an object to a string, boolean, integer, or other constant or literal, the

    variable should always be put on the right hand side, and the constant or literal put on the left.

    1

    2

    3

    if ( true === myCondition ) {

    // Do stuff

    }

    “A little bizarre, it is, to read. Get used to it, you will.” 

    Iteration

    When iterating over a large collection using a for loop, it is recommended to store the loop’s max

    value as a variable rather than re-computing the maximum every time:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    // Good & Efficient

    var i, max;

    // getItemCount() gets called once

    for ( i = 0, max = getItemCount(); i < max; i++ ) {

    // Do stuff

    }

    // Bad & Potentially Inefficient:

    // getItemCount() gets called every time

    for ( i = 0; i < getItemCount(); i++ ) {

    // Do stuff

    }

    Underscore.js Collection Functions

    Learn and understand Underscore’s collection and array methods. These functions,

    including _.each, _.map, and _.reduce, allow for efficient, readable transformations of large data sets.

    Underscore also permits jQuery-style chaining with regular JavaScript objects:

    1

    2

    3

    var obj = {

    first: 'thing 1',

    second: 'thing 2',

    http://underscorejs.org/#collectionshttp://underscorejs.org/#collectionshttp://underscorejs.org/#collectionshttp://underscorejs.org/#collections

  • 8/9/2019 Coding Std for html

    22/22

     

    P 22 f 22

    4

    5

    6

    78

    9

    10

    11

    12

    13

    14

    15

    third: 'lox'

    };

    var arr = _.chain( obj ).keys()

    .map(function( key ) {

    return key + ' comes ' + obj[ key ];

    })

    // Exit the chain

    .value();

    // arr === [ 'first comes thing 1', 'second comes thing 2', 'third comes lox' ]

    Iterating Over jQuery Collections

    The only time jQuery should be used for iteration is when iterating over a collection of jQuery objects:

    1

    2

    3

    4

    5

    $tabs.each(function( index, element ) {

    var $element = $( element );

    // Do stuff to $element

    });

    Never use jQuery to iterate over raw data or vanilla JavaScript objects.