Understanding and using JavaScript statements

Moving through the eleven statements supported by JavaScript

1 2 Page 2
Page 2 of 2

The next example shows how to use the new statement to create an instance of a user-defined object. The object function -- the thing that defines the object -- is also shown. This simplistic object assigns the string passed to it to a name property. That property is displayed in an alert box, using the syntax alert (newObj.name).

newObj = new myObject ("Gordon"); alert (newObj.name);

function myObject (Param1) { this.name = Param1; return (this); }

Back to index


The return statement is used to mark the end of a function. When JavaScript encounters the return statement, it "returns" to that spot immediately following the call to the function. The return statement can be used with and without a return value.

  • If a value is included with the return statement, then the function returns that value.

  • If no value is included with the return statement, then the function returns a null (nothing).

The return statement may not be used outside of a function. JavaScript reports an error if you attempt to use return outside a function. Here are two examples of return, with and without a value:

function myFunc() { var OutString = "This is a test"; return (OutString); }

function myFunc() { OutString = "This is a test"; return; }

It is common JavaScript practice to omit the parentheses surrounding the return value. I use the parentheses in deference to traditional C programming practice. Feel free to drop the parentheses.

When using return more than once in a function, be sure to use it in the same way each time, otherwise JavaScript will display a warning message. For instance, suppose your function tests if a value passed to it is less than 5. You want the function to return differently depending on whether this value is less than or more than 5. Here are the wrong and right ways to do it. Note that only one return statement returns a value.

First, the wrong way:

