JavaScript Tutorial: Object Properties and Flow Controls

By HTMLGoodies Staff

written by Jon Perry

Object Properties

We can extend the basic variable into a very useful and well-used concept, the object. A computer object is a representation of a real-life object. We briefly looked at objects in Part 1.

We can create objects as a container for related variables. Variables of an object are called properties.

To define a JavaScript object, we use the new Object() keyword.

Once we have created a new Object, we can begin to assign properties to it. These properties behave exactly like variables, but the common object groups them.

<HTML>
<HEAD>
<TITLE>Person Object</TITLE>
<SCRIPT>
person=new Object();
person.name='David';
person.age=30;
person.sex='male';
person.height=6;
document.write(person.name+' is '+person.age+' years old, '+person.sex+', and '+person.height+' foot tall.');
</SCRIPT>
</HEAD>
</HTML>

Objects become very useful when we need have a lot of data. If we needed to catagorize 1,000 people, we would use objects.

WITH

There is a keyword associated with an object, which is WITH. WITH creates a kind of halfway reference.

The preceding example could be rewritten as (see example):

<HTML>
<HEAD>
<TITLE>Person Object with WITH</TITLE>
<SCRIPT>
person=new Object();
with (person) {
name='David';
age=30;
sex='male';
height=6;
document.write(name+' is '+age+' years old, '+sex+', and '+height+' foot tall.');
}
</SCRIPT>
</HEAD>
</HTML>

As you can see, we can drop the repeated references to 'person', because with (person) has already made the reference for us.

Controlling the Flow

We have met variables and operators. We can define variables and manipulate them. But we don't want to individually change every variable by hand. If we have to sort a list of names, we don't want to be comparing every entry against every other entry in a slow and laborious fashion.

One of the achievements of the computer is that it allows multiple operations to be performed very quickly. We can combine this with the power of mathematics to produce very impressive techniques for our code.

The general route a program takes can be altered, in computer jargon this is known as the flow of the program. We can control the flow of a program with Flow Controls. Typically this might involve sorting a list while we still have unsorted entries left in the list. A program like this is capable of sorting any length of list, which is far more useful than any manual method.

There are two basic types of flow controls, decision types and loop types. Decision types change the flow accordingly to a condition, e.g. if we wish to know how many red cars per cars there are, we look at a car and decide whether it is red or not. If it is, then we add 1 to the Red column, if not we add 1 to the Other Color column.

A loop type would perform the continual action of monitoring the cars.

A JavaScript program to do this would look like:

<HTML>
<HEAD>
<TITLE>Red Cars</TITLE>
<SCRIPT>
R=0;
for (cars=0;cars<100;cars++)
if (Math.floor(Math.random()*5)==0) R++;
document.write('There were '+R+' red cars in 100 cars.');
</SCRIPT>
</HEAD>
</HTML>

This code introduces a few JavaScript statements that we haven't met yet, namely the two methods of the Math object, floor and random. You can ignore these for now. We're simply using them to simulate car counting, producing random numbers in a similar way to throwing dice.

We are more interested in the two flow controls, for and if.

The program itself states that about 1 in 5 cars is red, and then goes on to display an actual value for the experiment.

There are several flow controls. We shall look at:
if     Makes a decision based on a condition
if/else     if/else As if, but with an alternative clause
switch     Multi-if statement
for     An iterative loop
for/in     Iterates through the properties of an object
while     Performs code while a condition is true
do/while     Performs code, and then checks for the condition being true
break     Stops execution of a loop
continue     Skips an iterate of a loop

Decision Types

IF

IF is the simplest flow control. It alters the flow of the program according to a condition. This is where we first meet the comparison operators introduced in Part 1.

The syntax for IF is:

if (condition) {…code…}

As with all the flow control keywords, we only need {} if we are to execute more than one line of code.

So, as we saw in the opening example, we can test if a car is red.

We can equally test strings, or test for different criteria. For example "is a number larger than another", for which we would use the greater than symbol (>). This could be used in a sort routine.

The if statements also introduces the logical operators, && and ||. These represent AND and OR.

When we use AND (&&), we require all conditions to be true, and when we use OR ( || ) we require at least one condition to be true.

We might want to buy a house, and the house must have at least 3 bedrooms, be under $100,000 and have a garage.

In JavaScript, the code for this would look something like:

if (house.bedrooms>=3 && house.price<100000 && house.garage==true) {…'look at house' code…}

The statement demands a house that has at least 3 bedrooms AND is priced under $100,000 AND has a garage, but we are not concerned with any other variable, such as a garden or which direction the house is facing.

OR can be used similarly. We often have to produce complicated Boolean expressions, for example if we want a green or yellow car, which is under $5,000, then we would write:

