JavaScript branches and conditions Free Web Design Tutorials
Home   HTML CSS JavaScript PHP MySQL Usability Glossary
JavaScriptBasicsRunning a ScriptVariablesExpressions and OperatorsObjects.Properties.MethodsThe Date ObjectStringsRegular ExpressionsDefining RegExp PatternsJavaScript Branches and ConditionsBranches and ConditionsLoopsArraysArray MethodsSorting ArraysUser-Defined FunctionsCookiesWindowsFrames

Home > JavaScript > Branches and Conditionsprinter version

Branches and Conditions

Like other high-level languages JavaScript offers control structures to branch to different statements depending on whether expressions return true or false.

The two statements supported are if, with an optional else clause, and switch with two or more case clauses.

The if ... else Statement

The if statement tests whether a condition is true, and if so, executes one or more statements.

Example of a Simple if Statement
<script language="javascript" type="text/javascript">
    var number = 12;
    if (number < 20)
        document.write("This number is less than 20");
</script>


If more than one statement is to be executed then they must be surrounded by braces.

if Statement with Braces
<script language="javascript" type="text/javascript">
    var number = 12;
    if (number < 20)
    {
        document.write("This variable is less than 20");
        document.write("Or even less than twenty");
    }
</script>


The optional else clause is used to execute a statement or group of statements if the expression evaluates as false.

if ... else Statement
<script language="javascript" type="text/javascript">
    var number = 12;
    if (number < 20)
    {
        document.write("This variable is less than 20");
    }
    else
    {
        document.write("This variable is equal to or greater than 20");
    }
</script>


In the example above the braces were optional but with more than one statement they are required.

If a series of conditions need to be tested then if ...else can be nested or the elseif can be used but this can lead to long-winded unreadable code. A better alternative is the switch statement.

The Switch Statement

The expression to be tested goes within the switch statement and each of the possible values that the expression can take is listed as a case followed by the statement(s) to be executed if the case is true.

Example of the Switch Statement
<script language="javascript" type="text/javascript">
    var number = 2;
    switch (number)
    {
        case 1:
            document.write("The number equals 1");
            break;
        case 2:
            document.write("The number equals 2");
            break;
        case 3:
            document.write("The number equals 3");
            break;
        default:
            document.write("The number doesn't equal 1, 2 or 3");
    }
</script>


There are three things to remember about the switch statement.

  1. Each case must end with break otherwise whatever case statements follow the one picked will be executed as well the required one.
  2. A default case should be included to cover any case not mentioned or the construct will "fall through" to the statements following the switch construct.
  3. Values in case statements may be literals or variables (Boolean, floating-point or string) but not arrays, objects or functions.


Conditional Expressions

A number of conditions can be tested for within an if statement.



Note: A common mistake is to use the = assignment operator in place of the == equality operator which always results in true.

Also because of JavaScript's loose typing, the expression 10 == "10" will evaluate as true despite being different types.


Using Boolean Operators

Expressions can be combined using parentheses and used with the Boolean operators && (and) and || (or).



Examples of Boolean Operators
<script language="javascript" type="text/javascript">
    //Will output only if both conditions are true
    if (name == "Fred" && age == 40)
    {
        document.write ("Congratulations on being 40 Fred.");
    }

    //Will output if either condition is true
    if (name == "Fred" || name == "George")
    {
        document.write ("You're either Fred or George.");
    }
</script>


Multiple expressions can be used with combinations of Boolean operators and the use of parentheses although the larger they are the more tortured the logic can become.

The identity Operator

This is denoted by === and only returns true if the expressions evaluate as equal and the arguments are of the same type.

The non-identity Operator

This is the opposite and is denoted by !== and returns true if the arguments have different values or are of a different type.

For example if var_1 = 10 and var_2 = "10" are compared then they will not return true since one is an integer and the other a string.

The not Operator

Any Boolean expression can be negated with an exclamation mark!

Example of the not Operator
<script language="javascript" type="text/javascript">
    if (variable == 10)
    {
        document.write ("This variable equals 10.");
    }

    //The code above produces the same result as the code below.

    if (!(variable != 10))
    {
        document.write ("This variable equals 10.");
    }
</script>


Previous - Defining RegExp Patterns Previous - Defining RegExp Patterns     Next - Loops Next - JavaScript Loops


Privacy | Terms | Contact | Links | Sitemap | RSS Feeds RSS and JavaScript Feeds
©2009 www.webdesignworkmate.co.uk all rights reserved 
Design and Production by smallbizonline website design © 2000-2009
Valid HTML 4.01! Level Double-A conformance icon, W3C-WAI Web Content Accessibility Guidelines 1.0Valid CSS!
Recommended Reading
Javascript the definitive guide

Javascript and DHTML cookbook

Pro javascript techniques

simply javascript