Are you forced to adhere with company coding guidelines set in stone at some point in 1969? Or are your fellow developers free to express their artistic side with embedded ASCII art?

I like browsing through style guidelines. There are usually obvious rules, those which seem bizarre and a few hidden gems which you hadn’t discovered before. Unfortunately, few companies are brave enough to publish internal guidelines. The BBC revealed their documents in 2010 but Google has finally released the style guides the company uses for internal projects.

Rules are provided for C++, Objective C, Python, XML, and R — but we’re most interested in HTML, CSS and JavaScript. The documents are refreshingly short. I’ve seen too many where developers are expected to learn 1,001 arcane and subjective rules which show-off the writer’s knowledge rather than imparting useful advice.

Let’s take a closer look…


There are few surprises in the HTML style guide:

  • serve semantic HTML5 as text/html
  • separate markup, styling and scripting
  • validate your markup when possible
  • use fall-backs when technologies such as canvas aren’t supported

Google recommends shaving every byte: files should be UTF-8 encoded, trailing white space should be trimmed and you should avoid entity references such as — and ”. They even recommend omitting optional structures and closing tags, e.g.

<!DOCTYPE html>
<title>Saving money, saving bytes</title>

Uggh. I’m all for saving a few bytes but still prefer a stricter XHTML-like syntax.

Strangely, Google recommends indenting with two spaces rather than a tab. Isn’t that twice the quantity of whitespace characters you need?!


