Return to Course Content Home

JavaScript Statements



Recommended Reading

The JavaScript Tutorial at https://www.w3schools.com/js/default.jsp

Script Location

So, you've seen some commands when we walked through the Objects, but let's officially take care of how to write them.

As you've seen before, you can include JavaScript directly in your HTML page in the <body> section. All you need to do is use the <script type="text/javascript"></script> tagset within you code where you want the output of the JavaScript to be.

<html>
<body>
<script type="text/javascript">
   document.write("Hello World!");
</script>
</body>

If you placed this in your you code, you'd see the classic

Hello World!

In your browser window. Remember, the "document" object above was covered in the earlier section. You could have also written

window.document.write("Hello World!");

because the window object is implied in the first example.

If scripts can be placed in the <body> section, where else can they be located? A common place is the <head> section of your HTML. You place script in the <head> section because that JavaScript located in the <body> section will be executed when the page loads. After all, these script actually generate the content shown on your page. If you place your scripts in the <head> section, they are executed when they are called or when an event is triggered.

You can also reference JavaScript in an external file by using the:

<script src="external_script.js"></script>

tags. Replace the "external_script.js" with the name of your JavaScript file.

What is a JavaScript Statement?

JavaScript is one or more JavaScript statements. A JavaScript Statement is a command to the browser. This command can be to write text to the browser, to open a window or to modify existing text in the browser. By convention, JavaScript statements end with a semi-colon, but it is not required.

Like Java, JavaScript can be grouped with brackets {}s, and you can comment it out using Java type comments, either the /* */ pair or double slashes (//) at the beginning of a line.

Because the results of JavaScript are inserted into your HTML document at the location they occur in your code, you place your JavaScript where you want to see the results of its execution.

The good news is that JavaScript syntax is very much like Java, the bad news is that the real key part of JavaScript isn't knowing the statement syntax, it is understanding how to access the DOM (HTML Document Model), which we'll see later on.

Variables

Here is where we see a significant departure from the Java style of code. Unlike Java which requires typed variables like:

int x;
String y;

JavaScript lets you declare variables with the "var" statement, and you don't have to specify the type of variable you are using. Partially this is because there are only really three types of data, doubles, Strings and booleans. You can just declare variables for later use:

var foo;
var bar;

Or you can initialize them as well:

var foo=5;
var bar="Hello World!";

Once a variable has been declared, you can change its value at any time. There are no "final" variables in JavaScript.

foo=6;
bar="Goodbye Cruel World...";

JavaScript Operators

Logical

JavaScript has the same logical operators as Java, except type conversions are freely made. What this means is that if you have something like this:

var foo=10;

then you can do the following, which you can't do in Java

if (foo==10) document.write("foo==10");
if (foo=="10") document.write("foo==\"10\"");

Both of the above statements will evaluate to true. Conversions between Strings and Numbers is done automatically. If you want to test for equality, but don't want automatic conversion, use the === operator

if (foo==="10") document.write("foo===\"10\"");

The above will not evaluate to true, as 10 and "10" are not the same type.

Arithmetic

JavaScript has the same Arithmetic Operators as Java, including the +=, -= and so on styles.

Even though the String class has the concat() method, you can join Strings with the "+" operator just like in Java. If one of the values is not a String, it will be converted to a String and then concatenated.

var Foo="Hello" + " " + "World" + "!";

will evaluate to

Hello World!

If you try to use the "+" operator to add a String and a Number, the Number will be converted to a String, and then concatenated.

10 + 2 will evaluate to 12
"10" + 2 will evaluate to 102
10 + "2" will evaluate to 102
"10" + "2" will evaluate to 102

If Statements

if, if-then, if-then-else statements are the same as in Java

Switch statements

switch-case statements are the same as in Java

For Loops

for loops are the same as in Java, although they don't include the new for loops that are in Java 6. This includes the use of break; and continue; statements within the loop.

JavaScript also adds a different form of a for loop

for (var in object-list) {
 // do stuff
}

So you could do something like

var item;
var niftyWords = new Array();
niftyWords[0] = "foo";
niftyWords[1] = "bar";
niftyWords[2] = "baz";
niftyWords[3] = "bing";
  
for (item in niftyWords) {
 document.write(niftyWords[item] + "<br />");
}

Note that the var item is not bound to the actual value in the array, but instead the array index.

While Loops

while loops are the same as in Java. This includes the use of break; and continue; statements within the loop.

try...catch and throws

Yes, JavaScript even has try...catch statements, although not heavily types as in Java. The errors can be generated by just about anything (misspelling, bad variable name, etc). The general format is

try {
 // your code here
} catch (err) {
 //handle error, you can get the description of the error with err.description
}

If you want to throw an exception (within a function for example), you just call throw() with an error message.

throw("Ouch, that hurt");

 

onerror Event

The onerror event is a different way to catch errors. To use this method, you first create a function to handle errors, then pass the function name to the onerror variable.

function oops(msg) {
 // deal with the error
}
  
onerror=oops;

 

Functions

Functions are normally placed in the <head> section of your code, or included by using an external .js file. When you place a function in the <head> section, you know it is loaded before anything happens in the <body> of your page.

Functions are defined very similarly to Java, except of course there are no types for the variables:

function functionName(arg1, arg2, arg3, ... argN) {
// your function code
}

As with java, a return statement is used to return values, or exit the function with no return value if none specified. So to add two numbers:

function myAdd(arg1, arg2) {
 return arg1 + arg2;
}

As with Java, you can declare new variables within a function, but their scope is limited to that function, and they will be "gone" when the function returns.

Popup Boxes

JavaScript doesn't have Swing, but it does have the ability to create some popup windows that can be used to show bit of information or get some info from the users. There are three types

Popup type
How called
What it does
Alert Box alert("your message") Brings a box with your message and a single OK button for the user to acknowledge the message
Confirm Box confirm("your message") Brings a box with your message and an OK and CANCEL button for the user to confirm or cancel the action described by the message. Returns true for OK and false for CANCEL
Prompt Box prompt("your question", "default value") Similar to a Confirm box, only there will be a text field that the user can enter data. The data entered is returned from the prompt() call, or null if CANCEL was selected.