JavaScript Chapter 3 Javascript Programming Basics


Javascript Variables

In programming terminology, a variable is a storage area. You store things in variables so that you can retrieve them later. Think of variables as small boxes. You can write a number on a piece of paper then place that piece of paper in a box. Write a label on the box, such as "Mom's phone number", and you'll have a quick way to identify what kind of information you have stored in the box. One day, you might even decide to phone Mom. If so, you can quickly locate her phone number by looking at the label on the box and pulling out the piece of paper with her number on it.

In Javascript, when you're setting up a variable you start with the letters var (short for variable, of course). After a space, you then need to come up with a name for your variable (like "Mom's phone number"). The name can be almost anything you want. But there are some important considerations. These:
  • You can't have spaces in your variable
  • You can't start your variable name with a number
  • The variable should contain only letters, numbers ( but not the first character of the variable), a dollar sign ($) and an underscore ( _ )
Here are some valid variable names:
number1
moms_phone_number
$firstName
And here are some that will get you into trouble:
1number
moms phone number
"firstName"
For the ones that will get you into trouble, the first variable starts with a number, the second one has spaces, and the third is surrounded with double quotes.
To store something in a variable, you use an equals symbols ( = ). You can store numbers, strings of text and Boolean values in a variable. (Boolean values are Yes/No, True/False, 1 or 0.) These three, numbers, strings, and Booleans, are called primitive data types. As well as the primitive data types you can also store objects in variables, objects like the Window, Navigator, and Document objects you met earlier.
Let's get some practical work done, though.
Create a new web page for this. You can use the template you created in an earlier section. Add the Javascript tags to the HEAD section of the HTML. In between the Javascript tags, set up the following three variable and their values:
var number1 = 42;
var true_or_false = true;
var firstName = 'Kenny';
Your web page should then look like this:
Javascript code setting up three varaibles
So we have three Javascript variables set up, all starting with the keyword var. The first variable stores the number 42, the second one stores a value of true, and the third one stores the text 'Kenny'. Notice that the first two variables, the number and the Boolean, don't need any quote marks. The third one does, however: if you want to store strings of text they need to go between quotations marks, either single quotes or double quotes, but not a mixture of the two.
Now add the following write lines to your code
document.write( number1 + "<BR>" );
document.write( true_or_false + "<BR>" );
document.write( firstName + "<BR>" );
So we're using document.write to see what's inside of the variables. (The + "<BR>" is just so that each variable will be printed on a line of its own.)
Your Javascript should look like this:
Javascript code using varaibles and document.write
Make sure you end each line with a semicolon ( ; ). Make sure, too, that you have a space between var and the variable name. You don't actually need a space to the left and right of the equal symbol, but it helps to make your code more readable.
Save your work and load your web page in a browser. You should find the following written to your page:
42
true
Kenny
So what just happened? Well, we stored three values in three variables. We retrieved these values by just using the variable names. For example, if you had the code alert( number1) the alert box would display the value 42, which we stored in the variable we called number1. In other words, to get at the value itself, you just use the variable name.
You can use concatenation with variable names. For example, you can do this:
document.write( "The variable has a value of: " + number1 + "<BR>");
Here, we've combined the text "The variable has a value of: " with the variable name number1. We did the combining (concatenation) with the plus symbol ( + ). Try it yourself. Amend your document.write code so that it looks like our below:
document.write( "The variable has a value of: " + number1 + "<BR>");
document.write( "Is it true or false? " + true_or_false + "<BR>");
document.write( "What's your first name? " + firstName + "<BR>");
Make sure you get the quotation marks and the plus symbols in the right place, otherwise your code won't work. (You don't have to use double quotes, single quotes work just as well. You can't have a double quote at the start, though, and a single quote at the end.)
The results in a browser should look like this:
Output of Javascript variable code

 

Variable Assignment

