Coding standards

Most projects have coding standards. They make code look the same in every file, making it predictable, and easy to read.

We'll use some basic coding standards for HTML, CSS, and JS.

HTML

Indenting

A standard we'll follow is indentation by four spaces. When a tag is inside another tag, use indenting to make containership clear. For example:

<div id="output-container" class="hide-on-load">
    <p>I have a bracelet. It says:</p>
    <p>What would <span id="character">Scooby Doo</span>?</p>
</div>

Remember, the <div> is a wrapper for the two <p> tags. It contains them. We'll indent the inner tags.

The <span> is an exception to the indenting rule, because it's an inline tag, while <div> and <p> are block tags. We don't care about the difference between inline and block tags. Just remember that <span> doesn't need to be indented.

By the way, WebStorm and other IDEs indent automatically. Type <div> into WebStorm, press Enter, and see what happens.

Naming

When you give tags ids and classes, use names that suggest what the tags mean, or how they will be used. Here's some HTML:

<div id="this-thing" class="do-it">
    <p>We should make a t-shirt that says:</p>
    <p>My <span id="some-text"></span> is the best!</p>
</div>

The ids and the class don't tell you anything. Now check this out:

<div id="output-container" class="hide-on-load">
    <p>We should make a t-shirt that says:</p>
    <p>My <span id="pet"></span> is the best!</p>
</div>

The id output-container suggests that this is an output area, and that it contains multiple elements. The class hide-on-load suggests that the element won't be visible when the page loads. The id pet maybe contains the name of a pet.

Better.

Make ids and classes lowercase. If they are multi-word, like output-container and hide-on-load, use dashes (the – characters) to separate the words. This is a common way to do things in web development.

Comments

You can add comments to HTML. For example:

<!-- Navbar is injected from library/includes/navbar.html -->
<div id="navbar"></div>

The comment reminds you what the <div> is for.

CSS

Indent

Indent by four spaces between the braces (the {}) of a CSS rule.

You've already seen this in action:

#output-container {
    color: green;
    font-size: 150%;
    border: thin solid magenta;
}

WebStorm and other IDEs indent CSS automatically.

Comments

Comments explain what a CSS rule is for. For example:

/*
  Use this class on elements that are to be hidden when the page loads.
*/
.hide-on-load {
    display: none;
}

Notice that the syntaxes of HTML and CSS comments are different.

HTML comment: <!-- Comment goes here. -->
CSS comment: /* Comment goes here. -->

JS

Indent

Indent code by four spaces inside braces (the {}, remember). For example:

/**
* Record new expenses.
*/
CoffeeChocolate.recordNewExpenses = function() {
    //Process new coffee expense.
    var newCoffeeExpense = $("#newCoffeeExpense").val();
    //Anything found?
    if ( newCoffeeExpense != "" ) {
        //Something in the coffee field.
        //Check that it is not negative.
        if ( newCoffeeExpense < 0 ) {
            alert("Sorry, coffee expense cannot be negative. (Wish it could be.)")
        }
        else {
            //Coffee expense is OK.
            coffeeExpense += parseFloat(newCoffeeExpense);
            localStorage.setItem("coffeeExpense", coffeeExpense.toString());
        }
    }
    ...
}

(What this code does isn't important. You'll see that later.)

Each time there's an opening brace (a {), add indenting. Each time there's a closing brace (}), remove it.

BTW, IDEs automatically indent JS.

Comments

Comments in JS are very important! They explain what the code does. When someone wants to change the code in the future, they'll need comments to understand it.

Here's that code again. Check out the comments.

/**
* Record new expenses.
*/
CoffeeChocolate.recordNewExpenses = function() {
    //Process new coffee expense.
    var newCoffeeExpense = $("#newCoffeeExpense").val();
    //Anything found?
    if ( newCoffeeExpense != "" ) {
        //Something in the coffee field.
        //Check that it is not negative.
        if ( newCoffeeExpense < 0 ) {
            alert("Sorry, coffee expense cannot be negative. (Wish it could be.)")
        }
        else {
            //Coffee expense is OK.
            coffeeExpense += parseFloat(newCoffeeExpense);
            localStorage.setItem("coffeeExpense", coffeeExpense.toString());
        }
    }
    ...
}

There are two comment styles in JS:

  • Multi-line
  • Single-line

A multi-line comment can be as long as you want:

/**
* Record new expenses.
*/

Multi-line comments are often used before functions, to explain what functions do. The multi-line style is used at the top of a function, even if the comment has just one line, like the example you just saw. Multi-line comments help break up the code, so you can tell when new functions start.

Every line beginning with // is a single-line comment. The browser ignores everything from the // to the end of the line.

When do you add single-line comments? A good rule-of-thumb is to think about adding a comment every time you add a {.

You don't have to add comments for every piece of code. For example, look at this:

//Check that it is not negative.
if ( newCoffeeExpense < 0 ) {
    alert("Sorry, coffee expense cannot be negative. (Wish it could be.)")
}

It's clear what that one alert() statement does, so I didn't add a comment before it.

However, I did a comment before the if, explaining what it does.

Variables names

Two things here. First, a variable's name should help you understand what the variable is for. This is important!

For example, this could be from an app for a K12 school:

if ( a < 13 ) {
    $("#f").show();
}

Huh? What is a? What is f? No idea.

Here's another version:

if ( studentAge < 13 ) {
    $("#parent-permission-slip-message").show();
}

Aha! If a student is less than 13 years old, then show a message, that we need a permission slip from a parent.

The code is easier to understand.

The other thing about variable names is that they are camel case. The first character is lowercase. If a variable name is multi-word, like studentAge, start each part with an uppercase character.

Summary

  • In HTML:
    • Indent wrapped elements, except for <span>.
    • Give ids and classes meaningful names.
    • Makes the names lower case, with dashes separating words.
    • Comments are good.
  • In CSS:
    • Indent CSS rules.
    • Comments are good.
  • In JS:
    • Indent code wrapped in braces. Braces wrap code, making code blocks.
    • Comments are very good.
    • Use meaningful variable names.
    • Use camelCase variable names.