Overview

JavaScript is a client side programming language designed to give life to the web. JavaScript is interpreted on the fly by the clients browser. Different browsers handle some elements of JavaScript differently, so sometimes, cross browser coding is necessary. Below, you will find a simple guide for programmers as an introduction to JavaScript. Those who have programmed in C++, Java or C# should have little difficulty in making the transition.

Basic Language Features

Conditions

JavaScript supports the use of if...else structures and switch statements. The logical operators used are &&(AND), ||(OR), and !(NOT). Also, the use of == is for comparison, while = is for assignment. if(condition){ ...true code... } else{ ...false code... } switch(variable){ case value: code; break; case value: code; break; default: code;

Iteration (skip for CS2)

JavaScript supports the use of for, while and do¡Kwhile structures. In addition, there exists a for each loop. The format for each of the loops are as follows: for(var x; x<value; x++{code} while(x<value){code} do{code}while(x<value); for(var x in array){code}


JavaScript vs. Java


Below you will find a table comparing many of the basic commands/ideas from Java and JavaScript. This table will help JavaScript programmers see some basic differences between the two languages.
JavaScriptJava
Conditions if(condition)
code
else
code
if(condition)
code
else
code
For Loop for(var x=0; x<5; x++) for(int x=0; x<5; x++)
While Loop while(condition) while(condition)
do...while do{...}while(condition); do{...}while(condition);

Conditions

Basic Conditions

A conditional statement is one that can choose different courses of action based on a condition that can evaluate to true or false. The most common form of a condition is the if…else structure, but we will also look at switch statements.

We will begin with the standard if structure. Let’s say that we are going to build a simple guessing game in which the computer generates a random number between 1 and 100 and the user needs to guess that number. The first step would be to create a condition that checks if the user correctly guessed the number. A standard if structure checks if a condition is true. If so, the if block executes. So, we will check the user guess, called guess, against the number, called number. The code is as follows:
if(guess == number){ window.alert(“You got it!!”); }
Note the use of '==' in the condition. A single equals sign (=) is used for assignment. A double equals sign (==) is used for comparison. Using an assignment operator in place of a comparison operator will yield unpredictable results. Other comparison operators include >, <, >=, <=, and !=.

If the guess is correct, we will send a message stating that they were correct. However, if the guess is incorrect, we should provide feedback to that as well. To do this we use an if...else structure. In an if else structure, the two blocks of code are mutually exclusive (only one can run). If the condition is true, the if block runs. If the condition is false, the else block runs. In our guessing game example, if the guess is correct, say so, otherwise (else), tell them they are incorrect.
if(guess == number){ window.alert("CORRECT!"); } else{ window.alert("SORRY! That is not right."); }
Note that both the if and else code blocks are enclosed in curly braces {}. This denotes where each path starts and ends.

Sometimes, conditions can be more complicated. For example, if we ask a user to enter a word that starts with a letter between A and G, we have to do a little more work. Due to our math backgrounds, many of us would write this condition in the following form: if ("A" < name < "G")
However, the computer cannot translate this statement as the computer can only process ONE comparison operator at a time. So, to make the computer understand, we would have to break this into two statments "A"<name AND name<"G". The use of the word AND is the key here. In programming conditions, AND is represented by the symbol &&. So, the resulting condition would be as follows: if("A"<name && name<"G")
For an AND statement to be true, both parts must be true. There is also an operator for the word OR. That operator is ||. For an OR statement to be true, at least one of the parts must be true. Finally, we can negate conditions using the NOT (!) operator. The NOT operator reverses the truth value of a statement. Finally, a good programming vocab word is inclusive. The way the current questions is asked and coded, the user cannot succeed with a word that starts with A or G, just letters between them. Had we been asked for a letter between A and G, inclusive, that means that A and G are included in the successful results. The only change is that the comparison operators would be <= instead of <.
Nested Conditions
Computer Science books often like to make a big deal about nested conditions (a condition inside another condition). I don't believe this to be a challenge. If we know that within the brackets of an if or else case we can write any valid JavaScript code, and another condition is valid code, then we should be able to do it. Here is an example: if(username=="open"){ if(password=="sesame"){ window.alert("You may enter."); } else{ window.alert("Your password is incorrect."); } } else{ window.alert("Your username is incorrect."); }
That second conditional is valid JavaScript code so it can be placed inside either the if or else section without any issues. Just be careful of opening and closing braces and use indentation in your code to make it readable.

Sometimes, there is a need for a variety of mutually exclusive options (like on a menu). In cases like these, we typically end up nesting several conditionals inside the elses of the statements. It may look something like this:
if(option==1){ window.alert("you chose #1."); } else{ if(option==2){ window.alert("you chose #2."); } else{ if(option==3){ window.alert("you chose #3."); } else{ window.alert("you did not choose a valid option."); } } } This type of nested conditions can often be more easily written in an else...if chain. The above code would look as follows: if(option==1){ window.alert("you chose #1."); } else if(option==2){ window.alert("you chose #2."); } else if(option==3){ window.alert("you chose #3."); } else{ window.alert("you did not choose a valid option."); }

Loops/Iteration

Loop Basics

It is often necessary to repeat certain blocks of code for a specified(or unspecified) number of times. We use a control structure known as a loop to accomplish this. Every loop has four basic parts:

  1. Loop control variable declaration/initialization
  2. Loop condition
  3. Control variable alteration/reassignment
  4. Loop body(statements to be repeated)

Loops come in two basic varieties:


Regardless of whether you loop is pre or post test, it also has another type of classification: counting or sentinal. Counting loops are set to execute a certain number of times. Loops that depend on user input are called sentinal loops, and will execute as many times as necessary until the user enters a predefined value.

JavaScript also has two loop keywords that can help control the flow of the loop. Those words are break and continue. Break will immediately send control to the code following the loop. Continue sends control immediately to the top of the loop.

For Loops

A for loop, like any loop has 4 parts: the loop control variable start value, condition, code to be executed and an alteration of the control variable. “for” loops are popular because the combine 3 of these four items into one line. Here is an example of a for loop:
for(var x=0; x<5; x+=1){ code }
This is read, for the variable x starting with a value of 0 and as long as x is less than 5, execute the code and increment x by 1 each time.

So, to print 5 hello messages, we would write:
for(var x=1; x<=5; x+=1){ alert(“Hello”); }

While Loops

A while loop is a pretest iterative structure that can be used as a counting or sentinal loop. In general, a while loop looks like this:
<control var intitialization> while(<loop condition>) { <loop body> <control var alteration> }

As a counting loop, counting from 1 to 10, an example of a while loop might look like this:
var count=1; while(count<=10) { document.write(x+"<br/>"); count++; }

A sentinal loop is a loop that continues until a certain value is input by the user. For example, we might ask a user to enter names of people to invite to a party. If we first started by asking how many people they wanted to invite, we could run the loop as a counting loop (for). However, if don't want to ask for a number first, we can run the loop infinitely until a pre-determined value is input. In this case, we could use the value "quit". This way, we read all of the user input values and the loop will terminate when they enter "quit". In the case of a sentinal loop, the user input serves as control variable alteration. We also need to initlialize the control variable with input. This first read is called a priming read. var guests=[]; var input=window.prompt("Enter a guests name...(type quit to exit)"); //priming read while(input!="quit"){ guests.push(input); //places input at the end of guests input=window.prompt("Enter a guests name...(type quit to exit)"); //control var alteration } document.write(guests);

From here, it is a small step to making a while loop a data verification loop. A data verification loop is used to make sure that user input is within an accepted range and does not let the program continue until it is. Similar to a sentinal loop, both the initialization and alteration are handled through input commands. In the example below, program execution loops until the user enters a valid value between 1 and 10. When writing data verification loops, the easiest way to write the condition is to write the desired result, and then negate the entire thing. var input=window.prompt("Enter a number between 1 and 10, inclusive:"); while(!(input>=1 && input <=10)){ input=window.prompt("Enter a number between 1 and 10, inclusive:"); } //continue with program

do...while Loops

A do...while loop is a posttest iterative structure that can be used as a counting or sentinal loop. In general, a do...while loop looks like this:
<control var intitialization> do{ <loop body> <control var alteration> (while(<loop condition>); Note the semicolon at the end of the condition!

As a counting loop, counting from 1 to 10, an example of a do...while loop might look like this:
var count=1; do { document.write(x+"<br/>"); count++; }while(count<=1);

Do...while loops can also be used as sentinal loops. Because they are postest, they often do not need the priming read that their while loop counterpart requires.
var guests=[]; var input; do{ input=window.prompt("Enter a guests name...(type quit to exit)"); //control var alteration guests.push(input); //places input at the end of guests }while(input!="quit"); document.write(guests); Notice, however that in this example, the word 'quit' will be a member of the array and would need to be removed before processing or printing.

The best use for a do...while loop however is data verification. The lack of need of the priming read makes it a more efficient algorithm. var input; do{ input=window.prompt("Enter a number between 1 and 10, inclusive:"); }while(!(input>=1 && input <=10)); //continue with program

Loop Choices

So many loops...so little time. So, how do we know when to use each loop. In reality, you can use any of the three (for, while, do...while) for a counting loop and either while/do...while for sentinal and data verification. However, to be the most efficient, we typically stick to the following: Using the above guideline will allow each loop to use its strengths and be the most efficient code.