Stylesheet guidelines are dominated by further best-practice and byte-saving techniques:

  • use valid CSS unless dealing with bugs or proprietary syntaxes (vendor prefixes)
  • use short ID and class names, but ensure they’re not cryptic or presentational (e.g. #blue-button)
  • consider prefixed names for larger projects, e.g. #xyz-help, .xyz-column
  • simplify selectors when possible, e.g. #example rather than ul#example
  • use shorthand syntax notations
  • do not use quotes in url() or unit values after a zero
  • use short #abc hexadecimal color notation rather than #aabbcc
  • end every declaration with a semi-colon (even the last one)
  • avoid browser hacks

Google suggests omitting leading zeros from measurements, such as .5em. It saves a character, but I prefer code which is easier to scan.

The guide recommends a newline for every comma-separated selector which applies to a block. I tend to agree, although I’m guilty of using long lists of selector strings.

Finally, it states that property declarations should be alphabetized, e.g.

	border: 1px solid #000;
	border-radius: 6px;
	display: block;
	font-family: sans-serif;
	margin: 1em;
	outline: 0;
	padding: 10px;
	text-align: center;

Personally, I prefer to order properties in related chunks, such as block type/dimensions, fonts, text alignment, padding, margins, color, background, border and miscellaneous properties. Perhaps it would confuse some developers but I’ve used the method for many years and works for me.


Understandably, the JavaScript style guide is longer but eases you in with the basics:

  • always use var to declare variables
  • always end lines with a semi-colon
  • use standard rather that non-standard features
  • use camelCaseNames and UPPERCASE constants, but avoid the const keyword which isn’t supported in IE
  • use namespacing techniques
  • avoid eval() except for deserialization (strangely, JSON.Parse isn’t mentioned as an alternative)
  • avoid with() on objects and for-in on arrays
  • use array and object literals rather than more verbose declarations
  • be aware of truthy and falsy rules
  • do not use IE conditional comments in your JavaScript source
  • don’t modify the prototypes of built-in objects — that’s a shame since it’s one of JavaScripts more powerful features, but you know it’ll lead to problems
  • use closures carefully and do not introduce circular references
  • similarly, be careful using ‘this’

There was one unusual recommendation: don’t use functions within blocks, i.e. write:

if (x) {
  var foo = function() {}

rather than:

if (x) {
  function foo() {}

You’ll see the second syntax used everywhere. It works without problems but it’s not valid ECMAScript.

The document also mentions that wrapper objects should never be used for primitives unless you’re typecasting. It can lead to unexpected results such as:

var x = new Boolean(false);
if (x) {
	// this code evaluates

Dumb JavaScript.

Finally, the guide states you should use single quotes (‘) in preference to double quotes (“) when delimiting strings which could contain HTML attributes. I use double quotes everywhere and I’m not sure I can change the habit easily. That said, I use single quotes for static PHP strings, so perhaps I’m being picky!

The best advice is saved for the end of the documents: be consistent. Developers will rarely agree with every programming guideline but you should follow your own rules. It’ll make life easier for others trying to understand your code and when you when return to it six months later.

Do you agree with Google’s Style Guides? Does your company force you to follow strange development practices?

Tags: coding, development, documents, Google Tutorials & Articles, guidelines, HTML5 Dev Center, style
Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler

Free Guide:

How to Choose the Right Charting Library for Your Application

How do you make sure that the charting library you choose has everything you need? Sign up to receive this detailed guide from FusionCharts, which explores all the factors you need to consider before making the decision.

  • Brian Temecula

    I think that no matter where you go, there’s always a different style guide. You just have to be able to adapt. For my own projects, which are mostly PHP, I have my own style. If you come and work with me, you’ll have to adhere to it!

    • Vincent Young

      Agreed, there is always going to be variation, but some practices are better than others and we should try to promote those best practices. For example, the Google HTML/CSS style guide rule, ID and class name delimiters, suggest using a hyphen to separate words. I never use hyphens because you can not directly map names in JS. Instead I use, underscores.

      For example:
      #video-id {}

      If I wanted to cache this in JS: var video-id = document.getElementById(“video-id”); will not work because the hyphen is not valid. Bad form Peter!

      #video_id {}
      var video_id = document.getElementById(“video-id”); works just fine.

      • Robert Goula

        I agree with Vincent and follow the same practice of using underscores instead with the same reasons, but I also find it easier to ctrl-shift arrow across the entire set of words with the underscore when selecting for copy in most programs where as I usually need more keystrokes to get past the hyphens. The only exceptions to this is when I want to id something serializable and use the hyphen to separate a primary key like id=”some_type-1″, or if it is something from a framework that I am using but not necessarily in my scripting.

      • Knut

        You forgot to switch out one of the underscores, in “video-id”, but I get what you say, which certainly seems to be an important point!

      • Davide

        Using hypen is not generally seen as a problem, because when coding in Javascript you follow the general rule of using camel case syntax; thus, video-id becomes “videoId”.
        This, if you want to use the exact same name, thing that I don’t advice. If you do that, how can you distinguish a variable referring to a DOM element from another one ?
        For this reason I prefer to use the suffix “El” for variables denoting DOM elements; it helps me understanding what the code is referring to very quickly.

        videoEl = document.getElementById( ‘video-id’ );

        is much more semantic than

        videoId = document.getElementById( ‘video-id’ );

        because video-id is just a selector and doesn’t have to keep a one-to-one relation with the variable that point to the DOM element addressed by that selector.
        This approach remains consistent and shows its value when you migrate to DOM libraries like jQuery, where your selector is often composed by more than one keyword and couldn’t be used as a variable name as it is (like, for example, in ‘” or “#video-id img.portrait” )

  • Valentinas

    consistency is the key. But it should be across the team.

  • Wojciech Fornal

    On the one hand, developers are advised to save few bytes, on the other there is a constant push to abstract this and that (new JavaScript framework pops up every week ;)) that leads to loading lots of JavaScript and/or CSS code that is sometimes used only in 1% by particular site (well, that’s amenity of something interpreted in the browser, rather than precompiled and then distributed).

    There are more contradictions and incosistencies in webdev realm :/

  • McBenny

    Consistency is always the key, and I adhere to most of those rules, even if I don’t follow them exactly, it’s kinda close.
    About the order of style properties, I have another order that also has it’s logic: from the outside to the inside. That means first, what is outside the element, what may influence the full logic of the display, then the object itself. As an example:
    #myElement {
    margin:1em auto;
    border:1px solid #f00;
    This provides useful information quickly: the behaviour of your element and its relation to the context is set up in the first properties, you don’t have to parse the whole definition to see if the position of your element is due to a “margin” or a “top” property.
    Then we have the description of the element itself (border, background, padding) and at the end what concerns text formatting: text, lines, font.
    Finally the cursor property, to different from the rest to be with the element itself, but it could be with the background property…
    In fact that’s a bit of Craig’s “order properties in related chunks”, a bit of Google’s “declarations should be alphabetized”, and a bit of me ;-).

  • Petit Paul

    You are using single quotes in php for static strings because it saves the php engine the time to look at the string for possible included variables to expend, which it would do if you’d double quoted the string.

    • Craig Buckler

      Precisely. I’m careful about using single quotes in PHP but, for some reason, it feels wrong in JavaScript. That’s just me, though!

  • Chris Emerson

    Mixing tabs and spaces causes numerous problems, perhaps they think the extra whitespace characters are worth it to avoid these problems.

    • Craig Buckler

      Possibly, although I still prefer tab indenting with each tab taking 4 characters.

      • Stefan Gabos

        tabs should never be used for indenting as everybody has their editor set up differently and the code will look very different for everyone – for some “tab” is 2 spaces for others 4 spaces and so on; but a whites space character is always a white space character and will render the same no matter the editor or the OS

  • Davide

    Hi Craig,

    There are mainly 2 reasons why you should avoid defining functions inside code blocks: the first is called “scoping rules”, the second “hoisting”.
    Javascript has only functional scope, so when you declare a function inside of the “if” block (as in the example), you are really declaring the function in the containing scope. Hoisting, then, is the process of moving automatically the declaration of variables and functions to the top of the scope.

    If you write something like so:

    function test( x ) {
    if( x === 1 ) {
    var myvar = “some value”

    The JS virtual machine will see (and execute) this:

    function test( x ) {
    var myvar;
    if( x === 1 ) {
    myvar = “some value”

    This lead us to the understanding of “why” declaring a function in a code block is potentially dangerous.. if you do this:

    function test( format ) {
    if( format === ‘mp4′ ) {
    function decoder() {
    …some code…
    } else {
    function decoder() {
    ..something else…

    The second function declaration will overwrite the first one because of Hoisting (its declaration is moved to the top of the function twice, resulting in the second implementation overwriting the first one).

  • Darryl

    Overall great article. Just one minor gripe. At the beginning it says “Google has finally released the style guides”. I’ve been using the Google JavaScript style guide for reference for several months. Can you clarify what you meant by that? Was there just an official announcement?

    • Craig Buckler

      I’ve not seen an official announcement, but the documents seem to have become public knowledge in the past few weeks.

      • Anonymous

        The HTML/CSS guide has recently been released.

  • John E

    Great Post. Nice summary on their style guides.

  • Alfin

    Very interesting article. If read carefully, we can see that google always pay attention to every detail even for white space :-)

  • mkv

    There is one thing that should be obvious to anybody but even the few excerpts in the comments here reveal the fact that it is omitted. I am talking about the official language definition(s) which should NOT be a “matter of taste”. According to just about any language there should be a space in a language construct but no space in a function definition:

    Space after the keywords here:

    for (int i=0; i < 10; i++) … (Java)
    foreach ($recods as $record) …. (PHP)
    if (age < 18) (Java)
    if ($age < 18) (PHP)

    But no space here after the function name:

    private function callThis($valx, $valy)…. (PHP)
    public int callThis(int valx, int valy)…. (Java)

    The same goes for C, C++, Javascript, These definitions that can be found in the language documentation for any language is omitted by quite a few code writers which is quite a surprise. Yes, “if()” works just as well as “if ()” but that should be no excuse – especially if there is a coding standard for more trivial cases.

  • sofyan

    I think as long as things do not change the principle, I agree and wrote to remember is that Google has or googlebot crawl engine, therefore it’s easier for googlebot to crawl html, css and javascript scripts in accordance with its rules and style

  • Alex Hall

    Weirdly, the CSS guides are exactly those that I incoporate into my projects. I could be working for Google right now! Most of it sounds good to me. But I’m with you on the lazy coding aspects of HTML. For me, a stricter syntax is just better. All tags should be closed properly. Always.

  • morphics

    One reason to use spaces over tabs is to save time when copying code across systems. I’ve noticed that I save a lot of time copying and pasting Python code (using 4 spaces) versus copying and pasting PHP code (using tabs). Tabs often get handled badly, striped, or converted to spaces by terminals and editors, meaning that tabbed code often needs to be re-indented by hand. In an ideal world tabs would always be handled correctly and would be safe to use across the universe, but sadly that’s not the world in which we live.

    • Satya Prakash

      In vim, I use :set paste
      to save myself in this situation.

  • Sreenath H B

    The statement
    var x = new Boolean(false);
    uses the Boolean object and returns a Boolean object. So the following statement
    would return object.
    Thus putting the object in a conditional like:
    would infact try to do this:
    which would return the string “false” which is not equivalent to the boolean false and thus the conditional would evaluate to true.

    JavaScript isn’t dumb, its doing the right thing in the name of consistency while dealing with objects. As of JavaScript 1.3, the use of Boolean object is not recommended (and rightly so since boolean is natively supported) and the Boolean function is suggested for use if needed.

    • Craig Buckler

      Thanks Sreenath.

      In practice, no one’s ever going to use new Boolean(false) and JavaScript’s actually handling it consistently, but it is confusing and difficult to debug. Unfortunately, it’s more ammunition for the anti-JavaScript army.

Special Offer
Free course!

Git into it! Bonus course Introduction to Git is yours when you take up a free 14 day SitePoint Premium trial.