Curly Brackets

You've already seen curly brackets used in declaring a Function:

function someFunction() {
      alert("This is what's in the Function.");
      alert("This is something else in the Function.");
}

Curly brackets are also used in "if" statements and "for" loops.

Curly brackets always mean the same thing--that the lines of code between them all belong together. In the case of an "if" statement, you may want to execute several lines of code if the test condition is true. Curly brackets are used to enclose these lines of code, so that they are all executed in response to the single "if" statement.

In the case of a "for" loop, you often want to repeat several lines of code together. To do this, you enclose these lines of code in brackets following the "for" statement.

Formatting code in brackets

It's customary to indent lines of code that are contained in curly brackets (using the tab key). As you may have noticed, we do this with the lines of code inside Functions. Often, you can end up "nesting" bracketed statements within other bracketed statements. It makes it easier to keep track of things if you add an extra indentation after each opening bracket and remove an extra indentation after each closing bracket.

Here's an example using nested "if" statements:

function someFunction(x) {
      if (x > 5) {
            alert("It's greater than 5.");
            if (x < 10) {                  
                   alert("And it's less than 10.");
            }
      }
}

Notice that lines of code that end in a curly bracket don't require a semi-colon at the end.

If you've worked a lot with tables in HTML, then you know how important it is to keep track of opening and closing curly brackets. If you use an opening bracket inside another pair of brackets, be sure the corresponding closing bracket is also within the the same outer pair of brackets. Also, double check to make sure that you have one closing bracket for every opening bracket when you're done writing a Function.

The indenting convention described above will help you keep track of things.