if ((car.color=='green || car.color=='yellow') && car.price<5000) {…car code…}

This may be confusing to you, but if we break it down into its components, it should become simple.

The color of the car may be green OR yellow. If we don't like the color, then we would ignore the car.

If a car is $5,000 or more, then we don't like the price, and so we ignore the car regardless of it's color.

IF/ELSE IF/ELSE


There is another extension to the IF flow control, which involves handling the alternative case.

The syntax for IF/ELSE is:

if (condition) {…code1…} else {…code2…}

If the temperature is over 20C, then we go to the beach. But what if it isn't? What do we do now?

The ELSE statement would capture this:

if (temperature>=20) {…goto beach…} else {…stay indoors…}

As the temperature is less than 20C, we stay indoors.

ELSE IF

ELSE IF can be used to differentiate between several conditions.

The syntax for IF/ELSE IF/ELSE is:

if (condition1) {…code…} else if (condition2) {…code…} else {…code3…}

For example,

<HTML>
<HEAD>
<TITLE>Else If</TITLE>
<SCRIPT>
country='England';
if (country=='England') document.write('You could visit Buckingham Palace.');
else if (country=='France') document.write('You could see the Eiffel Tower.');
else document.write('Your country is beyond this program\'s scope.');
</SCRIPT>
</HEAD>
</HTML>

The final document write in that program contained a special character - the escape character, the back-slash (\). The escape character is very useful at times; it prevents the character following it from being considered part of the computer program.

In this case, if we used an unescaped ', then it would be seen as the end of the text for the document.write() method, and this would causes an error. But we escape it first, so the ' is treated as the character ' and not as an end-of-text qualifier.

We could write our programs using ELSE IF, but it is considered messy, and we tend to use the switch statement instead. ELSE IF does have its uses though, for example SWITCH doesn't do greater/less than very well.

SWITCH

The SWITCH statement selects an option from a variable.

The syntax for SWITCH is:

switch (variable) {
case value1 : {…code1…}
case value2 : {…code2…}

case valueN : {…codeN…}
default: {…default code…}

The variable may be either a string or integer variable. The value of variable is matched against the list of values inside the SWITCH statement, and if a match is found, then the associated code is performed. If no match is found, the code associated with the default value is performed.

This does require one extra detail. If, say, value 1 is matched, then unless we do something about it, all the codes will be performed, i.e. code1, code2, … , codeN and default code will all be executed.

We prevent this be adding break as the last line in any code.

This makes code easier to follow, and more extensible (easier to update). The previous example becomes:

<HTML>
<HEAD>
<TITLE>Switch</TITLE>
<SCRIPT>
country='England';
switch (country) {
case 'England': msg='You could visit Buckingham Palace.';
break;
case 'France': msg='You could see the Eiffel Tower.';
break;
default: msg='Your country is beyond this program\'s scope.';
}
document.write(msg);
</SCRIPT>
</HEAD>
</HTML>

When case 'England' is recognized as true, the message is set, and the break transfers the execution point to the } near the end.

Loop Types

FOR

The FOR loop iterates a variable through code from an initial number to a final number with a given step.

The syntax for FOR is:

for (variable=initialvalue;condition;step size) {…code…}

initialvalue is the starting number for the loop, and the loop passes the variable to the code. The variable is then updated by the step size, and the condition is checked. If we pass the condition, the code is then executed again with the new variable, and if we fail the condition, the loop is terminated.

This is a very useful keyword, and can greatly simplify repetitive and laborious tasks.

<HTML>
<HEAD>
<TITLE>For</TITLE>
<SCRIPT>
for (number=0;number<10;number++) document.write(number+'<BR>');
for (number=19;number>0;number-=2) document.write(number+'<BR>');
</SCRIPT>
</HEAD>
</HTML>

We can rapidly display a sequence of numbers, with varying step sizes.

FOR /IN

FOR/IN is similar in principle to for, but has a completely different use. FOR/IN looks at the properties of an object, and iterates through each one.

The syntax for FOR/IN is:

for (property in object) {…code…}

This can be seen in practice by re-examining the very first example in this article, the person object. We can remove the document.write() statement, and replace it with:

for (property in person) document.write(property+' has the value '+person[property]+'<BR>');

WHILE/DO WHILE

These two keywords are very similar, the difference between them is that DO WHILE always executes its code at least once, whereas WHILE may not.

The syntax for WHILE is:

while (condition) {…code…}

The syntax for DO WHILE is:

do {…code…} while (condition)

If the condition starts out false, then WHILE will never reach its code. DO WHILE, on the other hand, will.

This can be seen using a very simple demonstration.

<HTML>
<HEAD>
<TITLE>The Whiles</TITLE>
<SCRIPT>
document.write('while');
x=0;
while (x++<9)
document.write(x);
document.write('<BR>');
document.write('do while');
x=0;
do
document.write(x);
while (x++<9);
</SCRIPT>
</HEAD>
</HTML>

The While code iterates before writing, but the Do While writes first, then iterates. The results for each are slightly different, but note that both accept x reaching 9.

BREAK/CONTINUE

BREAK and CONTINUE provide more flexibility for our loops (and SWITCH if you count SWITCH as a decision/loop hybrid).

As we have seen, BREAK stops a loop immediately, and moves the current execution point to the end of the loop. CONTINUE will just skip an iteration, and continue the loop as normal.

These two keywords are stand-alone keywords.

<HTML>
<HEAD>
<TITLE>Break</TITLE>
<SCRIPT>
for (number=0;number<10;number++)
if (number==5) break; else document.write(number+'<BR>');
</SCRIPT>
</HEAD>
</HTML>

We only see 01234. When number is equal to 5, the loop is broken and terminated.

If we change the break to continue, then we would see 012346789 instead, with 5 missing, because when number equals 5, we skip the iteration.

This article originally appeared on WebDevelopersJournal.com.



Make a Comment

Loading Comments...

  • Web Development Newsletter Signup

    Invalid email
    You have successfuly registered to our newsletter.
  •  
  •