When setting up a variable, we did this:
var number1 = 42;
But you don't have to store a value in the variable all on the same line. You can use two lines instead:
var number1;
number1 = 42;
The first line here creates a variable called number1. But there's nothing stored in it. The second line is where we store something in the variable. Note that the var has now gone missing - you only need to use var once when you're setting up your variables.
You can also assign a different value to a variable. For example, you can do this:
var number1;
number1 = 42;
number1 = 100;
Javascript is a sequential programming language, meaning lines get executed from top to bottom. What we've done above is to first assign a value of 42 to the variable called number1. The third line stores a new number in this same variable. The two are not added together. When you assign a new number to a variable, it will erase the old contents. So the variable number1 will now hold a value of 100.
You can also overwrite the number 42 with a string of text. Like this:
var number1;
number1 = 42;
number1 = "one hundred";
This time the text "one hundred" is stored in the variable called number1, even though previously the variable held a number. Other languages wouldn't let you do this. If you set up a variable to hold a number then an error would be raised if you tried to store text in it. Javascript, however, doesn't care.

Mathematical Operators

You can use the mathematical operators with variables. This allows you to add up, multiply, subtract, and divide. The mathematical operators are these:
  • The plus symbol ( + ) is used for addition
  • The minus symbol ( - ) is used for subtraction
  • The asterisk symbol ( * ) is used for multiplication
  • The forward slash symbol ( / ) is used for division
  • The percentage symbol ( % ) is used for modulus calculations