function testMe (Val) {
    if (Val < 5)
        return (true);

Now, the right way:

function testMe (Val) {
    if (Val < 5)
        return (true);
        return (false);

Back to index


The this keyword (it's not really a statement) refers to the current object and is shorthand for using the formal name of the object. It is typically used in one of three ways:

  • To refer to the current form or control in an event handler (such as onClick or onSubmit)
  • To define a new property in a user-defined object

You can use the this operator with or without an object name, as in this or this.object. The object name helps to disambiguate what "this" means. For instance, suppose you want to return the whole form with an onClick event handler. You'd do it this way, to tell JavaScript you want the entire form object:

<INPUT TYPE="button" NAME="button" VALUE="Click" onClick="test(this.form)" >

Using just the this keyword, the onClick event handler passes only the button.

<INPUT TYPE="button" NAME="button" VALUE="Click" onClick="test(this)" >

Back to index


The var statement is usedis used to explicitly declare a variable. You may also define a value for the variable at the same time as you declare it, but this is not necessary. The var statement also sets the "scope" of a variable when the variable is defined inside a function. More about this in a bit.

The basic syntax is:

var VariableName;


var VariableName = value;
  • VariableName is the name of the variable you wish to use.
  • value is the value you want to assign to the variable.

In the first example, the variable VariableName is declared (allocated in memory), but its contents remain empty. In the second example, the VariableName variable is declared, and a value is assigned to it at the same time.

Used outside of a user-defined function, both of these do exactly the same thing:

var VariableName = "value";
VariableName = "value";

Both create a global variable (the variable is considered "global in scope") -- that is, a variable that can be accessed from any function in any window or frame that is currently loaded. For example, the following works because MyVar is declared outside the function and is therefore global (again, the var statement is optional here):

var MyVar = 5;
// or MyVar = 5;
function testVariable () {
    alert (MyVar);

Conversely, an error will occur if the MyVar variable is assigned in another function with the var statement, making it local to that function. The variable is considered "local in scope."

function defineVariable() {
    var MyVar = 5;
function testVariable () {
    alert (MyVar);

You also use the var statement if you've defined a global variable (see above) and want to use a separate, local variable of the same name in a function. In this example, MyVar is declared globally outside the testVariable() function. It is again defined inside the testVariable() function, this time with the var keyword to make it local. When this test is run, JavaScript displays 10 in the first alert box in the testVariable() function, and 5 in the anotherTest() function.

var MyVar = 5; function testVariable () { var MyVar = 10 alert ("testVariable function: " + MyVar); anotherTest(); }

function anotherTest() { alert ("anotherTest function: " + MyVar);

Back to index


The while statement sets up a unique repeating loop that causes the script to repeat a given set of instructions. The looping continues as long as the expression in the while statement is true. When the while statement proves false, the loop is broken and the script continues. Any JavaScript code inside the while statement block -- defined by using the { and } characters -- is considered part of the loop and is repeated. The syntax of the while statement is:

while (Expression)  {
    // stuff to repeat

In the following example, the while loop is repeated for a total of ten times. With each iteration of the loop, JavaScript prints text to the screen.

while (Count <10) {
    document.write ("Iteration: "+Count+"<BR>")

Here's how the this example works. First, the Count variable is set to 0. This is the initial value that will be compared in the while expression, which is Count <10. Count starts at 0. With each iteration of the loop, text is printed to the screen, and the Count variable is increased by 1.

The first ten times the loop is repeated Count <10 is true, so the loop continues. After the tenth trip, the Count variable contains the number 10, and the while expression proves false. The loop is broken, and JavaScript skips to the end of the while statement block (that portion after the } character).

The while loop is what is known as an entry loop. The test expression appears at the beginning of the loop structure. The contents of a while loop may never be executed, depending on the outcome of the test expression. For example,

Response = prompt ("Please enter a number greater than 1");
Count = 1;
while (Count <= Response) {
    document.write ("Count: "+ Count + "<BR>");

In this JavaScript example, a prompt method asks you to enter a number greater than 1. This number is then used to control the iterations of a while loop. If you type 5, for example, the loop will repeat five times. The loop continues as long as the while expression -- Count<=Response -- remains true. Notice that the Count variable starts at 1. In this way, if you enter a 0 in response to the prompt, the while loop fails, and the instructions inside the while loop block are never executed (because 1<=0 is false).

While loops are particularly handy for insisting that the user enters valid data. Here's a simplified version of a data validator (try the example to see how it works):

Response = "";
while ((Response == "") || (Response == "<undefined>")){
    Response=prompt ("Please enter your name", "");
if (Response != null)
    alert ("Hello, " + Response);

The first step is to assign an empty string to the Response variable. Since Response is empty, the while expression evaluated to true, and the prompt dialog appears, asking for the user's name. Since the Response string is empty, the prompt dialog appears within the text box. The script will not allow you to proceed unless you either click the Cancel button or type some text.

Notice the if test. Should the user click on Cancel, the value returned from the prompt dialog is null. Should the value be other than null, the script assumes it's a valid name, and an alert box greeting the user is displayed.

Back to index


The with statement is designed as a time and space saver. You use it to help cut down on extraneous keystrokes when writing a JavaScript program. The with statement is typically used with the built-in Math object, as it requires you to specify the name of the object when accessing any of its properties, such as:

alert (Math.PI);
alert (Math.round(1234.5678));

The syntax for with is:

with (object) {
  • object is the object you want to use
  • statements are one or more statements you want to execute using the object as the default

By using the with statement, you can cut out the references to the Math object, as it is implied. Be sure to enclose all the property constructions you wish to associate with the with statement inside { and } characters. These characters define the with statement block and are mandatory.

with (Math) {
    alert (PI);
    alert (round(1234.5678));

You are not limited to using the with statement to just Math objects. You can use it with almost any object, even objects you define yourself. For example, suppose you want to perform several actions on the document.forms[0].textbox object -- a textbox control in the first form of the document. There's no need to define this long and drawn out object name; you can use the with statement instead.

function test () {
    with (document.forms[0].textbox1) {
        alert (name);
        alert (value);

Because you've used the name and value properties in a with statement block, JavaScript automatically assumes they refer to the object specified in the with expression, in this case document.forms[0].textbox1.

Back to index


Statements are the glue that holds any JavaScript program together. While JavaScript doesn't have as many statements as some other languages, including its "big brother" Java, the variety of statements it does offer provides ample opportunity for programmers to create almost any application they can think up.

Gordon McComb is an author, consultant, and lecturer. He has written 50 books and over a thousand magazine articles during his 20 years as a professional writer. More than a million copies of his books are in print. Gordon also writes a weekly syndicated newspaper column on computers, reaching several million readers worldwide. Gordon's latest book is The JavaScript Sourcebook, available from Wiley Computer Publishing.

Learn more about this topic

This story, "Understanding and using JavaScript statements" was originally published by JavaWorld.

Copyright © 1996 IDG Communications, Inc.

1 2 Page 2
Page 2 of 2