Conditional Structure in JScript

Conditional structures are one the most important feature in any programming language. Jscript implements the if…else statement, just like a lot of other languages. The process is simple: the if structure evaluates an expression to a truth value (true or false); if the expression is evaluated to "true", then some certain statements are called afterwards, otherwise, if the user provides an else statement, Jscript parses the statements after "else". This is how you declare such a structure:

if (expression)

statements_if;

[else

statements_else];

We placed the "else" part in brackets because it's optional, so you can use "if" without "else". Here are some examples of both structures:

if (number == 1) //tests if the variable "number" holds the value "1"

{

response = "The number is one"; //this is executed if the expression is true

}

else

{

response = "The number is not one"; //this is executed if the expression is false

}

if (color == "white") //tests if the variable "color" holds the value "white"

color = "black"; //if so, let's change the white color to black

If you have an if…else structure with only one statement in each part (if and else), then you might find it easier to use the conditional operator "?"…":". This way, you will reduce the amount of written text.

expression ? statement_true : statement_false;

As you can see, we first type the expression, then the question mark. If the expression is evaluated to true, the statement after the question mark is parsed. Otherwise, the statement after ":" is parsed. You should know that you must have both operators for the whole thing to work; so if you don't use "else" in your structure, stick to using the standard if structure.

(number = 1) ? response = "The number is one" : response = "The number is not one";


Jscript also provides a way to execute more than two block of statements based on more than two values of a single expression. This can be accomplished by using the switch statement:

switch (expression)

{

case value_1:

statements_1

case value_2:

statements_2

[ default:

statements_default]

}

"switch" tests the expression for all the specified values, then executes the statements after it has encountered the first value that is equal to the expression's result. If it doesn't find any, then it executes the default statement, if there is one. If no values match the expression's result, and there is no "default" statement specified, then nothing is executed. After it has started to run the first block of statements it continues to run also the other statements, even if they don't "belong" to the value which was equal to the expression's result. To stop it, you can use a "break" statement:

switch (color)

{

case "black":

html_color = "000000";

break;

case "white":

html_color = "FFFFFF";

break;

case "red":

html_color = "FF0000";

break;

default:

html_color = "FFFFFF";

}

blog comments powered by Disqus