To get some practice with these symbols, create a new web page. Or you can reuse the one fromthe previous section. Add the two Javascript tags in the HEAD section. Between the two Javascript tags add the following code:
var number1 = 42;
var number2 = 100;
var total;
total = number1 + number2;
document.write( total );
Your code should then look like this:
Javascript code using the math operators
Save your work and load the page in a browser. You should see the number 142 written to the page. (If you don't see anything, check your code to make sure it looks exactly like ours.)
What we did here is to store the numbers 42 and 100 into two different variable, number1 andnumber2. We then set up a third variable called total. On the fourth line of the code we have this:
total = number1 + number2;
To the right of the equal sign are our two variables, with a plus symbol between the two. The plus symbol this time doesn't mean join together (concatenate). This time the plus symbol means "add up". Javascript doesn't get confused because the contents of both variables are numbers, and it knows it should be adding them up, not concatenating.
As an example of the above, try putting quote marks around the 100:
var number2 = "100";
When you save your changes and refresh the page in the browser, you'll see it writes this:
42100
Putting quotes around the 100 turns it into text. Now that one of the variables is text and the other is a number, Javascript concatenates the two rather than adds them up.
Exercise
Remove the quote marks from around 100. Change the plus symbol into a minus symbol. Save your changes and refresh the page in your browser. What total do you get now?

Exercise
Change the minus symbol into the symbol for multiplication, an asterisk symbol (*). Save your change and refresh the page in your browser. What total do you get now?

Exercise
Change the plus symbol into the symbol for division. Save your change and refresh the page in your browser. What's the new total?
You can use normal numbers with the mathematical operators. In the code below, we're adding up two numbers and storing the result in a variable:
var result;
result = 12 + 24;
document.write( result );
Javascript will add up the numbers on the right of the equal sign. When it has finished adding, it will store the result in the variable on the left of the equal sign.

Storing Javascript Objects in Variables

In the previous section we used an alert message and document.write with the various objects. This kind of thing:
alert ( window.innerWidth );
But you can store these values in variables as well. If you want to store the innerWidth value, for example, you can do it like this:
var width = window.innerWidth;
Once you have the value stored in a variable you can do other things with it later:
alert( width );

Operator Precedence

You can have more than two number for your math, of course. You can even mix variables and actual numbers. Change the total line of your code to this:
total = number1 + number2 / 2;
This time, we have a division symbol and a 2 at the end. What do you think will happen when you run this code? You may think that Javascript adds up the two values in our variables first and then divides by 2. But it doesn't.

To clarify what it is you want to do, you can use round brackets. If you want to do the addition first then the division, surround the addition with round brackets. Like this:
total = ( number1 + number2 ) / 2;
Now Javascript will do the sums between the round brackets first. When it's found an answer it will then divide by 2.
If you wanted to divide the second number by 2 then add that to the first number you just rearrange the round brackets:
total = number1 + ( number2 / 2) ;
The reason you need to do this is because of something called Operator Precedence. This just means which mathematical symbols get taken care of first. Take the following code:
var result = 5 + 3 * 8
The multiplication operator ( * ) has a higher priority than the plus symbol. Because the 3 and the 8 are together, Javascript thinks you want to multiply these two numbers first. After it multiplies 8 by 3 to get 24 it will then add the 5 at the start. Parentheses (round brackets) are used as a way to override this operator precedence. So if you want to add 5 plus three first, then multiply by 8, you'd do it like this:
var result = (5 + 3) * 8
The result would now be 64 ( 5 + 3 equals 8, then multiply by 8).
Division and multiplication have equal priority. These two in turn have priority over addition and subtraction which, again, have equal priority. To clear up what this means, take a look at the following:
var result = 32 - 16 / 8
Because division has a higher priority than subtraction the first thing Javascript does is to divide 16 by 8 to get 2. It then subtracts the 2 from 32 to get an answer of 30.
Now put some round brackets in:
var result = (32 - 16) / 8
This time, Javascript will see the parentheses and do this calculation first. 32 minus 16 is 16. This is then divided by 8 to get an answer of 2.
Now take this sum:
var result = 32 - 16 + 8;
Because addition and subtraction have the same priority the sum is calculated from left to right, giving an answer of 24. However, put some round bracket in and you get a different answer:
var result = 32 - (16 + 8);
In the sum above, Javascript will do the sum between the round brackets first, returning an answer of 24 (16 + 8 = 24). This is then subtracted from 32 to give a result of 8.
The moral of all this, then, is be careful of your mathematical operators: they might not give you the answer you were expecting.
The only other operator we haven't discussed is the modulus operator ( %). If you're not sure what this is, it's when you divide one number by another but keep the remainder. For example, in normal division 31 divided by 10 gives an answer of 3.1. In other words, 10 divides into 31 three times with one left over. Modulus keeps the 1 and throws away the rest. Why is this interesting? Because you can tell if a number is odd or even with modulus. All you need to do is divide any number by 2. If there's no remainder then you know the number is even. If there is a remainder then the number is odd. Here's some code to examine:
var result = 31 % 2;
if (result == 1) {
document.write("Odd number");
}
else {
document.write("Even number");
}
Although you haven't done IF statements yet, you should be able to figure out what's going on. First we test a number using the modulus operator. We then say IF 31 MOD 2 has a value of 1 then write "Odd number", ELSE write "Even number".


Javascript and IF Statements

Javascript is what's known as a sequential programming language. This means that each and every line of code is executed from top to bottom. Quite often, however, you don't want every line to execute - you'll want more control over the way your programmes work.
One way to control the flow of your code is with conditional logic. Conditional logic is all about what happens IF a condition is met or not met. For example, you may have an email text box on a form that you want your users to fill in. You don't want this text box to be empty when the user click the SUBMIT button. So you need a way to say "IF the email address is missing THEN don't send the form". You do this with IF Statement.

IF Statements

You can use an IF Statement to control the flow of your Javascript code. An IF Statement will evaluate to either true or false. They look like this:
if ( condition_to_test) {
}
So it's just the word "if" in lowercase. Next comes a pair of round brackets. In between the round brackets you need a condition to test. The condition will be evaluated and checked if it's true. If your condition is true then whatever code you have between a pair of curly brackets will get executed. IF your condition is false then the code between the curly brackets will be ignored. Take the following code as an example:
var first_name = "Kenny";
if ( first_name == "Kenny" ) {
document.write( "First Name is Kenny " + first_name );
}
The first line of the code stores the text "Kenny" into a variable called first_name. Next we have our IF Statement. The condition we're testing is between the round brackets:
first_name == "Kenny"
So we're checking to see whether or not the variable called first_name contains the word "Kenny". Notice that we now have two equal symbols (==) between the variable we want to check and the text we are checking for. The double equal symbols mean "has a value of". It's not assigning a value "Kenny" to the variable, like it would if there were only one equal symbol. The whole line, then, reads like this: "IF the variable called first_name has a value of Kenny". Javascript will test the truth of that statement. IS it true, or is it false? It is indeed true. In which case Javascript can go ahead and execute the code between the curly brackets.
In fact try that code out. Create a new web page from your template. Type the code above between your two Javascript tags. Your code should then look like this:
Javascript code showing an IF statement
Make sure you have the correct format for the new if statements (the correct syntax, as it's called). The first line, the one that starts with var, needs a single equal sign ( = ). This is because we're assigning a value of "Kenny" to the variable. In between the two round brackets of the IF statement, however, you need two equal signs (==). They mean "has a value of". You also need two curly brackets for IF statements. In between the curly bracket is where your code goes.
Save your work and test the results in a browser. You should see the following printed to your page:
First Name is Kenny Kenny
So we have Kenny written twice. The first time is because we typed "Kenny" between a pair of double quotes. The second time is because Javascript writes whatever is in the variablefirst_name. To see why you need two double equal symbols, delete one of them from between the round brackets of the IF statements. Now change "Kenny" to "Lenny":
if ( first_name = "Lenny" ) {
Save your changes and run the code again. This time, you'll see the following:
First Name is Kenny Lenny
Even though we assigned a value of "Kenny" to the variable in the first line (var first_name = "Kenny") Javascript has changed it to "Lenny". This is because we changed the double equal signs to a single equal sign in the IF statement. This assigns a new value to the variable.
So be careful when typing out your conditions between the round brackets of an IF statement: two equals signs checks a value, just one assigns a value.

You can also add an else part to your IF statements. This is for when you want to say what should happen if your IF Statement evaluates to false. As an example, change your code to this:
var first_name = "Benny";
if ( first_name == "Kenny" ) {
document.write("First Name is " + first_name);
}
else {
document.write("First Name is " + first_name);
}
The first line of the code has changed "Kenny" into "Benny". Between the curly brackets we now have:
document.write("First Name is " + first_name);
Look at the else part we've added, though:
else {
document.write("First Name is " + first_name);
}
If you add an else part, it needs its own pair of curly brackets. Miss one out and your code won't work. Between the curly brackets is where you type your code.
Save your changes and run your code. You should see this written to your browser:
First Name is Benny
So the first part of the IF Statement checks the condition between the round brackets. If it's true, the code for its pair of curly brackets will get executed. c If it's false then Javascript will jump to the else part. The code for the curly brackets of else will then get executed.

IF … ELSE IF

You can add another condition to test. This is done with ELSE IF. The syntax is this:
if ( first_condition_to_test ) {
}
else if ( second_condition_to_test ) {
}
Notice that else if is two words. If you type it as one word (elseif) then your code won't work. So it's just another IF statement with the word else in front of it.
You can add as many else … if parts as you need:
if ( first_condition_to_test ) {
}
else if ( second_condition_to_test ) {
}
else if ( third_condition_to_test ) {
}
Each condition you add will be evaluate to true or false. If Javascript finds a true value then it will execute any code between the curly brackets that go with it. After that, it will exit the IF statements altogether. So if the second else if above is true then its code gets executed. The third else if will be skipped and your programme will continue on its way.
You can also add an else right at the end, to catch anything you haven't checked for:
if ( first_condition_to_test ) {
}
else if ( second_condition_to_test ) {
}
else if ( third_condition_to_test ) {
}
else {
}
And here's an example of else if for you to try out:
The first line now assigns a value of "Jenny" to the first_name variable. You should be able to guess what gets executed.
Exercise
Change Jenny to "Kenny", then "Benny", then "Lenny" just to check what gets printed out. Now change "Benny" to "benny" (lowercase for the first letter). What do you think will print out? Is Javascript case sensitive here, or not case sensitive?

Nested If Statements

You can nest one or more IF statements. Supposing you wanted to test a variable to see what value it holds. But you also want to do further tests on it. You can do this kind of thing:
if ( x > 1) {
if ( x == 2) {
}
else if (x == 3 ) {
}
}
In the code above, we're first testing if the variable x is greater than 1. But we want to narrow it down even further. If it is indeed greater than 1 then a nested if … else statement gets executed. This further scrutinises the x variable.

To get the best out of the IF Statements, you'll need the use of something called comparison operators.

Javascript Comparison Operators

The IF statements you have used so far test a condition for true or false. They have used the double equal sign (== ). But there are other operators you can use besides the double equal sign. These are known as comparison operators. Here are some more of them. Remember, all these evaluate to either true or false.
!=    Is not equal to
>    Greater Than
<    Less Than
>=    Greater Than or equal to
<=    Less Than or equal to
===    Is exactly like and is of the same variable type as
To try then out, change the code between your two Javascript tags to this (or create a new one, if you prefer):
<SCRIPT LANGUAGE = "Javascript">
var over_eighteen = true;
if (over_eighteen != true) {
document.write("You're too young - go away!");
}
else {
document.write("You've passed the age test!");
}
</SCRIPT>
So this script places a value of true in a variable called over_eighteen. We trying to see what's in this variable with the help of an if … else statement. In between the round brackets of IF we have this:
over_eighteen != true
This reads "If over_eighteen does not equal true". So we want something to happen if our variable does not contain what we're looking for. Except, it does contain a value of true. So Javascript will skip this part and jump to the else part. The else part writes the text "You've passed the age test!" to the browser.
Save your work and test it out. Now change var over_eighteen = true to var over_eighteen = false. Save and rerun the script in your browser. You should see the message "You're too young - go away!".
Now try this script:
<SCRIPT LANGUAGE = "Javascript">
var available_width = window.innerWidth;
if ( available_width > 800 ) {
document.write("Show large image");
}
else {
document.write("Show small image");
}
</SCRIPT>
The first line gets the Inner Width available to the browser. We want to check what this is. Our IF statement uses the Greater Than operator ( > ) to check if the value in the available_width variable is more than 800 pixels. (If we wanted more precision we could have used the >= operator, which means Greater Than or Equal To.) If the condition evaluates to true (it is more than 800) then we'll show a larger image. However, if the condition evaluates to false then we'll show the smaller image.

Exercise
Reduce the size of your browser. Refresh the page and see what happens. If you reduce your browser to below 800 in width then the else part of the IF statement should execute.
Exercise
Change the Greater Than symbol to a Less Than symbol. Change the document.write messages to suit.
The final operator on the list is this one ===. So it's three equal signs, this time. The three equal signs are called the identity operator. This is used when you want to check a variable for equality and that it's of the same variable type. For example, take the script below:
var identity = 17;
if (identity === 17) {
document.write("variable is the number 17");
}
else if (identity == 17) {
document.write("variable is the text 17");
}
If you run the script, the first IF statement will evaluate to true, meaning that the variable does indeed hold a value of 17 and that its variable is the number type. However, change the first line to this:
var identity = "17";
We've now surrounded the number 17 with double quotes, turning it into text. When the code is run again, the else if part of the statement now evaluates to true, while the first part evaluates to false.
So you get more precision with the treble equal sign than you do with the double. Try not to worry too much about it, though: we'll use the double equal sign unless we really need the treble one.

The Ternary Operators

If you want a quick IF statement then you can use something called a ternary expression. This uses a question mark ( ? ) and a colon ( : ). The syntax is this:
var result = condition_to_test ? "TRUE" : "FALSE";
Here's a coding example:
var over_eighteen = true;
var result = over_eighteen ? "Truth" : "False";
document.write(result);
First we set a value for the variable over_eighteen. This condition is tested before the question mark. If it's true, the text before the colon gets placed in the result variable. If it's false the text after the colon will be placed in the variable.
We won't be using the ternary operators though. But they're there if you're feeling adventurous!

Javascript Logical Operators

Operators you will want to use with your IF Statements are the logical ones. The logical operators give you more options for your IF statements. There are only three to get the hang of:
&& Two ampersands mean AND
|| Two pipe characters mean OR
One exclamation mark/point means NOT
As an example, create the following code for a web page: (You can use your basic template, whichyou created earlier.)
Javascript code showing logical AND
So we start out by setting up two Boolean variables:
var cookies_enabled = true;
var javascript_enabled = false;
We then want to check what's in these two variables. The IF statement does this with the aid of the two ampersands ( && ) between the round brackets:
if ( cookies_enabled && javascript_enabled ) {
Notice the shorthand way to check Boolean variables:
cookies_enabled && javascript_enabled
We could have done this:
cookies_enabled == true && javascript_enabled == true
But if you're checking Boolean variables you can miss out the == true. Javascript will then think you're checking for a true value, which you are. So the whole line reads "IF cookies_enabled equals true AND javascript_enabled equals true".
If both are indeed true then the whole statement between the round brackets becomes true. In which case, the first document.write will get executed. However, if just one of these turns out to be false then the whole statement becomes false. In which case, the else part will be executed.
Once you've finished typing the script, try it out. Now change javascript_enabled = false tojavascript_enabled = true. Save the changes and refresh the web page in your browser. You should find that the first document.write will be printed.
The OR operators ( ||) allow you to check if just one of the values is true. (On a UK keyboard the OR operators are just to the left of the Z key. Hold down a SHIFT key first.) Change your IF statement to this:
if ( cookies_enabled || javascript_enabled ) {
The whole line now reads "IF cookies_enabled equals true OR javascript_enabled equals true".
Set cookies_enabled to false on the first line of your code. Save your changes and rerun your script. You should find that, again, the first document.write will be printed. Set both variables to false and the else part will be executed.
So with the OR operators just one part of the IF needs to evaluate to true and the whole statement will be true.
Let's have one more example just to clear things. Change your script to this:
var age = 24;
if ( age >= 18 && age <= 30 ) {
document.write("Between 18 and 30");
}
else {
document.write("Not Between 18 and 30");
}
This script checks to an age range. First we set a variable called age to a value of 24. We then use an IF statement to see what's in the variable. Between the round brackets we have this:
age >= 18 && age <= 30
This reads, "IF age is greater than or equal to 18 AND age is less than or equal to 30". If both those things are true then the whole statement becomes true, and the first document.write gets executed. If just one of them is false then the whole statement becomes false. To illustrate that, change the age variable from 24 to 14. Save the change and refresh the page in your browser. You should find that the else part gets executed.
Exercise
Add an ELSE IF part to your code. Make this ELSE IF part check the age ranges 13 to 17.

The NOT Operator

You saw above the shorthand way to check for true values:
if ( cookies_enabled && javascript_enabled ) {
This saves you having to type cookies_enabled == true. You can do this because by default Javascript will check your Boolean variables for a true value. If you want to check for a false value, you can use the NOT operator. (The NOT operator is just an exclamation mark/point.) Examine this code:
if ( !cookies_enabled) {
}
Now the cookies_enabled variable has a NOT operator before it. By default, Javascript will check for a true value. By placing a NOT operator before a Boolean value you're saying "If NOT true". If something is not true then it's false. In other words, if you want a quick way to check for a false value, type an exclamation mark before your Boolean variable.
A popular use of the NOT operator is to toggle a Boolean to either true or false. It's done like this:
bool_value = !bool_value;
On the right hand side of the equal sign the NOT operator flips the value. Once Javascript has flipped the true or false value it puts the answer into the variable on the left. This is the same variable as the one the right hand side. So bool_value will be the opposite of what it was before. In other words, if the variable bool_value was true before this line then it will be false after it. Likewise, if it was false before then it will be true after. Test it out with this code:
var bool_value = true;
document.write( bool_value + "<BR>" );
bool_value = !bool_value;
document.write( bool_value );
You should find that it writes true the first time and false the second time. Change the first line from true to false. Now rerun your script. It should be the other way round this time: it writes false the first time and true the second time.

If you don't fully understand all this boolean flipping, then don't worry - it's not crucial, so you can just move on!


Javascript Switch Statements

Sometimes, you'll have more than one value to check for your variables. You can do the checking with a lot of if ... else statements. Or you can use something called a switch statement. Here's an example:
var age = 17;
switch (age) {
case 17:
document.write("under 18");
break;
case 24:
document.write("over 18");
break;
default:
document.write("can't tell");
break;
}
In this example, we've set up a variable called age. We've then stored a value of 17 in the age variable. The switch statement examines what this value is. If it's the case that age hold a value of 17 then its code gets executed. The break keyword is for escaping the switch statement. If you miss it out Javascript will continue downwards and assume all your other cases are true, thus executing the rest of the case code. If none of your cases apply, a default value can be added.

But note the syntax for the switch statement. The word switch is lowercase. After this, you have a pair of round brackets. Inside the round brackets you type a variable name or add a condition to test. This will be evaluated to either true or false, depending on which case matches. Javascript will look at your list of cases and try to find a match. If it finds one, it executes that code. If it doesn't find one then the default option is executed. Note where all the curly brackets and colons are. You have a pair of curly brackets for the entire switch statement. You have a colon after each case.
However, switch statements in Javascript are not very useful as they don't allow you to test a range of values very easily, or at all. If you were checking for age ranges you want to check things like 18 to 30, 31 to 50, etc. Javascript switch statements don't allow you to do this, so you'd have to have one case for each age - a lot of cases, in other words. They can be useful in limited situations, though, so they're worth knowing about.

Javascript Programming Loops

One programming tool common to all languages is the loop. Normally, a programme is executed from top to bottom, with each line of code getting processed in turn. If you want to go back up and not down, you can use a loop. Loops are a great way to execute lines of code again and again. There are many reasons why you want to do this. But take the following sum as an example:
var total;
total = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10;
The code above just adds up the numbers 1 to 10. Which is fine if you only have 10 numbers. But supposed you have a 100 numbers, or 1000. You can't really type them all out. With a loop, though, you can add up a 1000, 10000 numbers, in just a few lines of code. The most common type a loop is called a for loop.

For Loops

For loops (lowercase "f") are structured like this:
The structure of a Javascript for loop
So you start with the word for. After a space you have a pair of round brackets. In between the round brackets you need three things, separated by semicolons: a start value for your loop, some way for the loop to end, and a way to get from one to the other, which is known as the increment value. Next come a pair of curly brackets. The code you want to execute repeatedly goes between the curly brackets. Here's a for loop that adds up the numbers 1 to 10. Try it out by creating a web page from the template in a previous section.
Javascript for loop used to add numbers
The first thing to notice here is that we're setting up variables to hold the start value of the loop and the end value. Loops are designed to go round and around a set number of times. You have to tell Javascript how many times you want to go round. So you need a starting value, and an end value. There are many ways to set an end value, but here we're saying, "Keep going round in a loop until the start value is no longer less than the end value." But how does the loop know that the start value is less than the end value? It knows because we've set an increment value. It's this:
start_value++
This is a shorthand way of saying "add 1 to the start_value variable". It's called incrementing a variable. The longhand way to increment a variable is this:
start_value = start_value + 1
If you do the calculation on the right hand side of the equal sign first, the line above will make more sense. Javascript will look at what's currently in the start_value variable, and then add 1 to it. Once it's done that it will place the result into the variable on the left of the equal sign, erasing its contents and thus setting a new value. The result is that the start_value variable keeps increasing by 1 each time round the loop.
You can also take 1 away from numbers with this:
start_value--
Two minus signs after a variable are called the decrement operator. They deduct 1 from whatever is in the variable. It is the same as saying this:
start_value = start_value - 1
To recap, the start value of the loop is whatever number we have put in the start_value variable; the end condition is when the start_value is no longer less than whatever value we have put in theend_value variable; and the way we get from one to the other is by incrementing the start_valuevariable.
Now have a look at what's in the curly brackets of the loop:
answer = answer + start_value;
This is the whole point of having a loop - to run some code over and over again.
We want to add up the numbers 1 to 10. So, again, do the calculation to the right of the equal sign first. Javascript will look at whatever value is currently held in the answer variable. The first time round the loop this will be zero. (It's zero because we set it that way at the top of the code.) Add 1 to zero to get an answer of 1. This is then stored in the variable to the left of the equal sign. This is the answer variable again. The answer variable will have its contents erased and the new value (1) placed inside of it.
Now, because we're incrementing the start_value variable each time round the loop, its value keeps changing. So the second time round the loop the values will be these:
Javascript loop values - first time round the loop
So we're adding 1 + 2 on the right of the equal sign. The answer ( 3) then gets stored to the left of the equal sign. Which means the third time round the loop the values will be these (remember: do the calculations to the right of the equal sign first, and then store the result to the left):
Javascript loop values - second time round the loop
And the fourth time round the loop the values will be:
Javascript loop values - third time round the loop
The start_value keeps going up by 1 each time round. It's getting towards the correct answer! Have a look at the fifth time round the loop:
Javascript loop values - fourth time round the loop
The final line of our code just writes out the answer. To get a better idea of what's going on, add this document.write inside of the loop's curly brackets:
answer = answer + start_value;
document.write( "answer= " + answer + " start value = " + start_value + "<BR>");
When you run then code you should see the following in the browser:
Output of Javascript loop code
By then end, then, answer is 55. We've went 10 times round the loop, adding up each time round.

Exercise
Use a for loop to print out the numbers 1 to 20.
Exercise
Use a for loop to print out the odd numbers from 1 to 20. (You'll need Modulus for this. And an IF Statement.) Your for loop should look like this:
for ( start_value; start_value < end_value; start_value++ ) {
if ( ) {
document.write("answer= " + start_value + "<BR>");
}
}
Obviously, you'll need something between the round brackets of your IF Statement. But what?

Common end values

Another common end value for loops is to get the length of something, the length of a string of text, for example, or the length of an array (you'll learn about arrays in a later section). In the code below, notice how we're using length:
var start_value = 1;
var some_string = "ABCDEFGH";
for ( start_value; start_value < some_string.length; start_value++ ) {
}
The length method is available to all strings and tells you how many characters a string of text has. We're looping round while the start value is less than the length of the some_string. As soon as the start value goes above the length of the string the loop will end.
But we'll explain the end value for loops whenever we meet them, so try not to worry about them too much.

Javascript while loops

While loops (lowercase "w") are another programming tool you can add to your armoury. Here's the structure of a while loop:
while ( condition_to_test ) {
}
Instead of the word "for" this time type while. After a space, you type a pair of round brackets. Inside of the round brackets you need a condition to test. This will be evaluated to either true or false. While your conditions is still true the loop will go round and round. When it's false, the loop will end. Take this code as an example:
var counter = 1;
var answer = 0;
while (counter < 11) {
answer = answer + counter;
counter++;
}
document.write("answer= " + answer);
Here, we have two variables, one called counter and the other, like before, called answer. Inside of the round brackets of while, we have this:
counter < 11
This will be evaluated to true or false each time round the loop. It says, "while counter is less than 11 keep looping".
To execute some code you again need a pair of curly brackets. Inside of the curly brackets, we have this:
answer = answer + counter;
counter++;
Again, we want to add up the numbers 1 to 10. We're doing it the same as before. This time we're adding up whatever is in the answer variable and whatever is in the counter variable. We need to move the counter on by 1, though, each time round the loop. Otherwise the loop would never end. The second line, then, increments the counter variable:
counter++;
The second time round the loop the counter variable will be 2. That's still less than 11 so the loop continues for a third time. When the counter advances to 11 the condition between the round brackets becomes false, so the loop will end.
While loops are a lot easier to use than for loops. Which one you use depends on the situation. But it's nice to master both. So try these two exercises:

Exercise
Use a while loop to add up the numbers 1 to 20.
Exercise
Use a while loop to print out the even number from 1 to 20. (You'll need Modulus for this. And an IF Statement.)

Comments